セルのインクリメント

既存の数値をインクリメントする書き込みリクエストを送信します。このタイプの書き込みは、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 のサンプルをご覧ください。