開始使用 Firestore (Datastore 模式) API

本頁提供了一個小練習題,練習如何透過 Firestore in Datastore mode API 來建立 TaskList 指令列應用程式。TaskList 應用程式用於存放、列出、更新及移除工作。

必要條件

  1. 能夠以本主題所使用的程式語言來撰寫並執行指令列應用程式
    在繼續本教學之前,除了對應用程式開發應有基本瞭解之外,也應知道如何下載與安裝額外的函式庫。
  2. 已啟用 Datastore mode API 的專案
    使用 Datastore 模式的應用程式會與已啟用 Datastore mode API 的 Google Cloud 專案相關聯。 Google Cloud 這個專案會以您在應用程式中所使用的憑證,以便 Google 辨識應用程式,並驗證專案使用 Datastore mode API 的權限。
    請按照這些操作說明建立專案,為專案啟用 Datastore 模式 API,並使用 gcloud auth login 指令設定本機開發環境的驗證憑證。記下專案 ID,後續步驟將會用到。

安裝和設定

為您的開發環境配置所需的設定及安裝程式庫。

C#

  1. 確認已安裝 Visual Studio (2013 或更新的版本 )。
  2. 範例存放區下載 TaskList 範例應用程式。
  3. 將下載下來的檔案解壓縮在「Documents」(文件) 目錄下。
  4. 在 Visual Studio 中開啟 dotnet-docs-samples-master\datastore\api\Datastore.sln 檔案。
  5. 在 Visual Studio 的「方案總管」視窗中,以滑鼠右鍵按一下「TaskList」專案,然後選擇「設定為啟動專案」
  6. 再次以滑鼠右鍵按一下「TaskList」專案,然後選擇「Properties」
  7. 在「Properties」(屬性) 視窗中,按一下「Debug」(偵錯),並在「Command line arguments:」(指令列引數:) 方塊中輸入您的Google Cloud 專案 ID。

    Visual Studio Debug Window

  8. 按一下 [File] (檔案) 接著點選 [Save] (儲存) 儲存您所做的變更。

  9. 執行應用程式,按下鍵盤上的 F5

Go

  1. 複製一份 TaskList 應用程式範例。

    go get github.com/GoogleCloudPlatform/golang-samples/datastore/tasks
    
  2. 將路徑變更至您所複製範例的目錄:

    cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/datastore/tasks
    
  3. 在指令列中執行以下指令,將 <project-id> 替換為您的 Google Cloud 專案 ID。

    export DATASTORE_PROJECT_ID=<project-id>
    

    (若使用 Windows:以 set 替代 export。)

  4. 執行應用程式!

    go run tasks.go
    

Java

  1. 確認已安裝 MavenJava (版本 8 以上)。

  2. 範例存放區下載 TaskList 範例應用程式。

  3. 在命令提示字元中,解壓縮下載的檔案:

    unzip main.zip
    
  4. 將路徑變更至 TaskList 應用主程式的目錄:

    cd java-datastore-main/samples/snippets
    
  5. 執行下列指令,其中 <project-id> 是您的 Google Cloud 專案 ID。

    gcloud config set project <project-id>
    
  6. 編譯並執行應用程式!

    mvn clean compile
    mvn exec:java -Dexec.mainClass="com.google.datastore.snippets.TaskList"
    

Node.js

  1. 設定適當的 Node.js 開發環境

  2. 範例存放區下載 TaskList 範例應用程式。

  3. 解壓縮下載內容:

    unzip master.zip
    
  4. 將路徑變更至 TaskList 應用主程式的目錄:

    cd nodejs-datastore-master/samples
    
  5. 安裝依附元件並連結應用程式:

    npm install
    
  6. 在指令列中執行以下指令,將 <project-id> 替換為您的 Google Cloud 專案 ID。

    export GCLOUD_PROJECT=<project-id>
    

    (若使用 Windows:以 set 替代 export。)

  7. 執行應用程式!

    node tasks.js
    

PHP

  1. 確認已安裝 PHP (版本 5.6 或更新的版本) 及 Composer
  2. 範例存放區下載 TaskList 範例應用程式。
  3. 解壓縮下載內容:

    unzip master.zip
    
  4. 將路徑變更至 TaskList 應用主程式的目錄:

    cd php-docs-samples-master/datastore/tutorial
    
  5. 安裝依附元件:

    composer install
    
  6. 執行應用程式!

    php src/list_tasks.php
    

