Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Cada entidade no Datastore tem uma chave que a identifica de maneira exclusiva. A chave tem os seguintes componentes:
O namespace da entidade, que possibilita a multilocação
O tipo da entidade, que a categoriza para as consultas do Datastore
Um caminho ancestral opcional que localiza a entidade na hierarquia do Datastore.
Um identificador da entidade individual, que pode ser:
uma string de nome da chave;
um código numérico inteiro
Como o identificador é parte da chave da entidade, ele é associado permanentemente à entidade e não pode ser alterado. Atribua o identificador de uma dessas maneiras:
Especifique sua própria string de nome de chave para a entidade.
Deixe o Datastore atribuir automaticamente à entidade um ID numérico inteiro.
Como especificar um nome de chave para uma entidade
Para atribuir um nome de chave a uma entidade, forneça um argumento stringID não vazio para
datastore.NewKey:
// 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)
Para permitir que o Datastore atribua um ID numérico automaticamente, use um argumento stringID vazio:
// Create a key such as Employee:8261.key:=datastore.NewKey(ctx,"Employee","",0,nil)// This is equivalent:key=datastore.NewIncompleteKey(ctx,"Employee",nil)
A política default gera uma sequência aleatória de IDs não utilizados que são aproximadamente distribuídos de maneira uniforme. Cada ID pode ter até 16 dígitos decimais.
A política legacy cria uma sequência de IDs inteiros menores e não consecutivos.
Para exibir os IDs de entidade para o usuário e/ou depender da ordem deles, use a alocação manual.
Como usar caminhos ancestrais
As entidades no Cloud Datastore formam um espaço hierarquicamente estruturado, semelhante à estrutura de diretórios de um sistema de arquivos. Ao criar uma entidade, é possível designar outra entidade como mãe e a nova como filha. Ao contrário do que ocorre em um sistema de arquivos, a entidade mãe não precisa existir de verdade. Uma entidade sem mãe é uma entidade raiz. A associação entre uma entidade e a mãe é permanente e não pode ser alterada depois que a entidade é criada. O Cloud Datastore nunca atribuirá o mesmo ID numérico a duas entidades com a mesma mãe ou a duas entidades raiz (sem mãe).
A mãe de uma entidade, a mãe da mãe, e assim por diante são ancestrais dela. A filha, a filha da filha, e assim por diante são descendentes dela. Uma entidade raiz e todos os descendentes pertencem ao mesmo grupo de entidades. A sequência de entidades começando com uma entidade raiz e prosseguindo de pai para filho, levando a uma determinada entidade, constitui o caminho do ancestral dessa entidade. A chave completa que identifica a entidade consiste em uma sequência de pares de identificadores de tipo que especifica o caminho ancestral e termina com os da própria entidade:
Para uma entidade raiz, o caminho ancestral está vazio, e a chave consiste unicamente no próprio tipo e identificador da entidade:
[Person:GreatGrandpa]
Esse conceito é ilustrado pelo seguinte diagrama:
Para designar o pai de uma entidade, use o argumento parent para
datastore.NewKey. O valor
desse argumento precisa ser a chave da entidade pai. O exemplo a seguir
cria uma entidade do tipo Address e designa uma entidade Employee como
pai:
// 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)
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 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)"]]