Cloud Bigtable Client Libraries

This page shows how to get started with the Cloud Client Libraries for the Cloud Bigtable API. Read more about the client libraries for Cloud APIs in Client Libraries Explained.

Installing the client library


See the GitHub README for details about this client library's requirements and install dependencies.


For more information, see Setting Up a C# Development Environment.
Install-Package Google.Cloud.Bigtable.V2 -Pre
Install-Package Google.Cloud.Bigtable.Admin.V2 -Pre


go get -u


pip install --upgrade google-cloud-happybase


For more information, see Setting Up a Java Development Environment.

If you are using Maven, add this to your pom.xml file


If you are using Gradle, add this to your dependencies

compile ''

If you are using SBT, add this to your dependencies

libraryDependencies += "" % "google-cloud-bigtable" % "0.95.0-alpha"


The Cloud Bigtable HBase client for Java includes the following Maven artifacts that you can use in your project. All of the artifacts are based on HBase 1.x:

The Cloud Bigtable Maven artifacts include the netty-tcnative-boringssl-static library, which requires that you use Linux, macOS, or Windows on an x86 64-bit processor.

If your application runs in the App Engine standard environment, you must use a current version of the Java runtime. The Java 7 runtime is deprecated and does not support the HBase client for Java.

The following examples assume that you are using the bigtable-hbase-1.x artifact.

如果您是使用 Maven,請在 pom.xml 檔案中新增以下指令:
如果您是使用 Gradle,請在相依元件中新增以下指令:
compile ''
如果您是使用 SBT,請在相依元件中新增以下指令:
libraryDependencies += "" % "bigtable-hbase-1.x" % "1.8.0"


For more information, see Setting Up a Node.js Development Environment.
npm install --save @google-cloud/bigtable


Install and enable the gRPC extension for PHP, then run the following command:

composer require google/cloud-bigtable


For more information, see Setting Up a Python Development Environment.
pip install --upgrade google-cloud-bigtable


For more information, see Setting Up a Ruby Development Environment.
gem install google-cloud-bigtable

Setting up authentication

To run the client library, you must first set up authentication by creating a service account and setting an environment variable. Complete the following steps to set up authentication. For more information, see the GCP authentication documentation .

GCP 主控台

  1. 在 GCP 主控台中,前往「Create service account key」(建立服務帳戶金鑰) 頁面。

    前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面
  2. 從 [Service account] (服務帳戶) 清單中選取 [New service account] (新增服務帳戶)
  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
  4. 從 [Role] (角色) 清單中,選取 [Project] (專案) > [Owner] (擁有者)

    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。以後您可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  5. 點選 [建立]。一個包含您金鑰的 JSON 檔案會下載到電腦中。


您可以使用本機電腦上的 Cloud SDK,或在 Cloud Shell 內執行下列指令。

  1. 建立服務帳戶。將 [NAME] 換成服務帳戶的名稱。

    gcloud iam service-accounts create [NAME]
  2. 向服務帳戶授予權限。用您的專案 ID 取代 [PROJECT_ID]

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID]" --role "roles/owner"
    附註:「Role」(角色) 欄位會授權服務帳戶存取資源。您稍後可以使用 GCP 主控台查看及變更這個欄位。如果您要開發正式版應用程式,請指定比 [Project] (專案) > [Owner] (擁有者) 更精細的權限。詳情請參閱為服務帳戶授予角色一文。
  3. 產生金鑰檔案。用金鑰檔案的名稱取代 [FILE_NAME]

    gcloud iam service-accounts keys create [FILE_NAME].json --iam-account [NAME]@[PROJECT_ID]

設定環境變數 GOOGLE_APPLICATION_CREDENTIALS 來為應用程式程式碼提供驗證憑證。 將 [PATH] 改成包含您的服務帳戶金鑰的 JSON 檔案路徑,並將 [FILE_NAME] 改成檔案名稱。 此變數僅適用於您目前的殼層工作階段,所以如果您開啟新的工作階段,請再次設定變數。

Linux 或 macOS



export GOOGLE_APPLICATION_CREDENTIALS="/home/user/Downloads/[FILE_NAME].json"


使用 PowerShell:






Using the client library

The following example shows how to use the client library. The example connects to a Cloud Bigtable instance and reads a row from a table.

If you haven't stored any data in Cloud Bigtable yet, you can use the cbt command-line tool to create a table and add some data. See the quickstart using cbt for instructions.


#include "google/cloud/bigtable/table.h"

