读取示例
Cloud Bigtable 客户端库提供从表格中读取数据的功能。本页面提供各种类型读取请求多种语言版本的示例。如需查看概览,请参阅读取。
读取一行
以下代码示例展示如何使用行键获取单行数据。
Go
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
/**
* 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
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, rowkey);
printRow(row);
} catch (IOException e) {
System.out.println(
"Unable to initialize service client, as a network error occurred: \n" + e.toString());
}
}
Python
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#
/// <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++
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
const rowkey = 'phone#4c410523#20190501';
const [row] = await table.row(rowkey).get();
printRow(rowkey, row.data);
PHP
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
# 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
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
/**
* 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
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, rowkey, filter);
printRow(row);
} catch (IOException e) {
System.out.println(
"Unable to initialize service client, as a network error occurred: \n" + e.toString());
}
}
Python
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#
/// <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++
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
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
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
# 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
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
/**
* 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
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).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
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#
/// <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++
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
const rowKeys = ['phone#4c410523#20190501', 'phone#4c410523#20190502'];
const [rows] = await table.getRows({keys: rowKeys});
rows.forEach(row => printRow(row.id, row.data));
PHP
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
# 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
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
/**
* 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
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).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
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#
/// <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++
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
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
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
# 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
读取多个范围内的行
以下代码示例展示如何使用多个开始键和结束键获取多行数据。 请注意,在单个请求中请求大量的行范围可能会影响读取性能。
Go
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
/**
* 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
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)
.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
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#
/// <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++
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
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
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
# 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
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
/**
* 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
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());
}
}
Python
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#
/// <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++
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
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
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
# 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 行。HBase
/**
* 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
由于此示例使用前缀以及开始和结束行键,因此它将返回两个过滤条件的并集的结果。
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)
.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++
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
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
/**
* 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
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).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
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#
/// <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++
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
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
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
# 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