Python

  1. 確認已安裝 Python (版本 2.7.9 或更新的版本)、pipvirtualenv
  2. 啟用 virtualenv 工作階段。

    virtualenv venv
    source venv/bin/activate
    
  3. 範例存放區下載 TaskList 範例應用程式。

  4. 解壓縮下載內容:

    unzip master.zip
    
  5. 將路徑變更至 TaskList 應用主程式的目錄:

    cd python-docs-samples-master/datastore/cloud-client
    
  6. 安裝依附元件:

    pip install -r requirements.txt
    
  7. 執行應用程式請將 <project-id> 替換為專案 ID。 Google Cloud

    python tasks.py new project-id
    

Ruby

  1. 確認已安裝 RubyBundler

  2. 範例存放區下載 TaskList 範例應用程式。

  3. 解壓縮下載內容:

    unzip master.zip
    
  4. 將路徑變更至 TaskList 應用主程式的目錄:

    cd google-cloud-ruby-master/google-cloud-datastore/samples
    
  5. 安裝依附元件:

    bundle install
    
  6. 在指令列中執行以下指令,將 <project-id> 替換為您的 Google Cloud 專案 ID。

    export GOOGLE_CLOUD_PROJECT=<project-id>
    

    (若使用 Windows:以 set 替代 export。)

  7. 執行應用程式!

    bundle exec ruby tasks.rb
    

建立 Authorized Service Object

如要透過 Google API Client 程式庫向 Google Cloud API 發出已驗證的要求,您必須:

  • 取得發送要求時需使用的憑證。
  • 建立使用此憑證的服務物件。

接下來,您就可以使用 Datastore 模式服務物件的方法發出 API 呼叫。

舉例來說,您要先從環境取得 Application Default Credentials 這項憑證,再將此憑證做為建立服務物件的傳入引數。

以下是建立已認證 Datastore 模式服務物件的呼叫方式:

C#

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore C# API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Create an authorized Datastore service using Application Default Credentials.
_db = DatastoreDb.Create(projectId);
// Create a Key factory to construct keys associated with this project.
_keyFactory = _db.CreateKeyFactory("Task");

Go

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Go API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"log"

	"cloud.google.com/go/datastore"
)

func createClient(projectID string) (*datastore.Client, error) {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Could not create datastore client: %v", err)
	}
	// Note: call the following from main() to ensure the client
	// properly frees all resources.
	// defer client.Close()
	return client, nil
}

Java

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Java API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// Create an authorized Datastore service using Application Default Credentials.
private final Datastore datastore = DatastoreOptions.getDefaultInstance().getService();

// Create a Key factory to construct keys associated with this project.
private final KeyFactory keyFactory = datastore.newKeyFactory().setKind("Task");

Node.js

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Node.js API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// By default, the client will authenticate using the service account file
// specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable and use
// the project specified by the GCLOUD_PROJECT environment variable. See
// https://googlecloudplatform.github.io/google-cloud-node/#/docs/datastore/latest/guides/authentication
const {Datastore} = require('@google-cloud/datastore');

// Creates a client
const datastore = new Datastore();

PHP

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore PHP API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Create a Cloud Datastore client.
 *
 * @param string $projectId The Google Cloud project ID.
 */
function build_service(string $projectId)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);
    return $datastore;
}

Python

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Python API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import datastore

def create_client(project_id):
    return datastore.Client(project_id)

Ruby

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Ruby API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

require "google/cloud/datastore"

datastore = Google::Cloud::Datastore.new

儲存資料

Datastore 模式中的物件稱為「實體」,每個實體都有特定的「種類」。TaskList 應用程式會儲存 Task 類實體,包含以下屬性:

  • description:工作說明,由使用者自訂的文字字串
  • created:顯示此項工作的建立日期
  • done:標示此項工作是否已完成的布林值

當使用者新增一項新工作,TaskList 應用程式就會建立一個 Task 實體,並針對先前列出的屬性給予引數值:

C#

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore C# API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/// <summary>
///  Adds a task entity to the Datastore
/// </summary>
/// <param name="description">The task description.</param>
/// <returns>The key of the entity.</returns>
Key AddTask(string description)
{
    Entity task = new Entity()
    {
        Key = _keyFactory.CreateIncompleteKey(),
        ["description"] = new Value()
        {
            StringValue = description,
            ExcludeFromIndexes = true
        },
        ["created"] = DateTime.UtcNow,
        ["done"] = false
    };
    return _db.Insert(task);
}

