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

C/C++

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

C#

Install-Package Google.Cloud.Bigtable.V2 -Pre
Install-Package Google.Cloud.Bigtable.Admin.V2 -Pre

Go

go get -u cloud.google.com/go/bigtable

HappyBase

pip install --upgrade google-cloud-happybase

HBase Java

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.

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

If you are using Maven, add this to your pom.xml file:
<dependency>
  <groupId>com.google.cloud.bigtable</groupId>
  <artifactId>bigtable-hbase-1.x</artifactId>
  <version>1.4.0</version>
</dependency>
If you are using Gradle, add this to your dependencies:
compile 'com.google.cloud.bigtable:bigtable-hbase-1.x:1.4.0'
If you are using SBT, add this to your dependencies:
libraryDependencies += "com.google.cloud.bigtable" % "bigtable-hbase-1.x" % "1.4.0"

Node.js

npm install --save @google-cloud/bigtable

Python

For more on setting up your Python development environment, refer to Python Development Environment Setup Guide.
pip install --upgrade 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.

GCP Console

  1. Go to the Create service account key page in the GCP Console.

    Go to the Create Service Account Key page
  2. From the Service account drop-down list, select New service account.
  3. Enter a name into the Service account name field.
  4. From the Role drop-down list, select Project > Owner.

    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  5. Click Create. A JSON file that contains your key downloads to your computer.

Command line

You can run the following commands using the Cloud SDK on your local machine, or within Cloud Shell.

  1. Create the service account. Replace [NAME] with your desired service account name.

    gcloud iam service-accounts create [NAME]
  2. Grant permissions to the service account. Replace [PROJECT_ID] with your project ID.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Note: The Role field authorizes your service account to access resources. You can view and change this field later using GCP Console. If you are developing a production application, specify more granular permissions than Project > Owner. For more information, see granting roles to service accounts.
  3. Generate the key file. Replace [FILE_NAME] with a name for the key file.

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

Provide authentication credentials to your application code by setting the environment variable GOOGLE_APPLICATION_CREDENTIALS. Replace [PATH] with the file path of the JSON file that contains your service account key, and [FILE_NAME] with the filename. This variable only applies to your current shell session, so if you open a new session, set the variable again.

Linux or macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

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

Windows

With PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

For example:

$env:GOOGLE_APPLICATION_CREDENTIALS="C:\Users\username\Downloads\[FILE_NAME].json"

With command prompt:

set GOOGLE_APPLICATION_CREDENTIALS=[PATH]

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 Quickstart using cbt for instructions.

C/C++

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

#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>" << std::endl;
    return 1;
  }

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

  google::cloud::bigtable::Table table(
      google::cloud::bigtable::CreateDefaultDataClient(
          project_id, instance_id, google::cloud::bigtable::ClientOptions()),
      table_id);

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

  std::cout << "Getting a single row by row key:" << std::flush;
  auto result = table.ReadRow(
      row_key, google::cloud::bigtable::Filter::FamilyRegex(column_family));
  if (not result.first) {
    std::cout << "Cannot find row " << row_key << " in the table: " << table_id
              << std::endl;
    return 0;
  }

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

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

C#

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

using System;
// 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";

            try
            {
                // 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;
        }
    }
}

Go

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

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

import (
	"flag"
	"log"

	"cloud.google.com/go/bigtable"
	"golang.org/x/net/context"
)

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

HappyBase

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

This code sample is coming soon.

HBase Java

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

package com.example.cloud.bigtable.quickstart;

import com.google.cloud.bigtable.hbase.BigtableConfiguration;

import java.io.IOException;
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)) {

      // 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";

        // 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("Row r1: %s", rowValue);

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

Node.js

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

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

// The ID of the Cloud Bigtable instance
const INSTANCE_ID = 'my-bigtable-instance';
// The ID of the Cloud Bigtable table
const TABLE_ID = 'my-table';
const GCLOUD_PROJECT = process.env.GCLOUD_PROJECT;

if (!GCLOUD_PROJECT) {
  throw new Error('Environment variables GCLOUD_PROJECT must be set!');
}

(async () => {
  try {
    var bigtableOptions = {
      projectId: GCLOUD_PROJECT,
    };

    const bigtable = Bigtable(bigtableOptions);
    // Creates a Bigtable client
    //const bigtable = new Bigtable(bigtableOptions);

    // 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
    let [singleRow] = await table.row('r1').get();

    // Print the row key and data (column value, labels, timestamp)
    console.log(
      `Row key: ${singleRow.id}\nData: ${JSON.stringify(
        singleRow.data,
        null,
        4
      )}`
    );
  } catch (err) {
    // Handle error performing the read operation
    console.error(`Error reading row r1:`, err);
  }
})();

Python

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

This code sample is coming soon.

Additional Resources

Third party Cloud Bigtable API client libraries

Scio

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.

Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Bigtable Documentation