递增单元格

发送用于递增现有数值的写入请求。这种类型的写入会发出 ReadModifyWriteRow API 请求。

深入探索

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

代码示例

C++

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

namespace cbt = ::google::cloud::bigtable;
[](cbt::Table table) {
  std::string row_key = "phone#4c410523#20190501";
  std::string column_family = "stats_summary";

  google::cloud::StatusOr<cbt::Row> row = table.ReadModifyWriteRow(
      row_key, cbt::ReadModifyWriteRule::IncrementAmount(
                   column_family, "connected_wifi", -1));

  if (!row) throw std::move(row).status();
  std::cout << "Successfully updated row" << row->row_key() << "\n";
}

C#

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


using System;
using Google.Cloud.Bigtable.V2;
using Google.Cloud.Bigtable.Common.V2;

namespace Writes
{
    public class WriteIncrement
    {
        /// <summary>
        /// Increments a cell value in a row with an existing value at that cell.
        ///</summary>
        /// <param name="projectId">Your Google Cloud Project ID.</param>
        /// <param name="instanceId">Your Google Cloud Bigtable Instance ID.</param>
        /// <param name="tableId">Your Google Cloud Bigtable table ID.</param>
        public string writeIncrement(
            string projectId = "YOUR-PROJECT-ID",
            string instanceId = "YOUR-INSTANCE-ID",
            string tableId = "YOUR-TABLE-ID")
        {
            BigtableClient bigtableClient = BigtableClient.Create();

            TableName tableName = new TableName(projectId, instanceId, tableId);
            BigtableByteString rowkey = new BigtableByteString("phone#4c410523#20190501");
            String COLUMN_FAMILY = "stats_summary";

            // Increment the value of stats_summary:connected_wifi by -1 (change 1 to 0 to show it's disconnected)
            ReadModifyWriteRowResponse readModifyWriteRowResponse = bigtableClient.ReadModifyWriteRow(
                tableName,
                rowkey,
                ReadModifyWriteRules.Increment(COLUMN_FAMILY, "connected_wifi", -1));
            return $"Successfully updated row {readModifyWriteRowResponse.Row.Key}";
        }
    }
}

Go

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import (
	"context"
	"fmt"
	"io"

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

func writeIncrement(w io.Writer, projectID, instanceID string, tableName string) error {
	// projectID := "my-project-id"
	// instanceID := "my-instance-id"
	// tableName := "mobile-time-series"

	ctx := context.Background()
	client, err := bigtable.NewClient(ctx, projectID, instanceID)
	if err != nil {
		return fmt.Errorf("bigtable.NewAdminClient: %w", err)
	}
	defer client.Close()
	tbl := client.Open(tableName)
	columnFamilyName := "stats_summary"

	increment := bigtable.NewReadModifyWrite()
	increment.Increment(columnFamilyName, "connected_wifi", -1)

	rowKey := "phone#4c410523#20190501"
	if _, err := tbl.ApplyReadModifyWrite(ctx, rowKey, increment); err != nil {
		return fmt.Errorf("ApplyReadModifyWrite: %w", err)
	}

	fmt.Fprintf(w, "Successfully updated row: %s\n", rowKey)
	return nil
}

Java

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.ReadModifyWriteRow;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.TableId;
import java.nio.charset.Charset;

public class WriteIncrement {
  private static final String COLUMN_FAMILY_NAME = "stats_summary";

  public static void writeIncrement(String projectId, String instanceId, String tableId) {
    // String projectId = "my-project-id";
    // String instanceId = "my-instance-id";
    // String tableId = "mobile-time-series";

    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
      // Get an existing row that has a cell with an incrementable value. A value can be incremented
      // if it is encoded as a 64-bit big-endian signed integer.
      String rowkey = "phone#4c410523#20190501";
      ReadModifyWriteRow mutation =
          ReadModifyWriteRow.create(TableId.of(tableId), rowkey)
              .increment(COLUMN_FAMILY_NAME, "connected_cell", -1);
      Row success = dataClient.readModifyWriteRow(mutation);

      System.out.printf(
          "Successfully updated row %s", success.getKey().toString(Charset.defaultCharset()));
    } catch (Exception e) {
      System.out.println("Error during WriteIncrement: \n" + e.toString());
    }
  }
}

Node.js

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

/**
 * TODO(developer): Uncomment these variables before running the sample.
 */
// const instanceId = 'YOUR_INSTANCE_ID';
// const tableId = 'YOUR_TABLE_ID';

const {Bigtable} = require('@google-cloud/bigtable');

const bigtable = new Bigtable();

async function writeIncrement() {
  const instance = bigtable.instance(instanceId);
  const table = instance.table(tableId);

  const row = table.row('phone#4c410523#20190501');
  await row.increment('stats_summary:connected_wifi', -1);

  console.log(`Successfully updated row ${row}`);
}

writeIncrement();

PHP

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\ReadModifyWriteRowRules;

/**
 * Increment an existing value in a table
 *
 * @param string $projectId The Google Cloud project ID
 * @param string $instanceId The ID of the Bigtable instance
 * @param string $tableId The ID of the table where the data needs to be incremented
 */
function write_increment(
    string $projectId,
    string $instanceId,
    string $tableId = 'mobile-time-series'
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $columnFamilyId = 'stats_summary';

    $rules = (new ReadModifyWriteRowRules())->increment($columnFamilyId, 'connected_wifi', 3);
    $row = $table->readModifyWriteRow('phone#4c410523#20190501', $rules);

    printf('Successfully updated row.' . PHP_EOL);
}

Python

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

from google.cloud import bigtable

def write_increment(project_id, instance_id, table_id):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)

    column_family_id = "stats_summary"

    row_key = "phone#4c410523#20190501"
    row = table.append_row(row_key)

    # Decrement the connected_wifi value by 1.
    row.increment_cell_value(column_family_id, "connected_wifi", -1)
    row.commit()

    print("Successfully updated row {}.".format(row_key))

Ruby

如需了解如何安装和使用 Bigtable 的客户端库,请参阅 Bigtable 客户端库

如需向 Bigtable 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

# instance_id = "my-instance"
# table_id    = "my-table"
table = bigtable.table instance_id, table_id
column_family = "stats_summary"

rowkey = "phone#4c410523#20190501"
decrement_rule = table.new_read_modify_write_rule(column_family, "connected_wifi")
                      .increment(-1)

row = table.read_modify_write_row rowkey, decrement_rule
puts "Successfully updated row #{row.key}"

后续步骤

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