Como criar, recuperar, atualizar e excluir entidades
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Os objetos de dados no Datastore são conhecidos como entidades. Cada uma é categorizada
como um tipo específico para fins de consultas. Por
exemplo, se você estiver programando um aplicativo de recursos humanos, poderá representar
cada funcionário com uma entidade do tipo Employee. Observe que os valores de dados
de entidade estão na forma de
propriedades.
Para mais informações sobre entidades, consulte o documento conceitual
Entidades, propriedades e chaves.
Como criar entidades e definir propriedades
Para criar uma nova entidade no Go, gere uma instância de estrutura do Go preenchendo os campos dela e chamando datastore.Put para salvá-la no Datastore. Apenas os campos exportados (que começam com uma letra maiúscula) serão salvos no Datastore. É possível especificar o nome de chave da entidade transmitindo um argumento stringID não vazio para datastore.NewKey.
O exemplo a seguir cria uma entidade do tipo Employee, preenche os
valores da propriedade e a salva no Datastore:
O tipo Employee declara quatro campos para o modelo de dados: FirstName, LastName, HireDate e AttendedHRTraining.
Se você fornecer um nome de chave vazio ou usar datastore.NewIncompleteKey, o Datastore gerará automaticamente um ID numérico para a chave da entidade:
Para recuperar uma entidade identificada por uma determinada chave, transmita o *datastore.Key como um argumento para a função datastore.Get. É possível gerar o *datastore.Key usando a função datastore.NewKey.
O datastore.Get preenche uma instância da estrutura do Go apropriada.
Como atualizar entidades
Para atualizar uma entidade atual, modifique os atributos da estrutura e, em seguida, chame datastore.Put. Os dados substituem a entidade existente. O objeto inteiro é enviado ao Datastore com todas as chamadas para datastore.Put.
Como excluir entidades
Dada a chave de uma entidade, é possível excluir a entidade com a função datastore.Delete:
// A batch put._,err=datastore.PutMulti(ctx,[]*datastore.Key{k1,k2,k3},[]interface{}{e1,e2,e3})// A batch get.varentities=make([]*T,3)err=datastore.GetMulti(ctx,[]*datastore.Key{k1,k2,k3},entities)// A batch delete.err=datastore.DeleteMulti(ctx,[]*datastore.Key{k1,k2,k3})
As operações em lote não alteram os custos. Você será cobrado por todas as chaves em uma operação em lote, independentemente de cada chave existir ou não.
O tamanho das entidades envolvidas em uma operação não afeta o custo.
[[["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 is applicable when upgrading to corresponding second-generation runtimes, but for App Engine Go 1.12+ runtime updates, a migration guide is available for legacy bundled service migration options.\u003c/p\u003e\n"],["\u003cp\u003eDatastore entities, categorized by kind for queries, are created in Go by instantiating a struct, populating its fields, and using \u003ccode\u003edatastore.Put\u003c/code\u003e to save them, with only exported fields being stored.\u003c/p\u003e\n"],["\u003cp\u003eEntities can be retrieved using \u003ccode\u003edatastore.Get\u003c/code\u003e with a \u003ccode\u003e*datastore.Key\u003c/code\u003e and updated by modifying the struct attributes and calling \u003ccode\u003edatastore.Put\u003c/code\u003e, which overwrites existing data.\u003c/p\u003e\n"],["\u003cp\u003eEntities can be deleted using the \u003ccode\u003edatastore.Delete\u003c/code\u003e function with the entity's key and for large-scale deletion, Dataflow is recommended for bulk operations.\u003c/p\u003e\n"],["\u003cp\u003eBatch operations, including \u003ccode\u003edatastore.PutMulti\u003c/code\u003e, \u003ccode\u003edatastore.GetMulti\u003c/code\u003e, and \u003ccode\u003edatastore.DeleteMulti\u003c/code\u003e, allow operations on multiple entities in a single call, however, costs are incurred for each key regardless of its existence, and transactions are recommended for ensuring complete success or failure.\u003c/p\u003e\n"]]],[],null,["# Creating, Retrieving, Updating, and Deleting Entities\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\nData objects in Datastore are known as *entities* , each of which is categorized\nunder a particular *kind* for the purpose of queries. For\ninstance, if you are writing a human resources application you might represent\neach employee with an entity of kind `Employee`. Note that the entity data\nvalues are in the form of\n\n[properties](/appengine/docs/legacy/standard/go111/datastore/entity-property-reference#properties_and_value_types).\n\n\nFor more information about entities, see the concept document\n[Entities, Properties, and Keys](/appengine/docs/legacy/standard/go111/datastore/entities).\n| **Important:** Inefficient data store code can result in unnecessarily high costs! So before you write your code, you should learn about [write costs](/datastore/pricing).\n\nCreating entities and setting properties\n----------------------------------------\n\nIn Go, you create a new entity by constructing an instance of a Go struct, populating its fields, and calling [`datastore.Put`](/appengine/docs/legacy/standard/go/datastore/reference#Put) to save it to Datastore. Only exported fields (beginning with an upper case letter) will be saved to Datastore. You can specify the entity's key name by passing a non-empty `stringID` argument to [`datastore.NewKey`](/appengine/docs/legacy/standard/go/datastore/reference#NewKey).\n\nThe following example creates an entity of kind `Employee`, populates its\nproperty values, and saves it to Datastore: \n\n import (\n \t\"context\"\n \t\"time\"\n\n \t\"google.golang.org/appengine/datastore\"\n )\n\n type Employee struct {\n \tFirstName string\n \tLastName string\n \tHireDate time.Time\n \tAttendedHRTraining bool\n }\n\n func f(ctx context.Context) {\n \t// ...\n \temployee := &Employee{\n \t\tFirstName: \"Antonio\",\n \t\tLastName: \"Salieri\",\n \t\tHireDate: time.Now(),\n \t}\n \temployee.AttendedHRTraining = true\n\n \tkey := datastore.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/datastore.html#google_golang_org_appengine_datastore_Key_NewIncompleteKey(ctx, \"Employee\", nil)\n \tif _, err := datastore.https://cloud.google.com/appengine/docs/legacy/standard/go111/reference/latest/datastore.html#google_golang_org_appengine_datastore_Key_Put(ctx, key, employee); err != nil {\n \t\t// Handle err\n \t}\n \t// ...\n }\n\nThe `Employee` type declares four fields for the data model: `FirstName`, `LastName`, `HireDate`, and `AttendedHRTraining`.\n\nIf you provide a empty key name, or use [`datastore.NewIncompleteKey`](/appengine/docs/legacy/standard/go/datastore/reference#NewIncompleteKey), Datastore will automatically generate a numeric ID for the entity's key: \n\n employee := &Employee{\n \tFirstName: \"Antonio\",\n \tLastName: \"Salieri\",\n \tHireDate: time.Now(),\n }\n employee.AttendedHRTraining = true\n key := datastore.NewIncompleteKey(ctx, \"Employee\", nil)\n _, err = datastore.Put(ctx, key, employee)\n\nRetrieving entities\n-------------------\n\nTo retrieve an entity identified by a given key, pass the `*datastore.Key` as an argument to the [`datastore.Get`](/appengine/docs/legacy/standard/go/datastore/reference#Get) function. You can generate the `*datastore.Key` using the [`datastore.NewKey`](/appengine/docs/legacy/standard/go/datastore/reference#NewKey) function. \n\n employeeKey := datastore.NewKey(ctx, \"Employee\", \"asalieri\", 0, nil)\n addressKey := datastore.NewKey(ctx, \"Address\", \"\", 1, employeeKey)\n var addr Address\n err = datastore.Get(ctx, addressKey, &addr)\n\n`datastore.Get` populates an instance of the appropriate Go struct.\n\nUpdating entities\n-----------------\n\nTo update an existing entity, modify the attributes of the struct, then call [`datastore.Put`](/appengine/docs/legacy/standard/go/datastore/reference#Put). The data overwrites the existing entity. The entire object is sent to Datastore with every call to `datastore.Put`.\n| **Note:** The Datastore API does not distinguish between creating a new entity and updating an existing one. If the key represents an entity that already exists, the `datastore.Put` function overwrites the existing entity. You can use a transaction to test whether an entity with a given key exists before creating one.\n\nDeleting entities\n-----------------\n\nGiven an entity's key, you can delete the entity with the [`datastore.Delete`](/appengine/docs/legacy/standard/go/datastore/reference#Delete) function: \n\n key := datastore.NewKey(ctx, \"Employee\", \"asalieri\", 0, nil)\n err = datastore.Delete(ctx, key)\n\nDeleting entities in bulk\n-------------------------\n\nIf you need to delete a large number of entities, we recommend [using\nDataflow to delete entities in bulk](/datastore/docs/bulk-delete).\n\nUsing batch operations\n----------------------\n\nYou can use the following batch operations if you want to operate on multiple\nentities in a single Datastore call:\n\n- [`datastore.PutMulti`](/appengine/docs/legacy/standard/go/datastore/reference#PutMulti),\n- [`datastore.GetMulti`](/appengine/docs/legacy/standard/go/datastore/reference#GetMulti) and\n- [`datastore.DeleteMulti`](/appengine/docs/legacy/standard/go/datastore/reference#DeleteMulti).\n\nHere is an example of a batch call: \n\n // A batch put.\n _, err = datastore.PutMulti(ctx, []*datastore.Key{k1, k2, k3}, []interface{}{e1, e2, e3})\n\n // A batch get.\n var entities = make([]*T, 3)\n err = datastore.GetMulti(ctx, []*datastore.Key{k1, k2, k3}, entities)\n\n // A batch delete.\n err = datastore.DeleteMulti(ctx, []*datastore.Key{k1, k2, k3})\n\nBatch operations do not change your costs. You will be charged for\nevery key in a batched operation, whether or not each key exists.\nThe size of the entities involved in an operation does not affect the cost.\n| **Note:** A call to `datastore.PutMulti` or `datastore.DeleteMulti` may succeed for some entities but not others. If it is important that the call succeed completely or fail completely, you must use a [transaction](/appengine/docs/legacy/standard/java/datastore/transactions), and all affected entities must be in the same [entity group](/appengine/docs/legacy/standard/go/datastore/entities#Transactions_and_entity_groups)."]]