読み取りの例

Cloud Bigtable クライアント ライブラリを使用すると、テーブルからデータを読み取ることができます。このページでは、複数の言語における各タイプの読み取りリクエストの例を示します。概要については、読み取りをご覧ください。

必要なロール

テーブルからデータを読み取るために必要な権限を取得するには、Bigtable 読み取り roles/bigtable.reader)の IAM ロールを付与するよう、管理者に依頼してください。ロールの付与の詳細については、アクセスを管理するをご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

単一行の読み取り

次のコードサンプルは、行キーを使用してデータの単一行を取得する方法を示しています。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readRow(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)
	rowKey := "phone#4c410523#20190501"
	row, err := tbl.ReadRow(ctx, rowKey)
	if err != nil {
		return fmt.Errorf("could not read row with key %s: %w", rowKey, err)
	}

	printRow(w, row)
	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

/**
 * Example of reading an individual row key.
 */
public static void readRow() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRow(projectId, instanceId, tableId);
}

public static void readRow(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));

    byte[] rowkey = Bytes.toBytes("phone#4c410523#20190501");

    Result row = table.get(new Get(rowkey));
    printRow(row);

  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readRow() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRow(projectId, instanceId, tableId);
}

public static void readRow(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    String rowkey = "phone#4c410523#20190501";

    Row row = dataClient.readRow(TableId.of(tableId), rowkey);
    printRow(row);

  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python 非同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

from google.cloud.bigtable.data import BigtableDataClientAsync

async def read_row(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:
            row_key = "phone#4c410523#20190501"
            row = await table.read_row(row_key)
            print(row)

Python 同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

    row_key = "phone#4c410523#20190501"

    row = table.read_row(row_key)
    print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/// <summary>
/// /// Reads one row from an existing table.
///</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 readRow(
    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);
    Row row = bigtableClient.ReadRow(tableName, rowKey: "phone#4c410523#20190501");

    return printRow(row);
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](google::cloud::bigtable::Table table, std::string const& row_key) {
  StatusOr<std::pair<bool, cbt::Row>> tuple =
      table.ReadRow(row_key, cbt::Filter::PassAllFilter());
  if (!tuple) throw std::move(tuple).status();
  if (!tuple->first) {
    std::cout << "Row " << row_key << " not found\n";
    return;
  }
  PrintRow(tuple->second);
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

const rowkey = 'phone#4c410523#20190501';

const [row] = await table.row(rowkey).get();
printRow(rowkey, row.data);

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;

/**
 * Read a row using the row key
 *
 * @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 to read from
 */
function read_row(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $rowkey = 'phone#4c410523#20190501';
    $row = $table->readRow($rowkey);

    print_row($rowkey, $row);
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

  # instance_id = "my-instance"
  # table_id    = "my-table"
  bigtable = Google::Cloud::Bigtable.new
  table = bigtable.table instance_id, table_id

  row = table.read_row "phone#4c410523#20190501"
  print_row row
end

行の一部の読み取り

次のコードサンプルは、行から特定の列を取得する方法を示しています。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readRowPartial(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)
	rowKey := "phone#4c410523#20190501"
	row, err := tbl.ReadRow(ctx, rowKey, bigtable.RowFilter(bigtable.ColumnFilter("os_build")))
	if err != nil {
		return fmt.Errorf("could not read row with key %s: %w", rowKey, err)
	}

	printRow(w, row)

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

/**
 * Example of reading a subset of the columns for a single row.
 */
public static void readRowPartial() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowPartial(projectId, instanceId, tableId);
}

public static void readRowPartial(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));
    byte[] rowkey = Bytes.toBytes("phone#4c410523#20190501");

    Result row =
        table.get(
            new Get(rowkey).addColumn(Bytes.toBytes("stats_summary"), Bytes.toBytes("os_build")));
    printRow(row);

  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readRowPartial() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowPartial(projectId, instanceId, tableId);
}