Go

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Go API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"log"
	"time"

	"cloud.google.com/go/datastore"
)

// Task is the model used to store tasks in the datastore.
type Task struct {
	Desc    string    `datastore:"description"`
	Created time.Time `datastore:"created"`
	Done    bool      `datastore:"done"`
	id      int64     // The integer ID used in the datastore.
}

// AddTask adds a task with the given description to the datastore,
// returning the key of the newly created entity.
func AddTask(projectID string, desc string) (*datastore.Key, error) {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Could not create datastore client: %v", err)
	}
	defer client.Close()
	task := &Task{
		Desc:    desc,
		Created: time.Now(),
	}
	key := datastore.IncompleteKey("Task", nil)
	return client.Put(ctx, key, task)

}

Java

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Java API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * Adds a task entity to the Datastore.
 *
 * @param description The task description
 * @return The {@link Key} of the entity
 * @throws DatastoreException if the ID allocation or put fails
 */
Key addTask(String description) {
  Key key = datastore.allocateId(keyFactory.newKey());
  Entity task =
      Entity.newBuilder(key)
          .set(
              "description",
              StringValue.newBuilder(description).setExcludeFromIndexes(true).build())
          .set("created", Timestamp.now())
          .set("done", false)
          .build();
  datastore.put(task);
  return key;
}

Node.js

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Node.js API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

async function addTask(description) {
  const taskKey = datastore.key('Task');
  const entity = {
    key: taskKey,
    data: [
      {
        name: 'created',
        value: new Date().toJSON(),
      },
      {
        name: 'description',
        value: description,
        excludeFromIndexes: true,
      },
      {
        name: 'done',
        value: false,
      },
    ],
  };

  try {
    await datastore.save(entity);
    console.log(`Task ${taskKey.id} created successfully.`);
  } catch (err) {
    console.error('ERROR:', err);
  }
}

PHP

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore PHP API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Create a new task with a given description.
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $description
 */
function add_task(string $projectId, string $description)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);

    $taskKey = $datastore->key('Task');
    $task = $datastore->entity(
        $taskKey,
        [
            'created' => new DateTime(),
            'description' => $description,
            'done' => false
        ],
        ['excludeFromIndexes' => ['description']]
    );
    $datastore->insert($task);
    printf('Created new task with ID %d.' . PHP_EOL, $task->key()->pathEnd()['id']);
}

Python

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Python API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import datastore

def add_task(client: datastore.Client, description: str):
    # Create an incomplete key for an entity of kind "Task". An incomplete
    # key is one where Datastore will automatically generate an Id
    key = client.key("Task")

    # Create an unsaved Entity object, and tell Datastore not to index the
    # `description` field
    task = datastore.Entity(key, exclude_from_indexes=("description",))

    # Apply new field values and save the Task entity to Datastore
    task.update(
        {
            "created": datetime.datetime.now(tz=datetime.timezone.utc),
            "description": description,
            "done": False,
        }
    )
    client.put(task)
    return task.key

Ruby

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Ruby API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def add_task description
  require "google/cloud/datastore"

  datastore = Google::Cloud::Datastore.new

  task = datastore.entity "Task" do |t|
    t["description"] = description
    t["created"]     = Time.now
    t["done"]        = false
    t.exclude_from_indexes! "description", true
  end

  datastore.save task

  puts task.key.id

  task.key.id
end

我們將針對這個應用程式,提供一個方法來更新 done 屬性值,以標示出已完成的工作:

C#

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore C# API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/// <summary>
/// Marks a task entity as done.
/// </summary>
/// <param name="id">The ID of the task entity as given by Key.</param>
/// <returns>true if the task was found.</returns>
bool MarkDone(long id)
{
    using (var transaction = _db.BeginTransaction())
    {
        Entity task = transaction.Lookup(_keyFactory.CreateKey(id));
        if (task != null)
        {
            task["done"] = true;
            transaction.Update(task);
        }
        transaction.Commit();
        return task != null;
    }
}

Go

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Go API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"log"

	"cloud.google.com/go/datastore"
)

// MarkDone marks the task done with the given ID.
func MarkDone(projectID string, taskID int64) error {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Could not create datastore client: %v", err)
	}
	defer client.Close()
	// Create a key using the given integer ID.
	key := datastore.IDKey("Task", taskID, nil)

	// In a transaction load each task, set done to true and store.
	_, err = client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {
		var task Task
		if err := tx.Get(key, &task); err != nil {
			return err
		}
		task.Done = true
		_, err := tx.Put(key, &task)
		return err
	})
	return err
}

