添加任务

创建并保存假设类型为“Task”的实体

深入探索

如需查看包含此代码示例的详细文档,请参阅以下内容:

代码示例

C#

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 C# API 参考文档

如需向 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);
}

Java

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Java API 参考文档

如需向 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

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Node.js API 参考文档

如需向 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

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 PHP API 参考文档

如需向 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

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Python API 参考文档

如需向 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

如需了解如何安装和使用 Datastore 模式客户端库,请参阅 Datastore 模式客户端库。 如需了解详情,请参阅 Datastore 模式 Ruby API 参考文档

如需向 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

后续步骤

如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器