int main(int argc, char* argv[]) try {
  if (argc != 4) {
    std::string const cmd = argv[0];
    auto last_slash = std::string(cmd).find_last_of('/');
    std::cerr << "Usage: " << cmd.substr(last_slash + 1)
              << " <project_id> <instance_id> <table_id>\n";
    return 1;

  std::string const project_id = argv[1];
  std::string const instance_id = argv[2];
  std::string const table_id = argv[3];

  // Create a namespace alias to make the code easier to read.
  namespace cbt = google::cloud::bigtable;

  cbt::Table table(cbt::CreateDefaultDataClient(project_id, instance_id,

  std::string row_key = "r1";
  std::string column_family = "cf1";

  std::cout << "Getting a single row by row key:" << std::flush;
  google::cloud::StatusOr<std::pair<bool, cbt::Row>> result =
      table.ReadRow(row_key, cbt::Filter::FamilyRegex(column_family));
  if (!result) {
    throw std::runtime_error(result.status().message());
  if (!result->first) {
    std::cout << "Cannot find row " << row_key << " in the table: " << table_id
              << "\n";
    return 0;

  cbt::Cell const& cell = result->second.cells().front();
  std::cout << cell.family_name() << ":" << cell.column_qualifier() << "    @ "
            << cell.timestamp().count() << "us\n"
            << '"' << cell.value() << '"' << "\n";

  return 0;
} catch (std::exception const& ex) {
  std::cerr << "Standard C++ exception raised: " << ex.what() << "\n";
  return 1;


using System;
using Google.Cloud.Bigtable.Common.V2;
// Imports the Google Cloud client library
using Google.Cloud.Bigtable.V2;

namespace GoogleCloudSamples.Bigtable
    public class QuickStart
        public static int Main(string[] args)
            // Your Google Cloud Platform project ID
            const string projectId = "YOUR-PROJECT-ID";
            // The name of the Cloud Bigtable instance
            const string instanceId = "YOUR-INSTANCE-ID";
            // The name of the Cloud Bigtable table
            const string tableId = "my-table";

                // Creates a Bigtable client
                BigtableClient bigtableClient = BigtableClient.Create();

                // Read a row from my-table using a row key
                Row row = bigtableClient.ReadRow(
                    new TableName(projectId, instanceId, tableId), "r1", RowFilters.CellsPerRowLimit(1));
                // Print the row key and data (column value, labels, timestamp)
                Console.WriteLine($"{"Row key:",-30}{row.Key.ToStringUtf8()}\n" +
                                  $"{"  Column Family:",-30}{row.Families[0].Name}\n" +
                                  $"{"    Column Qualifyer:",-30}{row.Families[0].Columns[0].Qualifier.ToStringUtf8()}\n" +
                                  $"{"      Value:",-30}{row.Families[0].Columns[0].Cells[0].Value.ToStringUtf8()}\n" +
                                  $"{"      Labels:",-30}{row.Families[0].Columns[0].Cells[0].Labels}\n" +
                                  $"{"      Timestamp:",-30}{row.Families[0].Columns[0].Cells[0].TimestampMicros}\n");
            catch (Exception ex)
                // Handle error performing the read operation
                Console.WriteLine($"Error reading row r1: {ex.Message}");
            return 0;


// Quickstart is a sample program demonstrating use of the Cloud Bigtable client
// library to read a row from an existing table.
package main

import (


func main() {
	projectID := "my-project-id"   // The Google Cloud Platform project ID
	instanceID := "my-instance-id" // The Google Cloud Bigtable instance ID
	tableID := "my-table"          // The Google Cloud Bigtable table

	ctx := context.Background()

	// Set up Bigtable data operations client.
	client, err := bigtable.NewClient(ctx, projectID, instanceID)
	if err != nil {
		log.Fatalf("Could not create data operations client: %v", err)

	tbl := client.Open(tableID)

	// Read data in a row using a row key
	rowKey := "r1"
	columnFamilyName := "cf1"

	log.Printf("Getting a single row by row key:")
	row, err := tbl.ReadRow(ctx, rowKey)
	if err != nil {
		log.Fatalf("Could not read row with key %s: %v", rowKey, err)
	log.Printf("Row key: %s\n", rowKey)
	log.Printf("Data: %s\n", string(row[columnFamilyName][0].Value))

	if err = client.Close(); err != nil {
		log.Fatalf("Could not close data operations client: %v", err)


Read more in the API Reference Documentation for the Cloud Bigtable API HappyBase Client Library.

This code sample is coming soon.



public class Quickstart {

  public static void quickstart(String projectId, String instanceId, String tableId) {
    // String projectId = "my-project-id";
    // String instanceId = "my-instance-id";
    // String tableId = "my-table-id";

    BigtableDataSettings settings =

    // 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(settings)) {
      System.out.println("\nReading a single row by row key");
      Row row = dataClient.readRow(tableId, "r1");
      System.out.println("Row: " + row.getKey().toStringUtf8());
      for (RowCell cell : row.getCells()) {
            "Family: %s    Qualifier: %s    Value: %s%n",
            cell.getFamily(), cell.getQualifier().toStringUtf8(), cell.getValue().toStringUtf8());
    } catch (NotFoundException e) {
      System.err.println("Failed to read from a non-existent table: " + e.getMessage());
    } catch (Exception e) {
      System.out.println("Error during quickstart: \n" + e.toString());


Read more in the API Reference Documentation for the Cloud Bigtable HBase Client for Java.



import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.Table;
import org.apache.hadoop.hbase.util.Bytes;

 * A quickstart application that shows connecting to a Cloud Bigtable instance
 * using the native HBase API to read a row from a table.
public class Quickstart {

  public static void main(String... args) {

    String projectId = args[0];  // my-gcp-project-id
    String instanceId = args[1]; // my-bigtable-instance-id
    String tableId = args[2];    // my-bigtable-table-id

    // Create a connection to the Cloud Bigtable instance.
    // Use try-with-resources to make sure the connection is closed correctly
    try (Connection connection = BigtableConfiguration.connect(projectId, instanceId)) {

      System.out.println("--- Connection established with Bigtable Instance ---");
      // Create a connection to the table that already exists
      // Use try-with-resources to make sure the connection to the table is closed correctly
      try (Table table = connection.getTable(TableName.valueOf(tableId))) {

        // Read a row
        String rowKey = "r1";
        System.out.printf("--- Reading for row-key: %s for provided table: %s ---\n",
            rowKey, tableId);

        // Retrieve the result
        Result result = table.get(new Get(Bytes.toBytes(rowKey)));

        // Convert row data to string
        String rowValue = Bytes.toString(result.value());

        System.out.printf("Scanned value for Row r1: %s \n", rowValue);

        System.out.println(" --- Finished reading row --- ");

      }  catch (IOException e) {
        // handle exception while connecting to a table
        throw e;
    } catch (IOException e) {
      System.err.println("Exception while running quickstart: " + e.getMessage());


// Imports the Google Cloud client library
const Bigtable = require('@google-cloud/bigtable');

async function quickstart(
  INSTANCE_ID = 'my-instance', // ID of the Cloud Bigtable instance
  TABLE_ID = 'my-table' // ID of the Cloud Bigtable table
) {
  const bigtable = Bigtable();

  // Connect to an existing instance:my-bigtable-instance
  const instance = bigtable.instance(INSTANCE_ID);

  // Connect to an existing table:my-table
  const table = instance.table(TABLE_ID);

  // Read a row from my-table using a row key
  const [singleRow] = await table.row('r1').get();

  // Print the row key and data (column value, labels, timestamp)
  const rowData = JSON.stringify(, null, 4);
  console.log(`Row key: ${}\nData: ${rowData}`);


use Google\Cloud\Bigtable\BigtableClient;

/** Uncomment and populate these variables in your code */
// $project_id = 'The Google project ID';
// $instance_id = 'The Bigtable instance ID';
// $table_id = 'The Bigtable table ID';

// Connect to an existing table with an existing instance.
$dataClient = new BigtableClient([
    'projectId' => $project_id,
$table = $dataClient->table($instance_id, $table_id);
$key = 'r1';
// Read a row from my-table using a row key
$row = $table->readRow($key);

$column_family_id = 'cf1';
$column_id = 'c1';
// Get the Value from the Row, using the column_family_id and column_id

$value = $row[$column_family_id][$column_id][0]['value'];

printf("Row key: %s\nData: %s\n", $key, $value);


import argparse

from import bigtable

def main(project_id="project-id", instance_id="instance-id",
    # Create a Cloud Bigtable client.
    client = bigtable.Client(project=project_id)

    # Connect to an existing Cloud Bigtable instance.
    instance = client.instance(instance_id)

    # Open an existing table.
    table = instance.table(table_id)

    row_key = 'r1'
    row = table.read_row(row_key.encode('utf-8'))

    column_family_id = 'cf1'
    column_id = 'c1'.encode('utf-8')
    value = row.cells[column_family_id][column_id][0].value.decode('utf-8')

    print('Row key: {}\nData: {}'.format(row_key, value))

if __name__ == '__main__':
    parser = argparse.ArgumentParser(
    parser.add_argument('project_id', help='Your Cloud Platform project ID.')
        'instance_id', help='ID of the Cloud Bigtable instance to connect to.')
        help='Existing table used in the quickstart.',

    args = parser.parse_args()
    main(args.project_id, args.instance_id, args.table)


# Import google bigtable client lib
require "google-cloud-bigtable"

# The name of the Cloud Bigtable instance
INSTANCE_NAME = "my-bigtable-instance"

#  The name of the Cloud Bigtable table
TABLE_NAME = "my-table"

gcloud =
bigtable = gcloud.bigtable

# Get table client
table = bigtable.table(INSTANCE_NAME, TABLE_NAME)

# Read and print row
pp table.read_row("user00000001")

Additional resources

Third-party Cloud Bigtable API client libraries


The Scio client library provides a Scala API for Cloud Dataflow, which can read from and write to Cloud Bigtable. The Scio repository provides sample code for a Cloud Dataflow pipeline that uses Cloud Bigtable.



Cloud Bigtable Documentation