Datastore 模式 Firestore API 使用入门

本页面提供了一个简短的练习,让您了解如何使用 Datastore 模式 Firestore API 构建简单的命令行 TaskList 应用。TaskList 应用可存储、列出、更新和移除任务。

前提条件

  1. 能够使用本主题中所用的编程语言编写和运行命令行应用
    除了对如何开发应用有基本了解之外,您应能够下载并安装其他库,然后再开始学习本教程。
  2. 启用了 Datastore 模式 API 的 Google Cloud 控制台项目
    使用 Datastore 模式的应用必须与启用了 Datastore 模式 API 的 Google Cloud 控制台项目相关联。此项目提供您在应用中使用的身份验证凭据,以向 Google 表明应用的身份并授权其使用 Datastore 模式 API。
    按照以下说明创建项目,为其启用 Datastore 模式 API,并通过 gcloud auth login 命令为本地开发环境设置身份验证凭据。请记下项目的 ID,稍后您将会用到。
  3. 具有处于活跃状态的 App Engine 应用
    使用 Datastore 模式 API 的项目要求有一个处于活跃状态的 App Engine 应用。打开 App Engine 信息中心并确认项目是否有处于活跃状态的 App Engine 应用。
    如果需要,请创建一个 App Engine 应用。该应用一定不能被停用。

安装和设置

安装客户端库并为开发环境配置任意额外设置。

C#

  1. 确保安装了 Visual Studio(2013 版或更高版本)。
  2. 点击此处下载 TaskList 示例应用。
  3. 将文件从 zip 解压缩到 Documents 文件夹中的一个目录中
  4. 在 Visual Studio 中,打开 dotnet-docs-samples-master\datastore\api\Datastore.sln 文件。
  5. 在 Visual Studio 的解决方案资源管理器窗口中,右键点击 TaskList 项目并选择设为启动项目
  6. 再次右键点击 TaskList 项目并选择属性
  7. 属性窗口中,点击调试,然后在“命令行参数:”框中输入 Google Cloud Platform 项目的 ID。

    Visual Studio 调试窗口

  8. 点击文件,然后点击保存以保存更改。

  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 Platform 项目 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 Platform 项目 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 Platform 项目 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>,请使用您的 Google Cloud Platform 项目 ID。

    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 Platform 项目 ID。

    export GOOGLE_CLOUD_PROJECT=<project-id>
    

    (Windows 用户:请使用 set 而不是 export。)

  7. 运行应用!

    bundle exec ruby tasks.rb
    

创建授权服务对象

为了使用 Google API 客户端库向 Google Cloud API 发送身份验证请求,您必须进行以下操作:

  • 获取用于请求的凭据。
  • 创建使用该凭据的服务对象。

然后,您可以通过对 Datastore 模式服务对象调用相关方法来进行 API 调用。

在本例中,您将从环境中获取应用默认凭据,并将其作为参数传递以创建服务对象。

以下是用于创建授权的 Datastore 模式服务对象的调用:

C#

如需了解如何安装和使用 Cloud Datastore 客户端库,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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

运行查询

除了直接按实体的键从 Datastore 模式数据库中检索实体之外,应用还可执行查询,按实体属性的值进行检索。典型的查询包括以下元素:

  • 要查询的实体种类
  • 零个或多个过滤条件,例如用于选择其属性与值匹配的种类
  • 零个或零个以上排序顺序,用于对结果进行排序

对于此应用,我们将在 Datastore 模式数据库中查询 Task 实体并按创建时间排序:

C#

如需了解如何安装和使用 Cloud Datastore 客户端库,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 客户端库。 如需了解详情,请参阅 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 模式 API 所需的最基本的步骤。Datastore 模式支持快速且高度可扩缩的 ACID 事务、类似于 SQL 的查询、索引等。