添加到汇总单元格

向聚合单元格添加整数。这种类型的写入会发出 AddToCell API 请求。

深入探索

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

代码示例

Go

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

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

import (
	"context"
	"fmt"
	"io"
	"time"

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

func writeAggregate(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.NewClient: %w", err)
	}
	defer client.Close()
	tbl := client.Open(tableName)
	columnFamilyName := "view_count"
	viewTimestamp, err := time.Parse(time.RFC3339, "2024-03-13T12:41:34Z")
	if err != nil {
		return err
	}
	hourlyBucket := viewTimestamp.Truncate(time.Hour)

	mut := bigtable.NewMutation()
	mut.AddIntToCell(columnFamilyName, "views", bigtable.Time(hourlyBucket), 1)

	rowKey := "page#index.html"
	if err := tbl.Apply(ctx, rowKey, mut); err != nil {
		return fmt.Errorf("Apply: %w", err)
	}

	fmt.Fprintf(w, "Successfully wrote 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.RowMutation;
import com.google.common.primitives.Longs;
import com.google.protobuf.ByteString;
import java.time.Instant;
import java.time.temporal.ChronoUnit;

public class WriteAggregate {
  private static final String COUNT_COLUMN_FAMILY_NAME = "view_count";
  private static final long MICROS_PER_MILLI = 1000;

  public static void writeAggregate(String projectId, String instanceId, String tableId) {
    // String projectId = "my-project-id";
    // String instanceId = "my-instance-id";
    // String tableId = "page-view-counter";

    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {

      String rowKey = "page#index.html";
      Instant viewTimestamp = Instant.parse("2024-03-13T12:41:34.123Z");

      // Bucket the views for an hour into a single count, giving us an hourly view count for a
      // given page.
      Instant hourlyBucket = viewTimestamp.truncatedTo(ChronoUnit.HOURS);
      long hourlyBucketMicros = hourlyBucket.toEpochMilli() * MICROS_PER_MILLI;

      RowMutation rowMutation =
          RowMutation.create(tableId, rowKey)
              .addToCell(COUNT_COLUMN_FAMILY_NAME, "views", hourlyBucketMicros, 1);

      dataClient.mutateRow(rowMutation);
      System.out.printf("Successfully wrote row %s", rowKey);

    } catch (Exception e) {
      System.out.println("Error during WriteAggregate: \n" + e.toString());
    }
  }

  public static void mergeAggregate(String projectId, String instanceId, String tableId) {
    // String projectId = "my-project-id";
    // String instanceId = "my-instance-id";
    // String tableId = "page-view-counter";

    try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {

      String rowKey = "page#index.html";
      Instant viewTimestamp = Instant.parse("2024-03-13T12:41:34.123Z");

      // Bucket the views for an hour into a single count, giving us an hourly view count for a
      // given page.
      Instant hourlyBucket = viewTimestamp.truncatedTo(ChronoUnit.HOURS);
      long hourlyBucketMicros = hourlyBucket.toEpochMilli() * MICROS_PER_MILLI;

      RowMutation rowMutation =
          RowMutation.create(tableId, rowKey)
              .mergeToCell(
                  COUNT_COLUMN_FAMILY_NAME,
                  "views",
                  hourlyBucketMicros,
                  ByteString.copyFrom(Longs.toByteArray(1L)));

      dataClient.mutateRow(rowMutation);
      System.out.printf("Successfully wrote row %s", rowKey);

    } catch (Exception e) {
      System.out.println("Error during mergeAggregate: \n" + e.toString());
    }
  }
}

Python

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

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

import time

from google.cloud.bigtable.data import BigtableDataClient
from google.cloud.bigtable.data.exceptions import MutationsExceptionGroup
from google.cloud.bigtable.data.mutations import AddToCell, RowMutationEntry

def write_aggregate(project_id, instance_id, table_id):
    """Increments a value in a Bigtable table using AddToCell mutation."""
    with BigtableDataClient(project=project_id) as client:
        with client.get_table(instance_id, table_id) as table:
            row_key = "unique_device_ids_1"
            try:
                with table.mutations_batcher() as batcher:
                    # The AddToCell mutation increments the value of a cell.
                    # The `counters` family must be set up to be an aggregate
                    # family with an int64 input type.
                    reading = AddToCell(
                        family="counters",
                        qualifier="odometer",
                        value=32304,
                        # Convert nanoseconds to microseconds
                        timestamp_micros=time.time_ns() // 1000,
                    )
                    batcher.append(
                        RowMutationEntry(row_key.encode("utf-8"), [reading])
                    )
            except MutationsExceptionGroup as e:
                # MutationsExceptionGroup contains a FailedMutationEntryError for
                # each mutation that failed.
                for sub_exception in e.exceptions:
                    failed_entry: RowMutationEntry = sub_exception.entry
                    cause: Exception = sub_exception.__cause__
                    print(
                        f"Failed mutation for row {failed_entry.row_key!r} with error: {cause!r}"
                    )

后续步骤

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