프리픽스를 사용해 행 읽기

프리픽스를 사용해 쿼리를 만듭니다.

더 살펴보기

이 코드 샘플이 포함된 자세한 문서는 다음을 참조하세요.

코드 샘플

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);
  }
}

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;
}

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
}

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).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());
  }
}

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);
    }
}

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)

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

다음 단계

다른 Google Cloud 제품의 코드 샘플을 검색하고 필터링하려면 Google Cloud 샘플 브라우저를 참조하세요.