참고: Go 1.11은 2024년 1월 30일 지원 종료되었습니다. 기존 Go 1.11 애플리케이션을 계속 실행하고 트래픽을 수신합니다. 그러나 지원 종료 날짜 이후에는 해당 런타임을 사용하는 애플리케이션의 재배포를 App Engine에서 차단할 수 있습니다.
지원되는 최신 Go 버전으로 마이그레이션하는 것이 좋습니다.
Datastore의 데이터 객체를 항목이라고 하며, 각 항목은 쿼리를 위해 특정한 종류로 분류됩니다. 예를 들어 인사 관리 애플리케이션을 작성하는 경우 각 직원을 Employee 종류의 항목으로 나타낼 수 있습니다. 항목 데이터 값의 형식은 속성이라는 점에 유의하세요.
항목에 대한 자세한 내용은 항목, 속성, 키 개념 문서를 참조하세요.
항목 생성 및 속성 설정
Go에서는 Go 구조체의 인스턴스를 구성하고 해당 필드를 채우고, datastore.Put을 호출하여 Datastore에 저장하는 방식으로 새 항목을 만듭니다. 내보낸 필드(대문자로 시작)만 Datastore에 저장됩니다. 비어 있지 않은 stringID 인수를 datastore.NewKey에 전달하여 항목의 키 이름을 지정할 수 있습니다.
다음 예시에서는 Employee 종류의 항목을 만들고 속성 값을 채우고 Datastore에 저장합니다.
// 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})
일괄 작업을 수행해도 비용은 변하지 않습니다. 각 키가 있는지 여부와 관계없이 일괄 처리된 작업에서 모든 키에 요금이 부과됩니다.
작업과 관련된 항목 크기는 비용에 영향을 주지 않습니다.
[[["이해하기 쉬움","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-03-26(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)."]]