建立、擷取、更新及刪除實體

Datastore 中的資料物件又稱為「實體」。為方便查詢,每個實體會分門別類到特定的「種類」中。舉例來說,人力資源應用程式可以用 Employee 種類的實體來代表每位員工。請注意,實體資料值採屬性形式。如要進一步瞭解實體,請參閱實體、屬性和金鑰概念文件。

建立實體及設定屬性

在 Go 中,您可以透過下列方式建立新的實體:建立 Go 結構的執行個體、填入其欄位,並呼叫 datastore.Put,將實體儲存至 Datastore。只有匯出的欄位 (以大寫字母開頭) 會儲存至 Datastore。您可以將非空白的 stringID 引數傳送至 datastore.NewKey,藉此為實體指定索引鍵名稱。

以下範例會建立 Employee 種類的實體、填入屬性值,並將其儲存至 Datastore:

import (
	"context"
	"time"

	"google.golang.org/appengine/datastore"
)

type Employee struct {
	FirstName          string
	LastName           string
	HireDate           time.Time
	AttendedHRTraining bool
}

func f(ctx context.Context) {
	// ...
	employee := &Employee{
		FirstName: "Antonio",
		LastName:  "Salieri",
		HireDate:  time.Now(),
	}
	employee.AttendedHRTraining = true

	key := datastore.NewIncompleteKey(ctx, "Employee", nil)
	if _, err := datastore.Put(ctx, key, employee); err != nil {
		// Handle err
	}
	// ...
}

Employee 型別會為資料模型宣告四個欄位:FirstNameLastNameHireDateAttendedHRTraining

如果您提供空白的金鑰名稱,或使用 datastore.NewIncompleteKey,Datastore 會自動為實體的金鑰產生數字 ID:

employee := &Employee{
	FirstName: "Antonio",
	LastName:  "Salieri",
	HireDate:  time.Now(),
}
employee.AttendedHRTraining = true
key := datastore.NewIncompleteKey(ctx, "Employee", nil)
_, err = datastore.Put(ctx, key, employee)

擷取實體

如要擷取以特定索引鍵識別的實體,請將 *datastore.Key 當做引數傳送至 datastore.Get 函式。您可以使用 datastore.NewKey 函式產生 *datastore.Key

employeeKey := datastore.NewKey(ctx, "Employee", "asalieri", 0, nil)
addressKey := datastore.NewKey(ctx, "Address", "", 1, employeeKey)
var addr Address
err = datastore.Get(ctx, addressKey, &addr)

datastore.Get 會填入適當 Go 結構的例項。

更新實體

如要更新現有實體,請修改結構的屬性,然後呼叫 datastore.Put。此資料會覆寫現有實體。每次呼叫 datastore.Put 時,系統會將整個物件傳送至 Datastore。

刪除實體

如有實體的索引鍵,您就可以透過 datastore.Delete 函式刪除該實體:

key := datastore.NewKey(ctx, "Employee", "asalieri", 0, nil)
err = datastore.Delete(ctx, key)

刪除大量實體

如果需要刪除大量的實體,建議您使用 Dataflow 來同時刪除多個實體

使用批次作業

如果您想在單一 Datastore 呼叫中針對大量實體進行操作,可以使用下列批次作業:

以下是批次呼叫的範例:

// A batch put.
_, err = datastore.PutMulti(ctx, []*datastore.Key{k1, k2, k3}, []interface{}{e1, e2, e3})

// A batch get.
var entities = 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})

批次作業不會影響費用。無論每個索引鍵存在與否,您都必須為批次作業中的每一個索引鍵付費。作業中實體的大小不會影響費用。