Go 1.11은 지원이 종료되었으며 2026년 1월 31일에 지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Go 1.11 애플리케이션을 배포할 수 없습니다. 기존 Go 1.11 애플리케이션은 지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다. 지원되는 최신 Go 버전으로 마이그레이션하는 것이 좋습니다.
// Create a key with a key name "asalieri".key:=datastore.NewKey(ctx,// context.Context"Employee",// Kind"asalieri",// String ID; empty means no string ID0,// Integer ID; if 0, generate automatically. Ignored if string ID specified.nil,// Parent Key; nil means no parent)
Datastore에서 숫자 ID를 자동으로 할당하도록 하려면 비어 있는 stringID 인수를 사용합니다.
// Create a key such as Employee:8261.key:=datastore.NewKey(ctx,"Employee","",0,nil)// This is equivalent:key=datastore.NewIncompleteKey(ctx,"Employee",nil)
식별자 할당
2가지 자동 ID 정책을 사용하여 자동 ID를 생성하도록 Datastore를 구성할 수 있습니다.
default 정책은 거의 균일하게 분포된 미사용 ID의 임의 시퀀스를 생성합니다. 각 ID는 최대 16자리 숫자입니다.
legacy 정책은 연속되지 않는 더 작은 정수 ID 시퀀스를 만듭니다.
사용자에게 항목 ID를 표시하거나 항목 ID의 순서를 결정하려는 경우 수동으로 할당하는 것이 좋습니다.
상위 경로 사용
Cloud Datastore의 항목은 파일 시스템의 디렉토리 구조와 유사한 계층 구조 형식의 공간을 형성합니다. 항목을 만들 때 선택적으로 다른 항목을 상위 요소로 지정할 수 있으며, 새 항목은 상위 항목의 하위 요소가 됩니다. 파일 시스템과 달리 상위 항목이 실제로 존재할 필요는 없습니다. 상위 요소가 없는 항목은 루트 항목입니다. 항목과 상위 요소 간의 연결은 영구적이며 항목이 생성되면 변경할 수 없습니다. Cloud Datastore는 상위 요소가 동일한 2개의 항목 또는 2개의 루트 항목(상위 요소가 없는 항목)에 동일한 숫자 ID를 할당하지 않습니다.
항목의 상위 요소, 상위 요소의 상위 요소 등은 재귀적으로 해당 항목의 상위가 되고, 항목의 하위 요소, 하위 요소의 하위 요소 등은 해당 항목의 하위가 됩니다. 루트 항목과 그 하위에 있는 모든 항목은 동일한 항목 그룹에 속합니다. 루트 항목에서 시작하여 상위 요소에서 하위 요소로 진행되고 지정된 항목까지 이어지는 항목의 시퀀스를 해당 항목의 상위 경로라고 합니다. 항목을 식별하는 전체 키는 상위 경로를 지정하고 항목 자체로 종료되는 종류-식별자 쌍의 시퀀스로 구성됩니다.
루트 항목의 경우 상위 경로는 비어 있으며 키는 항목의 고유한 종류 및 식별자로만 구성됩니다.
[Person:GreatGrandpa]
이 개념은 다음 다이어그램에서 설명합니다.
항목의 상위 항목을 지정하려면 datastore.NewKey에 대해 parent 인수를 사용합니다. 이 인수의 값은 상위 항목의 키여야 합니다. 다음 예시에서는 Address 종류의 항목을 만들고 Employee 항목을 해당 상위 항목으로 지정합니다.
// Create Employee entityemployee:=&Employee{/* ... */}employeeKey,err:=datastore.Put(ctx,datastore.NewIncompleteKey(ctx,"Employee",nil),employee)// Use Employee as Address entity's parent// and save Address entity to datastoreaddress:=&Address{/* ... */}addressKey:=datastore.NewIncompleteKey(ctx,"Address",employeeKey)_,err=datastore.Put(ctx,addressKey,address)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 2025-09-04(UTC)"],[[["\u003cp\u003eThis API supports first-generation runtimes and can be used when upgrading to corresponding second-generation runtimes, with a migration guide available for those updating to the App Engine Go 1.12+ runtime.\u003c/p\u003e\n"],["\u003cp\u003eEach entity in Datastore is uniquely identified by a key, which includes the entity's namespace, kind, an optional ancestor path, and an identifier that can either be a key name string or an integer numeric ID.\u003c/p\u003e\n"],["\u003cp\u003eIdentifiers for entities can be assigned either by specifying a key name string or by allowing Datastore to automatically assign an integer numeric ID.\u003c/p\u003e\n"],["\u003cp\u003eDatastore offers two auto ID policies, 'default' and 'legacy', to generate automatic IDs, and manual allocation is the preferred method for applications that need to display or depend on entity ID order.\u003c/p\u003e\n"],["\u003cp\u003eEntities in Cloud Datastore can form a hierarchy with parent-child relationships, where the ancestor path defines the lineage of an entity from a root entity, and the relationship between an entity and its parent is permanent.\u003c/p\u003e\n"]]],[],null,["# Creating and Using Entity Keys\n\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| go\n| /services/access). If you are updating to the App Engine Go 1.12+ runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/go-differences) to learn about your migration options for legacy bundled services.\n\n\u003cbr /\u003e\n\nEach entity in Datastore has a *key* that uniquely identifies it. The key consists of the following components:\n\n- The *namespace* of the entity, which allows for [multitenancy](/appengine/docs/legacy/standard/go111/multitenancy)\n- The [*kind*](#Kinds_and_identifiers) of the entity, which categorizes it for the purpose of Datastore queries\n- An optional [*ancestor path*](#Ancestor_paths) locating the entity within the Datastore hierarchy.\n- An [*identifier*](#Kinds_and_identifiers) for the individual entity, which can be either\n\n - a *key name* string\n - an integer *numeric ID*\n\nBecause the identifier is part of the entity's key, the identifier is associated\npermanently with the entity and cannot be changed. You assign the identifier in\neither of two ways:\n\n- Specify your own *key name* string for the entity.\n- Let Datastore automatically assign the entity an integer *numeric ID*.\n\n| Don't name a property \"key.\" This name is reserved for a special property used to store the Model key. Though it may work locally, a property named \"key\" will prevent deployment to App Engine.\n\nSpecifying a key name for an entity\n-----------------------------------\n\nTo assign a key name to an entity, provide a non-empty `stringID` argument to\n[`datastore.NewKey`](/appengine/docs/legacy/standard/go/datastore/reference#NewKey): \n\n // Create a key with a key name \"asalieri\".\n key := datastore.NewKey(\n \tctx, // context.Context\n \t\"Employee\", // Kind\n \t\"asalieri\", // String ID; empty means no string ID\n \t0, // Integer ID; if 0, generate automatically. Ignored if string ID specified.\n \tnil, // Parent Key; nil means no parent\n )\n\nTo let Datastore assign a numeric ID automatically, use an empty `stringID` argument: \n\n // Create a key such as Employee:8261.\n key := datastore.NewKey(ctx, \"Employee\", \"\", 0, nil)\n // This is equivalent:\n key = datastore.NewIncompleteKey(ctx, \"Employee\", nil)\n\n### Assigning identifiers\n\nYou can configure Datastore to generate auto IDs using [two different auto id policies](/appengine/docs/legacy/standard/go111/config/appref#app_yaml_Auto_ID_policy):\n\n- The `default` policy generates a random sequence of unused IDs that are approximately uniformly distributed. Each ID can be up to 16 decimal digits long.\n- The `legacy` policy creates a sequence of non-consecutive smaller integer IDs.\n\nIf you want to display the entity IDs to the user, and/or depend upon their order, the best thing to do is use manual allocation.\n| **Note:** Instead of using key name strings or generating numeric IDs automatically, advanced applications may sometimes wish to assign their own numeric IDs manually to the entities they create. Be aware, however, that there is nothing to prevent Datastore from assigning one of your manual numeric IDs to another entity. The only way to avoid such conflicts is to have your application obtain a block of IDs with the [`datastore.AllocateIDs`](/appengine/docs/legacy/standard/go/datastore/reference#AllocateIDs) function. Datastore's automatic ID generator will keep track of IDs that have been allocated with this function and will avoid reusing them for another entity, so you can safely use such IDs without conflict.\n\nUsing ancestor paths\n--------------------\n\nEntities in Cloud Datastore form a hierarchically structured space similar to\nthe directory structure of a file system. When you create an entity, you can\noptionally designate another entity as its *parent;* the new entity is a\n*child* of the parent entity (note that unlike in a file system, the parent\nentity need not actually exist). An entity without a parent is a *root\nentity.* The association between an entity and its parent is permanent, and\ncannot be changed once the entity is created. Cloud Datastore will never assign\nthe same numeric ID to two entities with the same parent, or to two root\nentities (those without a parent).\n\nAn entity's parent, parent's parent, and so on recursively, are its\n*ancestors;* its children, children's children, and so on, are its\n*descendants.* A root entity and all of its descendants belong to\nthe same *entity group.* The sequence of entities beginning with a root\nentity and proceeding from parent to child, leading to a given entity,\nconstitute that entity's *ancestor path.* The complete key identifying\nthe entity consists of a sequence of kind-identifier pairs specifying its\nancestor path and terminating with those of the entity itself: \n\n```\n[Person:GreatGrandpa, Person:Grandpa, Person:Dad, Person:Me]\n```\n\nFor a root entity, the ancestor path is empty and the key consists solely of\nthe entity's own kind and identifier: \n\n```\n[Person:GreatGrandpa]\n```\n\nThis concept is illustrated by the following diagram:\n\n\nTo designate an entity's parent, use the `parent` argument to\n[`datastore.NewKey`](/appengine/docs/legacy/standard/go/datastore/reference#NewKey). The value\nof this argument should be the parent entity's key.. The following example\ncreates an entity of kind `Address` and designates an `Employee` entity as its\nparent: \n\n // Create Employee entity\n employee := &Employee{ /* ... */ }\n employeeKey, err := datastore.Put(ctx, datastore.NewIncompleteKey(ctx, \"Employee\", nil), employee)\n\n // Use Employee as Address entity's parent\n // and save Address entity to datastore\n address := &Address{ /* ... */ }\n addressKey := datastore.NewIncompleteKey(ctx, \"Address\", employeeKey)\n _, err = datastore.Put(ctx, addressKey, address)"]]