Créer, récupérer, mettre à jour et supprimer des entités
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Dans Datastore, les objets de données sont appelés entités. Chacune de ces entités possède un genre spécifique qui la classe dans une catégorie pour les besoins des requêtes. Par exemple, si vous écrivez une application de ressources humaines, vous pouvez représenter chaque employé avec une entité du genre Employee. Sachez que les valeurs de données des entités apparaissent sous la forme de propriétés.
Pour en savoir plus sur les entités, consultez le document conceptuel Entités, propriétés et clés.
Créer des entités et définir les propriétés
Dans Go, pour créer une entité, construisez une instance d'une structure Go, renseignez ses champs, puis appelez datastore.Put pour l'enregistrer dans Datastore. Seuls les champs exportés (commençant par une lettre majuscule) seront enregistrés dans Datastore. Vous pouvez spécifier le nom de clé de l'entité en transmettant un argument stringID non vide à datastore.NewKey.
L'exemple suivant crée une entité du genre Employee, renseigne ses valeurs de propriété et l'enregistre dans Datastore :
Le type Employee déclare quatre champs pour le modèle de données : FirstName, LastName, HireDate et AttendedHRTraining.
Si vous fournissez un nom de clé vide ou utilisez datastore.NewIncompleteKey, Datastore génère automatiquement un ID numérique pour la clé de l'entité :
Pour récupérer une entité identifiée par une clé donnée, transmettez l'élément *datastore.Key en tant qu'argument à la fonction datastore.Get. Vous pouvez générer l'élément *datastore.Key à l'aide de la fonction datastore.NewKey.
datastore.Get insère une instance de la structure Go appropriée.
Mettre à jour des entités
Pour mettre à jour une entité existante, modifiez les attributs de la structure, puis appelez datastore.Put. Les données écrasent l'entité existante. L'objet entier est envoyé à Datastore à chaque appel de datastore.Put.
Supprimer des entités
Selon la clé d'une entité, vous pouvez supprimer l'entité à l'aide de la fonction 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})
Les opérations par lot n'entraînent pas de modification des coûts. Vous serez facturé pour chaque clé employée dans ces opérations, que cette clé existe ou non.
La taille des entités impliquées dans une opération n'a pas d'incidence sur les coûts.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/09/04 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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)."]]