Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Cada entidad en Datastore tiene una clave que la identifica de manera única. La clave consta de los siguientes componentes:
El espacio de nombres de la entidad, que permite la función de multiusuario
El tipo de entidad, que la clasifica para realizar consultas de Datastore
Una ruta principal opcional que ubica la entidad dentro de la jerarquía de Datastore
Un identificador de la entidad individual, que puede ser alguna de las siguientes opciones:
una string de nombre de clave
un ID numérico de enteros
Debido a que es parte de la clave de la entidad, el identificador se encuentra asociado de forma permanente a la entidad y no se puede cambiar. El identificador se puede asignar de las siguientes dos maneras:
Especifica tu propia string de nombre de clave para la entidad.
Permite que Datastore asigne de forma automática un ID numérico entero a la entidad.
Especificar un nombre de clave para una entidad
Para asignar un nombre de clave a la entidad, proporciona un argumento stringID no vacío a 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 que Datastore asigne un ID numérico de forma automática, usa un argumento stringID vacío:
// Create a key such as Employee:8261.key:=datastore.NewKey(ctx,"Employee","",0,nil)// This is equivalent:key=datastore.NewIncompleteKey(ctx,"Employee",nil)
La política default genera una secuencia aleatoria de ID sin usar con una distribución bastante uniforme. Cada ID puede tener hasta 16 dígitos decimales.
La política legacy crea una secuencia de ID de números enteros no consecutivos más breves.
Si quieres mostrar al usuario los ID de la entidad o depender de su pedido, lo mejor que puedes hacer es usar la asignación manual.
Usa rutas principales
Las entidades de Cloud Datastore conforman un espacio con estructura jerárquica similar a la estructura de directorios de un sistema de archivos. Cuando creas una entidad, tienes la opción de designar otra entidad como superior, en cuyo caso la nueva entidad es secundaria respecto de la entidad superior (ten en cuenta que, a diferencia de lo que ocurre en un sistema de archivos, no es necesario que efectivamente exista una entidad superior). Las entidades que no tienen una principal se denominan entidades raíz. La asociación entre una entidad secundaria y la entidad superior es permanente, y no puede cambiarse una vez creada la entidad. Cloud Datastore nunca asignará el mismo ID numérico a dos entidades asociadas a la misma entidad superior ni a dos entidades raíz (no asociadas a una entidad superior).
La entidad superior de una entidad determinada, la superior de la superior y así sucesivamente son sus principales. Las entidades secundarias respecto de una entidad determinada, las secundarias de las secundarias y así sucesivamente son sus descendientes. Una entidad raíz y todos sus descendientes pertenecen al mismo grupo de entidad. La secuencia de entidades que comienza con una entidad raíz y sigue de principal a secundaria, hasta llegar a una entidad determinada, constituye la ruta de principal de esa entidad. La clave completa que identifica una entidad consta de una secuencia de pares de tipo-identificador que especifican la ruta de principales y terminan con el tipo y el identificador de la propia entidad:
En el caso de una entidad raíz, la ruta de principales está vacía, y la clave consta solo del tipo y el identificador de la entidad:
[Person:GreatGrandpa]
Este concepto se ilustra en el diagrama siguiente:
Para designar el superior de una entidad, usa el argumento parent en datastore.NewKey. El valor de este argumento debería ser la clave de la entidad principal. En el siguiente ejemplo, se crea una entidad de tipo Address y se designa una entidad Employee como su superior:
// 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 comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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)"]]