읽기/수정/쓰기 수행

이러한 유형의 쓰기는 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 WriteIncrementSample
    {
        /// <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 샘플 브라우저를 참조하세요.