寫入樣本

本文提供程式碼範例,說明使用 Cloud Bigtable 用戶端程式庫時,可以傳送至 Bigtable 的各種類型寫入要求。

本頁面的範例會使用 SetCell 突變,將寫入要求傳送至非匯總儲存格。如要查看如何傳送新增要求來匯總儲存格,請參閱「在寫入時匯總資料」。

嘗試這些範例之前,請確定您已經瞭解何時該與不該使用每種類型寫入要求

Bigtable 的 Python 用戶端程式庫提供兩種 API,即 asyncio 和同步 API。如果應用程式是非同步,請使用 asyncio

本頁面的程式碼範例是指範例資料中的範例資料表。

執行簡易寫入作業作業

下列程式碼範例示範如何向 Bigtable 發出簡易寫入要求。這種類型的寫入會產生 MutateRow API 要求。

Go

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

import (
	"context"
	"encoding/binary"
	"fmt"
	"io"

	"bytes"

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

func writeSimple(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 := "stats_summary"
	timestamp := bigtable.Now()

	mut := bigtable.NewMutation()
	buf := new(bytes.Buffer)
	binary.Write(buf, binary.BigEndian, int64(1))

	mut.Set(columnFamilyName, "connected_cell", timestamp, buf.Bytes())
	mut.Set(columnFamilyName, "connected_wifi", timestamp, buf.Bytes())
	mut.Set(columnFamilyName, "os_build", timestamp, []byte("PQ2A.190405.003"))

	rowKey := "phone#4c410523#20190501"
	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
}

HBase

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。


import com.google.cloud.bigtable.hbase.BigtableConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

public class WriteSimple {

  private static final byte[] COLUMN_FAMILY_NAME = Bytes.toBytes("stats_summary");

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

    try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
      final Table table = connection.getTable(TableName.valueOf(Bytes.toBytes(tableId)));
      long timestamp = System.currentTimeMillis();
      byte[] one = new byte[]{0, 0, 0, 0, 0, 0, 0, 1};

      String rowKey = "phone#4c410523#20190501";
      Put put = new Put(Bytes.toBytes(rowKey));

      put.addColumn(COLUMN_FAMILY_NAME, Bytes.toBytes("connected_cell"), timestamp, one);
      put.addColumn(COLUMN_FAMILY_NAME, Bytes.toBytes("connected_wifi"), timestamp, one);
      put.addColumn(
          COLUMN_FAMILY_NAME,
          Bytes.toBytes("os_build"),
          timestamp,
          Bytes.toBytes("PQ2A.190405.003"));
      table.put(put);

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

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

Java

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。


import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.models.RowMutation;
import com.google.cloud.bigtable.data.v2.models.TableId;
import com.google.protobuf.ByteString;

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

  public static void writeSimple(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)) {
      long timestamp = System.currentTimeMillis() * 1000;

      String rowkey = "phone#4c410523#20190501";

      RowMutation rowMutation =
          RowMutation.create(TableId.of(tableId), rowkey)
              .setCell(
                  COLUMN_FAMILY_NAME,
                  ByteString.copyFrom("connected_cell".getBytes()),
                  timestamp,
                  1)
              .setCell(
                  COLUMN_FAMILY_NAME,
                  ByteString.copyFrom("connected_wifi".getBytes()),
                  timestamp,
                  1)
              .setCell(COLUMN_FAMILY_NAME, "os_build", timestamp, "PQ2A.190405.003");

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

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

Python asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

from google.cloud.bigtable.data import BigtableDataClientAsync
from google.cloud.bigtable.data import SetCell

async def write_simple(project_id, instance_id, table_id):
    async with BigtableDataClientAsync(project=project_id) as client:
        async with client.get_table(instance_id, table_id) as table:
            family_id = "stats_summary"
            row_key = b"phone#4c410523#20190501"

            cell_mutation = SetCell(family_id, "connected_cell", 1)
            wifi_mutation = SetCell(family_id, "connected_wifi", 1)
            os_mutation = SetCell(family_id, "os_build", "PQ2A.190405.003")

            await table.mutate_row(row_key, cell_mutation)
            await table.mutate_row(row_key, wifi_mutation)
            await table.mutate_row(row_key, os_mutation)

Python

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

from datetime import datetime, timezone

from google.cloud import bigtable


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

    timestamp = datetime.now(timezone.utc)
    column_family_id = "stats_summary"

    row_key = "phone#4c410523#20190501"

    row = table.direct_row(row_key)
    row.set_cell(column_family_id, "connected_cell", 1, timestamp)
    row.set_cell(column_family_id, "connected_wifi", 1, timestamp)
    row.set_cell(column_family_id, "os_build", "PQ2A.190405.003", timestamp)

    row.commit()

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

C#

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。


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

namespace Writes
{
    public class WriteSimpleSample
    {
        /// <summary>
        /// Mutate one row in an existing table and column family. Updates multiple cells within that row using one API call.
        ///</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 WriteSimple(
            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");
            BigtableVersion timestamp = new BigtableVersion(DateTime.UtcNow);
            string COLUMN_FAMILY = "stats_summary";

            Mutation[] mutations = {
                    Mutations.SetCell(COLUMN_FAMILY, "connected_cell", 1, timestamp),
                    Mutations.SetCell(COLUMN_FAMILY, "connected_wifi", 1, timestamp),
                    Mutations.SetCell(COLUMN_FAMILY, "os_build", "PQ2A.190405.003", timestamp)
                };
            MutateRowResponse mutateRowResponse = bigtableClient.MutateRow(tableName, rowkey, mutations);
            Console.WriteLine(mutateRowResponse);
            return $"Successfully wrote row {rowkey}";
        }
    }
}

C++

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

namespace cbt = ::google::cloud::bigtable;
[](cbt::Table table) {
  auto timestamp = std::chrono::duration_cast<std::chrono::milliseconds>(
      std::chrono::system_clock::now().time_since_epoch());

  std::string row_key = "phone#4c410523#20190501";
  cbt::SingleRowMutation mutation(row_key);
  std::string column_family = "stats_summary";

  mutation.emplace_back(cbt::SetCell(column_family, "connected_cell",
                                     timestamp, std::int64_t{1}));
  mutation.emplace_back(cbt::SetCell(column_family, "connected_wifi",
                                     timestamp, std::int64_t{1}));
  mutation.emplace_back(
      cbt::SetCell(column_family, "os_build", timestamp, "PQ2A.190405.003"));
  google::cloud::Status status = table.Apply(std::move(mutation));
  if (!status.ok()) throw std::runtime_error(status.message());
  std::cout << "Successfully wrote row" << row_key << "\n";
}

Node.js

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

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

async function writeSimple() {
  /**
   * TODO(developer): Uncomment these variables before running the sample.
   */
  // const instanceId = 'YOUR_INSTANCE_ID';
  // const tableId = 'YOUR_TABLE_ID';
  const instance = bigtable.instance(instanceId);
  const table = instance.table(tableId);

  const timestamp = new Date();
  const rowToInsert = {
    key: 'phone#4c410523#20190501',
    data: {
      stats_summary: {
        connected_cell: {
          value: 1,
          timestamp,
        },
        connected_wifi: {
          value: 1,
          timestamp,
        },
        os_build: {
          value: 'PQ2A.190405.003',
          timestamp,
        },
      },
    },
  };

  await table.insert(rowToInsert);

  console.log(`Successfully wrote row ${rowToInsert.key}`);
}

writeSimple();

PHP

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\DataUtil;
use Google\Cloud\Bigtable\Mutations;

/**
 * Write data 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 written
 */
function write_simple(
    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);

    $timestampMicros = time() * 1000 * 1000;
    $columnFamilyId = 'stats_summary';
    $mutations = (new Mutations())
    ->upsert($columnFamilyId, 'connected_cell', '1', $timestampMicros)