Java

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Java API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * Marks a task entity as done.
 *
 * @param id The ID of the task entity as given by {@link Key#id()}
 * @return true if the task was found, false if not
 * @throws DatastoreException if the transaction fails
 */
boolean markDone(long id) {
  Transaction transaction = datastore.newTransaction();
  try {
    Entity task = transaction.get(keyFactory.newKey(id));
    if (task != null) {
      transaction.put(Entity.newBuilder(task).set("done", true).build());
    }
    transaction.commit();
    return task != null;
  } finally {
    if (transaction.isActive()) {
      transaction.rollback();
    }
  }
}

Node.js

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Node.js API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

async function markDone(taskId) {
  const transaction = datastore.transaction();
  const taskKey = datastore.key(['Task', datastore.int(taskId)]);

  try {
    await transaction.run();
    const [task] = await transaction.get(taskKey);
    task.done = true;
    transaction.save({
      key: taskKey,
      data: task,
    });
    await transaction.commit();
    console.log(`Task ${taskId} updated successfully.`);
  } catch (err) {
    await transaction.rollback();
  }
}

PHP

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore PHP API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Mark a task with a given id as done.
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $taskId
 */
function mark_done(string $projectId, string $taskId)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);

    $taskKey = $datastore->key('Task', $taskId);
    $transaction = $datastore->transaction();
    $task = $transaction->lookup($taskKey);
    $task['done'] = true;
    $transaction->upsert($task);
    $transaction->commit();
    printf('Task %d updated successfully.' . PHP_EOL, $taskId);
}

Python

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Python API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import datastore

def mark_done(client: datastore.Client, task_id: str | int):
    with client.transaction():
        # Create a key for an entity of kind "Task", and with the supplied
        # `task_id` as its Id
        key = client.key("Task", task_id)
        # Use that key to load the entity
        task = client.get(key)

        if not task:
            raise ValueError(f"Task {task_id} does not exist.")

        # Update a field indicating that the associated
        # work has been completed
        task["done"] = True

        # Persist the change back to Datastore
        client.put(task)

Ruby

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Ruby API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def mark_done task_id
  require "google/cloud/datastore"

  datastore = Google::Cloud::Datastore.new

  task = datastore.find "Task", task_id

  task["done"] = true

  datastore.save task
end

以下是使用 Task 實體金鑰移除 Task 實體的方法:

C#

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore C# API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/// <summary>
/// Deletes a task entity.
/// </summary>
/// <param name="id">The ID of the task entity as given by Key.</param>
void DeleteTask(long id)
{
    _db.Delete(_keyFactory.CreateKey(id));
}

Go

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Go API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"log"

	"cloud.google.com/go/datastore"
)

// DeleteTask deletes the task with the given ID.
func DeleteTask(projectID string, taskID int64) error {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Could not create datastore client: %v", err)
	}
	return client.Delete(ctx, datastore.IDKey("Task", taskID, nil))
}

Java

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Java API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * Deletes a task entity.
 *
 * @param id The ID of the task entity as given by {@link Key#id()}
 * @throws DatastoreException if the delete fails
 */
void deleteTask(long id) {
  datastore.delete(keyFactory.newKey(id));
}

Node.js

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Node.js API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

async function deleteTask(taskId) {
  const taskKey = datastore.key(['Task', datastore.int(taskId)]);

  await datastore.delete(taskKey);
  console.log(`Task ${taskId} deleted successfully.`);
}

PHP

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore PHP API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Delete a task with a given id.
 *
 * @param string $projectId The Google Cloud project ID.
 * @param string $taskId
 */
function delete_task(string $projectId, string $taskId)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);

    $taskKey = $datastore->key('Task', $taskId);
    $datastore->delete($taskKey);

    printf('Task %d deleted successfully.' . PHP_EOL, $taskId);
}

Python

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Python API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import datastore

def delete_task(client: datastore.Client, task_id: str | int):
    # Create a key for an entity of kind "Task", and with the supplied
    # `task_id` as its Id
    key = client.key("Task", task_id)
    # Use that key to delete its associated document, if it exists
    client.delete(key)