public static void readRowPartial(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    String rowkey = "phone#4c410523#20190501";
    Filters.Filter filter =
        FILTERS
            .chain()
            .filter(FILTERS.family().exactMatch("stats_summary"))
            .filter(FILTERS.qualifier().exactMatch("os_build"));

    Row row = dataClient.readRow(TableId.of(tableId), rowkey, filter);
    printRow(row);

  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python 非同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

async def read_row_partial(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:
            row_key = "phone#4c410523#20190501"
            col_filter = row_filters.ColumnQualifierRegexFilter(b"os_build")

            row = await table.read_row(row_key, row_filter=col_filter)
            print(row)

Python 同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

    row_key = "phone#4c410523#20190501"
    col_filter = row_filters.ColumnQualifierRegexFilter(b"os_build")

    row = table.read_row(row_key, filter_=col_filter)
    print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/// <summary>
/// /// Reads part of one row from an existing table.
///</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 readRowPartial(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);
    String rowkey = "phone#4c410523#20190501";
    RowFilter filter = RowFilters.ColumnQualifierExact("os_build");
    Row row = bigtableClient.ReadRow(tableName, rowkey, filter);
    return printRow(row);
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](google::cloud::bigtable::Table table, std::string const& row_key) {
  StatusOr<std::pair<bool, cbt::Row>> tuple = table.ReadRow(
      row_key, cbt::Filter::ColumnName("stats_summary", "os_build"));
  if (!tuple) throw std::move(tuple).status();
  if (!tuple->first) {
    std::cout << "Row " << row_key << " not found\n";
    return;
  }
  PrintRow(tuple->second);
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

const COLUMN_FAMILY = 'stats_summary';
const COLUMN_QUALIFIER = 'os_build';
const rowkey = 'phone#4c410523#20190501';

const [row] = await table
  .row(rowkey)
  .get([`${COLUMN_FAMILY}:${COLUMN_QUALIFIER}`]);

printRow(rowkey, row);

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\Filter;

/**
 * Read partial row data
 *
 * @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 to read from
 */
function read_row_partial(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $rowkey = 'phone#4c410523#20190501';
    $rowFilter = Filter::qualifier()->regex('os_build');
    $row = $table->readRow($rowkey, ['filter' => $rowFilter]);

    print_row($rowkey, $row);
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

  # instance_id = "my-instance"
  # table_id    = "my-table"
  bigtable = Google::Cloud::Bigtable.new
  table = bigtable.table instance_id, table_id
  filter = Google::Cloud::Bigtable::RowFilter.qualifier "os_build"

  row = table.read_row "phone#4c410523#20190501", filter: filter
  print_row row
end

複数行の読み取り

次のコードサンプルは、一連の行キーを使用して複数行のデータを取得する方法を示しています。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readRows(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)
	err = tbl.ReadRows(ctx, bigtable.RowList{"phone#4c410523#20190501", "phone#4c410523#20190502"},
		func(row bigtable.Row) bool {
			printRow(w, row)
			return true
		},
	)
	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/**
 * Example of reading multiple row keys.
 */
public static void readRows() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRows(projectId, instanceId, tableId);
}

public static void readRows(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));
    List<Get> queryRowList = new ArrayList<Get>();
    queryRowList.add(new Get(Bytes.toBytes("phone#4c410523#20190501")));
    queryRowList.add(new Get(Bytes.toBytes("phone#4c410523#20190502")));

    Result[] rows = table.get(queryRowList);

    for (Result row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readRows() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRows(projectId, instanceId, tableId);
}

public static void readRows(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    Query query =
        Query.create(TableId.of(tableId))
            .rowKey("phone#4c410523#20190501")
            .rowKey("phone#4c410523#20190502");
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python 非同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

async def read_rows(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:

            query = ReadRowsQuery(row_keys=[
                b"phone#4c410523#20190501",
                b"phone#4c410523#20190502"
            ])
            async for row in await table.read_rows_stream(query):
                print(row)

Python 同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

    row_set = RowSet()
    row_set.add_row_key(b"phone#4c410523#20190501")
    row_set.add_row_key(b"phone#4c410523#20190502")

    rows = table.read_rows(row_set=row_set)
    for row in rows:
        print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。



/// <summary>
/// /// Reads multiple rows from an existing table.
///</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 readRows(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);

    RowSet rowSet = RowSet.FromRowKeys("phone#4c410523#20190501", "phone#4c410523#20190502");
    ReadRowsStream readRowsStream = bigtableClient.ReadRows(tableName, rowSet);

    string result = "";
    readRowsStream.ForEach(row => result += printRow(row));

    return result;
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](cbt::Table table) {
  // Read and print the rows.
  for (StatusOr<cbt::Row>& row : table.ReadRows(
           cbt::RowSet("phone#4c410523#20190501", "phone#4c410523#20190502"),
           cbt::Filter::PassAllFilter())) {
    if (!row) throw std::move(row).status();
    PrintRow(*row);
  }
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

const rowKeys = ['phone#4c410523#20190501', 'phone#4c410523#20190502'];
const [rows] = await table.getRows({keys: rowKeys});
rows.forEach(row => printRow(row.id, row.data));

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;

/**
 * Read rows using an array of keys
 *
 * @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 to read from
 */
function read_rows(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $rows = $table->readRows(
        ['rowKeys' => ['phone#4c410523#20190501', 'phone#4c410523#20190502']]
    );

    foreach ($rows as $key => $row) {
        print_row($key, $row);
    }
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

# instance_id = "my-instance"
# table_id    = "my-table"
bigtable = Google::Cloud::Bigtable.new
table = bigtable.table instance_id, table_id

table.read_rows(keys: ["phone#4c410523#20190501", "phone#4c410523#20190502"]).each do |row|
  print_row row
end

行の範囲の読み取り

次のコードサンプルは、開始キーと終了キーを使用して複数行のデータを取得する方法を示しています。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readRowRange(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)
	err = tbl.ReadRows(ctx, bigtable.NewRange("phone#4c410523#20190501", "phone#4c410523#201906201"),
		func(row bigtable.Row) bool {
			printRow(w, row)
			return true
		},
	)

	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/**
 * Example of reading a range of rows using a key range.
 */
public static void readRowRange() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowRange(projectId, instanceId, tableId);
}

public static void readRowRange(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));

    Scan rangeQuery =
        new Scan()
            .withStartRow(Bytes.toBytes("phone#4c410523#20190501"))
            .withStopRow(Bytes.toBytes("phone#4c410523#201906201"));

    ResultScanner rows = table.getScanner(rangeQuery);

    for (Result row : rows) {
      printRow(row);
    }

  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readRowRange() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowRange(projectId, instanceId, tableId);
}

public static void readRowRange(String projectId, String instanceId, String tableId) {
  String start = "phone#4c410523#20190501";
  String end = "phone#4c410523#201906201";

  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    Query query = Query.create(TableId.of(tableId)).range(start, end);
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python 非同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

from google.cloud.bigtable.data import BigtableDataClientAsync
from google.cloud.bigtable.data import ReadRowsQuery
from google.cloud.bigtable.data import RowRange

async def read_row_range(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:

            row_range = RowRange(
                start_key=b"phone#4c410523#20190501",
                end_key=b"phone#4c410523#201906201"
            )
            query = ReadRowsQuery(row_ranges=[row_range])

            async for row in await table.read_rows_stream(query):
                print(row)

Python 同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

    row_set = RowSet()
    row_set.add_row_range_from_keys(
        start_key=b"phone#4c410523#20190501", end_key=b"phone#4c410523#201906201"
    )

    rows = table.read_rows(row_set=row_set)
    for row in rows:
        print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/// <summary>
/// /// Reads a range of rows from an existing table.
///</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 readRowRange(string projectId = "YOUR-PROJECT-ID", string instanceId = "YOUR-INSTANCE-ID", string tableId = "YOUR-TABLE-ID")
{
    String start = "phone#4c410523#20190501";
    String end = "phone#4c410523#201906201";

    BigtableClient bigtableClient = BigtableClient.Create();
    TableName tableName = new TableName(projectId, instanceId, tableId);
    RowSet rowSet = RowSet.FromRowRanges(RowRange.ClosedOpen(start, end));
    ReadRowsStream readRowsStream = bigtableClient.ReadRows(tableName, rowSet);

    string result = "";
    readRowsStream.ForEach(row => result += printRow(row));

    return result;
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](cbt::Table table) {
  // Read and print the rows.
  for (StatusOr<cbt::Row>& row :
       table.ReadRows(cbt::RowRange::Range("phone#4c410523#20190501",
                                           "phone#4c410523#201906201"),
                      cbt::Filter::PassAllFilter())) {
    if (!row) throw std::move(row).status();
    PrintRow(*row);
  }
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

const start = 'phone#4c410523#20190501';
const end = 'phone#4c410523#201906201';

await table
  .createReadStream({
    start,
    end,
  })
  .on('error', err => {
    // Handle the error.
    console.log(err);
  })
  .on('data', row => printRow(row.id, row.data))
  .on('end', () => {
    // All rows retrieved.
  });

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;

/**
 * Read using a range for row keys
 *
 * @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 to read from
 */
function read_row_range(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $rows = $table->readRows([
        'rowRanges' => [
            [
                'startKeyClosed' => 'phone#4c410523#20190501',
                'endKeyOpen' => 'phone#4c410523#201906201'
            ]
        ]
    ]);

    foreach ($rows as $key => $row) {
        print_row($key, $row);
    }
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

# instance_id = "my-instance"
# table_id    = "my-table"
bigtable = Google::Cloud::Bigtable.new
table = bigtable.table instance_id, table_id

range = table.new_row_range.between "phone#4c410523#20190501", "phone#4c410523#201906201"
table.read_rows(ranges: range).each do |row|
  print_row row
end

複数の行範囲の読み取り

次のコードサンプルは、複数の開始キーと終了キーを使用して複数行のデータを取得する方法を示しています。1 つのリクエストで多数の行範囲をリクエストすると、読み取りのパフォーマンスに影響を与える可能性があります。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readRowRanges(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)
	err = tbl.ReadRows(ctx, bigtable.RowRangeList{
		bigtable.NewRange("phone#4c410523#20190501", "phone#4c410523#201906201"),
		bigtable.NewRange("phone#5c10102#20190501", "phone#5c10102#201906201"),
	},
		func(row bigtable.Row) bool {
			printRow(w, row)
			return true
		},
	)
	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

/**
 * Example of reading multiple disjoint row ranges.
 */
public static void readRowRanges() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowRanges(projectId, instanceId, tableId);
}

public static void readRowRanges(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));
    List<RowRange> ranges = new ArrayList<>();

    ranges.add(
        new RowRange(
            Bytes.toBytes("phone#4c410523#20190501"),
            true,
            Bytes.toBytes("phone#4c410523#20190601"),
            false));
    ranges.add(
        new RowRange(
            Bytes.toBytes("phone#5c10102#20190501"),
            true,
            Bytes.toBytes("phone#5c10102#20190601"),
            false));
    Filter filter = new MultiRowRangeFilter(ranges);
    Scan scan = new Scan().setFilter(filter);

    ResultScanner rows = table.getScanner(scan);

    for (Result row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readRowRanges() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowRanges(projectId, instanceId, tableId);
}

public static void readRowRanges(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    Query query =
        Query.create(TableId.of(tableId))
            .range("phone#4c410523#20190501", "phone#4c410523#20190601")
            .range("phone#5c10102#20190501", "phone#5c10102#20190601");
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

    row_set = RowSet()
    row_set.add_row_range_from_keys(
        start_key=b"phone#4c410523#20190501", end_key=b"phone#4c410523#201906201"
    )
    row_set.add_row_range_from_keys(
        start_key=b"phone#5c10102#20190501", end_key=b"phone#5c10102#201906201"
    )

    rows = table.read_rows(row_set=row_set)
    for row in rows:
        print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/// <summary>
/// /// Reads multiple ranges of rows from an existing table.
///</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 readRowRanges(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);
    RowSet rowSet = RowSet.FromRowRanges(RowRange.ClosedOpen("phone#4c410523#20190501", "phone#4c410523#20190601"),
    RowRange.ClosedOpen("phone#5c10102#20190501", "phone#5c10102#20190601"));
    ReadRowsStream readRowsStream = bigtableClient.ReadRows(tableName, rowSet);

    string result = "";
    readRowsStream.ForEach(row => result += printRow(row));

    return result;
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](cbt::Table table) {
  // Read and print the rows.
  for (StatusOr<cbt::Row>& row : table.ReadRows(
           cbt::RowSet({cbt::RowRange::Range("phone#4c410523#20190501",
                                             "phone#4c410523#20190601"),
                        cbt::RowRange::Range("phone#5c10102#20190501",
                                             "phone#5c10102#20190601")}),
           cbt::Filter::PassAllFilter())) {
    if (!row) throw std::move(row).status();
    PrintRow(*row);
  }
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

await table
  .createReadStream({
    ranges: [
      {
        start: 'phone#4c410523#20190501',
        end: 'phone#4c410523#20190601',
      },
      {
        start: 'phone#5c10102#20190501',
        end: 'phone#5c10102#20190601',
      },
    ],
  })
  .on('error', err => {
    // Handle the error.
    console.log(err);
  })
  .on('data', row => printRow(row.id, row.data))
  .on('end', () => {
    // All rows retrieved.
  });

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;

/**
 * Read using multiple ranges for row keys
 *
 * @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 to read from
 */
function read_row_ranges(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $rows = $table->readRows([
        'rowRanges' => [
            [
                'startKeyClosed' => 'phone#4c410523#20190501',
                'endKeyOpen' => 'phone#4c410523#201906201'
            ],
            [
                'startKeyClosed' => 'phone#5c10102#20190501',
                'endKeyOpen' => 'phone#5c10102#201906201'
            ]
        ]
    ]);

    foreach ($rows as $key => $row) {
        print_row($key, $row);
    }
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

# instance_id = "my-instance"
# table_id    = "my-table"
bigtable = Google::Cloud::Bigtable.new
table = bigtable.table instance_id, table_id

ranges = []
ranges <<
  table.new_row_range.between("phone#4c410523#20190501", "phone#4c410523#201906201") <<
  table.new_row_range.between("phone#5c10102#20190501", "phone#5c10102#201906201")
table.read_rows(ranges: ranges).each do |row|
  print_row row
end

行キー接頭辞を使用した複数行の読み取り

次のコードサンプルは、行キー接頭辞を使用して複数行のデータを取得する方法を示しています。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readPrefix(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)
	err = tbl.ReadRows(ctx, bigtable.PrefixRange("phone#"),
		func(row bigtable.Row) bool {
			printRow(w, row)
			return true
		},
	)
	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/**
 * Example of reading a range of rows using a row prefix.
 */
public static void readPrefix() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readPrefix(projectId, instanceId, tableId);
}

public static void readPrefix(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));
    Scan prefixScan = new Scan().setRowPrefixFilter(Bytes.toBytes("phone"));
    ResultScanner rows = table.getScanner(prefixScan);

    for (Result row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readPrefix() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readPrefix(projectId, instanceId, tableId);
}

public static void readPrefix(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    Query query = Query.create(TableId.of(tableId)).prefix("phone");
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python 非同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

from google.cloud.bigtable.data import BigtableDataClientAsync
from google.cloud.bigtable.data import ReadRowsQuery
from google.cloud.bigtable.data import RowRange

async def read_prefix(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:

            prefix = "phone#"
            end_key = prefix[:-1] + chr(ord(prefix[-1]) + 1)
            prefix_range = RowRange(start_key=prefix, end_key=end_key)
            query = ReadRowsQuery(row_ranges=[prefix_range])

            async for row in await table.read_rows_stream(query):
                print(row)

Python 同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

def read_prefix(project_id, instance_id, table_id):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    table = instance.table(table_id)
    prefix = "phone#"
    end_key = prefix[:-1] + chr(ord(prefix[-1]) + 1)

    row_set = RowSet()
    row_set.add_row_range_from_keys(prefix.encode("utf-8"), end_key.encode("utf-8"))

    rows = table.read_rows(row_set=row_set)
    for row in rows:
        print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/// <summary>
/// /// Reads rows starting with a prefix from an existing table.
///</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 readPrefix(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);

    String prefix = "phone";
    Char prefixEndChar = prefix[prefix.Length - 1];
    prefixEndChar++;
    String end = prefix.Substring(0, prefix.Length - 1) + prefixEndChar;
    RowSet rowSet = RowSet.FromRowRanges(RowRange.Closed(prefix, end));
    ReadRowsStream readRowsStream = bigtableClient.ReadRows(tableName, rowSet);

    string result = "";
    readRowsStream.ForEach(row => result += printRow(row));

    return result;
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](cbt::Table table) {
  // Read and print the rows.
  for (StatusOr<cbt::Row>& row : table.ReadRows(
           cbt::RowRange::Prefix("phone"), cbt::Filter::PassAllFilter())) {
    if (!row) throw std::move(row).status();
    PrintRow(*row);
  }
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

const prefix = 'phone#';

await table
  .createReadStream({
    prefix,
  })
  .on('error', err => {
    // Handle the error.
    console.log(err);
  })
  .on('data', row => printRow(row.id, row.data))
  .on('end', () => {
    // All rows retrieved.
  });

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;

/**
 * Read using a row key prefix
 *
 * @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 to read from
 */
function read_prefix(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $prefix = 'phone#';
    $end = $prefix;
    // Increment the last character of the prefix so the filter matches everything in between
    $end[-1] = chr(
        ord($end[-1]) + 1
    );

    $rows = $table->readRows([
        'rowRanges' => [
            [
                'startKeyClosed' => $prefix,
                'endKeyClosed' => $end,
            ]
        ]
    ]);

    foreach ($rows as $key => $row) {
        print_row($key, $row);
    }
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

# instance_id = "my-instance"
# table_id    = "my-table"
bigtable = Google::Cloud::Bigtable.new
table = bigtable.table instance_id, table_id

prefix = "phone#"
end_key = prefix[0...-1] + prefix[-1].next
range = table.new_row_range.between prefix, end_key
table.read_rows(ranges: range).each do |row|
  print_row row
end

逆方向にスキャン

以下のコードサンプルは、逆方向にスキャンする方法を示しています。詳しくは、リバース スキャンをご覧ください。効率の低下を避けるため、リバース スキャンの行数を約 50 に制限します。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readRowsReversed(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)
	err = tbl.ReadRows(ctx, bigtable.NewRange("phone#5c10102", "phone#5c10103"),
		func(row bigtable.Row) bool {
			printRow(w, row)
			return true
		},
		bigtable.ReverseScan())
	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

/**
 * Example of reading a range of rows in reverse order.
 */
public static void readRowsReversed() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowsReversed(projectId, instanceId, tableId);
}

public static void readRowsReversed(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));
    Scan revScan =
        new Scan()
            .setReversed(true)
            .setLimit(2)
            .withStartRow(Bytes.toBytes("phone#4c410523#20190505"));
    ResultScanner rows = table.getScanner(revScan);

    for (Result row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

この例では、接頭辞、開始行キー、終了行キーを使用しているため、この 2 つのフィルタを組み合わせた結果が返されます。

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readRowsReversed() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readRowsReversed(projectId, instanceId, tableId);
}

public static void readRowsReversed(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    Query query =
        Query.create(TableId.of(tableId))
            .reversed(true)
            .limit(3)
            .prefix("phone#4c410523")
            .range("phone#5c10102", "phone#5c10103");
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::Options;
using ::google::cloud::StatusOr;
[](cbt::Table table) {
  // Read and print the rows.
  auto reader = table.ReadRows(
      cbt::RowRange::RightOpen("phone#5c10102", "phone#5c10103"), 3,
      cbt::Filter::PassAllFilter(),
      Options{}.set<cbt::ReverseScanOption>(true));
  for (StatusOr<cbt::Row>& row : reader) {
    if (!row) throw std::move(row).status();
    PrintRow(*row);
  }
}

フィルタを使った読み取り

次のコードサンプルは、行フィルタを使用して複数行のデータを取得する方法を示しています。読み取りリクエストで使用できるフィルタの種類について詳しくは、フィルタの概要をご覧ください。複数の言語でさまざまな種類のフィルタを実装する方法を示す追加のコードサンプルもご利用いただけます。

Go

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

func readFilter(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)
	err = tbl.ReadRows(ctx, bigtable.RowRange{},
		func(row bigtable.Row) bool {
			printRow(w, row)
			return true
		},
		bigtable.RowFilter(bigtable.ValueFilter("PQ2A.*$")),
	)
	if err != nil {
		return fmt.Errorf("tbl.ReadRows: %w", err)
	}

	return nil
}

HBase

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/**
 * Example of filtering row contents using filters.
 */
public static void readFilter() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readFilter(projectId, instanceId, tableId);
}

public static void readFilter(String projectId, String instanceId, String tableId) {
  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests.
  try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {
    Table table = connection.getTable(TableName.valueOf(tableId));

    ValueFilter valueFilter =
        new ValueFilter(CompareOp.EQUAL, new RegexStringComparator("PQ2A.*"));
    Scan scan = new Scan().setFilter(valueFilter);

    ResultScanner rows = table.getScanner(scan);

    for (Result row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Java

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

public static void readFilter() {
  // TODO(developer): Replace these variables before running the sample.
  String projectId = "my-project-id";
  String instanceId = "my-instance-id";
  String tableId = "mobile-time-series";
  readFilter(projectId, instanceId, tableId);
}

public static void readFilter(String projectId, String instanceId, String tableId) {
  Filters.Filter filter = FILTERS.value().regex("PQ2A.*");

  // Initialize client that will be used to send requests. This client only needs to be created
  // once, and can be reused for multiple requests. After completing all of your requests, call
  // the "close" method on the client to safely clean up any remaining background resources.
  try (BigtableDataClient dataClient = BigtableDataClient.create(projectId, instanceId)) {
    Query query = Query.create(TableId.of(tableId)).filter(filter);
    ServerStream<Row> rows = dataClient.readRows(query);
    for (Row row : rows) {
      printRow(row);
    }
  } catch (IOException e) {
    System.out.println(
        "Unable to initialize service client, as a network error occurred: \n" + e.toString());
  }
}

Python 非同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

from google.cloud.bigtable.data import BigtableDataClientAsync
from google.cloud.bigtable.data import ReadRowsQuery
from google.cloud.bigtable.data import row_filters

async def read_with_filter(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:

            row_filter = row_filters.ValueRegexFilter(b"PQ2A.*$")
            query = ReadRowsQuery(row_filter=row_filter)

            async for row in await table.read_rows_stream(query):
                print(row)

Python 同期

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

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

    rows = table.read_rows(filter_=row_filters.ValueRegexFilter(b"PQ2A.*$"))
    for row in rows:
        print_row(row)

C#

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。


/// <summary>
/// /// Reads using a filter from an existing table.
///</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 readFilter(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);

    RowFilter filter = RowFilters.ValueRegex("PQ2A.*");

    ReadRowsStream readRowsStream = bigtableClient.ReadRows(tableName, filter: filter);
    string result = "";
    readRowsStream.ForEach(row => result += printRow(row));

    return result;
}

C++

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

namespace cbt = ::google::cloud::bigtable;
using ::google::cloud::StatusOr;
[](cbt::Table table) {
  // Read and print the rows.
  for (StatusOr<cbt::Row>& row :
       table.ReadRows(cbt::RowRange::InfiniteRange(),
                      cbt::Filter::ValueRegex("PQ2A.*"))) {
    if (!row) throw std::move(row).status();
    PrintRow(*row);
  }
}

Node.js

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

const filter = {
  value: /PQ2A.*$/,
};

await table
  .createReadStream({
    filter,
  })
  .on('error', err => {
    // Handle the error.
    console.log(err);
  })
  .on('data', row => printRow(row.id, row.data))
  .on('end', () => {
    // All rows retrieved.
  });

PHP

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

use Google\Cloud\Bigtable\BigtableClient;
use Google\Cloud\Bigtable\Filter;

/**
 * Read using a filter
 *
 * @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 to read from
 */
function read_filter(
    string $projectId,
    string $instanceId,
    string $tableId
): void {
    // Connect to an existing table with an existing instance.
    $dataClient = new BigtableClient([
        'projectId' => $projectId,
    ]);
    $table = $dataClient->table($instanceId, $tableId);

    $rowFilter = Filter::value()->regex('PQ2A.*$');

    $rows = $table->readRows([
        'filter' => $rowFilter
    ]);

    foreach ($rows as $key => $row) {
        print_row($key, $row);
    }
}

Ruby

Bigtable 用のクライアント ライブラリをインストールして使用する方法については、Bigtable クライアント ライブラリをご覧ください。

Bigtable で認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、クライアント ライブラリの認証を設定するをご覧ください。

# instance_id = "my-instance"
# table_id    = "my-table"
bigtable = Google::Cloud::Bigtable.new
table = bigtable.table instance_id, table_id

filter = Google::Cloud::Bigtable::RowFilter.value "PQ2A.*$"
table.read_rows(filter: filter).each do |row|
  print_row row
end

次のステップ