Ruby

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Ruby API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def delete_task task_id
  require "google/cloud/datastore"

  datastore = Google::Cloud::Datastore.new

  task = datastore.find "Task", task_id

  datastore.delete task
end

執行查詢

除了按實體金鑰直接從 Cloud Datastore 擷取實體之外,應用程式也可以執行「查詢」,按實體的屬性值擷取實體。典型的查詢包含以下幾項:

  • 查詢所使用的實體類型
  • 零或多個過濾條件,例如搜尋屬性值滿足條件值的種類
  • 零或多個排列規則,對查詢結果排序

我們將針對這個應用程式搜尋 Datastore 模式的 Task 實體,並依建立時間排序:

C#

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore C# API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/// <summary>
/// Returns a list of all task entities in ascending order of creation time.
/// </summary>
IEnumerable<Entity> ListTasks()
{
    Query query = new Query("Task")
    {
        Order = { { "created", PropertyOrder.Types.Direction.Descending } }
    };
    return _db.RunQuery(query).Entities;
}

Go

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Go API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import (
	"context"
	"log"

	"cloud.google.com/go/datastore"
)

// ListTasks returns all the tasks in ascending order of creation time.
func ListTasks(projectID string) ([]*Task, error) {
	ctx := context.Background()
	client, err := datastore.NewClient(ctx, projectID)
	if err != nil {
		log.Fatalf("Could not create datastore client: %v", err)
	}

	var tasks []*Task
	// Create a query to fetch all Task entities, ordered by "created".
	query := datastore.NewQuery("Task").Order("created")
	keys, err := client.GetAll(ctx, query, &tasks)
	if err != nil {
		return nil, err
	}

	// Set the id field on each Task from the corresponding key.
	for i, key := range keys {
		tasks[i].id = key.ID
	}

	return tasks, nil
}

Java

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Java API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * Returns a list of all task entities in ascending order of creation time.
 *
 * @throws DatastoreException if the query fails
 */
Iterator<Entity> listTasks() {
  Query<Entity> query =
      Query.newEntityQueryBuilder().setKind("Task").setOrderBy(OrderBy.asc("created")).build();
  return datastore.run(query);
}

Node.js

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Node.js API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

async function listTasks() {
  const query = datastore.createQuery('Task').order('created');

  const [tasks] = await datastore.runQuery(query);
  console.log('Tasks:');
  tasks.forEach(task => {
    const taskKey = task[datastore.KEY];
    console.log(taskKey.id, task);
  });
}

PHP

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore PHP API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

use Google\Cloud\Datastore\DatastoreClient;

/**
 * Return an iterator for all the tasks in ascending order of creation time.
 *
 * @param string $projectId The Google Cloud project ID.
 */
function list_tasks(string $projectId)
{
    $datastore = new DatastoreClient(['projectId' => $projectId]);

    $query = $datastore->query()
        ->kind('Task')
        ->order('created');
    $result = $datastore->runQuery($query);
    /* @var Entity $task */
    foreach ($result as $index => $task) {
        printf('ID: %s' . PHP_EOL, $task->key()->pathEnd()['id']);
        printf('  Description: %s' . PHP_EOL, $task['description']);
        printf('  Status: %s' . PHP_EOL, $task['done'] ? 'done' : 'created');
        printf('  Created: %s' . PHP_EOL, $task['created']->format('Y-m-d H:i:s e'));
        print(PHP_EOL);
    }
}

Python

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Python API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

from google.cloud import datastore

def list_tasks(client: datastore.Client):
    # Create a query against all of your objects of kind "Task"
    query = client.query(kind="Task")
    query.order = ["created"]

    return list(query.fetch())

Ruby

如要瞭解如何安裝及使用 Cloud Datastore 的用戶端程式庫,請參閱這篇文章。 詳情請參閱 Cloud Datastore Ruby API 參考說明文件

如要向 Cloud Datastore 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

def list_tasks
  require "google/cloud/datastore"

  datastore = Google::Cloud::Datastore.new

  query = datastore.query("Task").order("created")
  tasks = datastore.run query

  tasks.each do |t|
    puts t["description"]
    puts t["done"] ? "  Done" : "  Not Done"
    puts "  ID: #{t.key.id}"
  end
end

後續步驟

本教學課程只介紹從指令列應用程式呼叫 Datastore mode API 的最基本步驟。Datastore 模式支援快速且可高度擴展的 ACID 交易、類 SQL 查詢、索引等。