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++

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

C#

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

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

Java

For more information, see Setting Up a Java Development Environment. Si usas Maven, agrega lo siguiente a tu archivo pom.xml:
<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-bigtable</artifactId>
  <version>0.79.0-alpha</version>
</dependency>
Si usas Gradle, agrega lo siguiente a tus dependencias:
compile 'com.google.cloud:google-cloud-bigtable:0.79.0-alpha'
Si usas SBT, agrega lo siguiente a tus dependencias:
libraryDependencies += "com.google.cloud" % "google-cloud-bigtable" % "0.79.0-alpha"

HBase

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.

Si usas Maven, agrega lo siguiente a tu archivo pom.xml:
<dependency>
  <groupId>com.google.cloud.bigtable</groupId>
  <artifactId>bigtable-hbase-1.x</artifactId>
  <version>1.8.0</version>
</dependency>
Si usas Gradle, agrega lo siguiente a tus dependencias:
compile 'com.google.cloud.bigtable:bigtable-hbase-1.x:1.8.0'
Si usas SBT, agrega lo siguiente a tus dependencias:
libraryDependencies += "com.google.cloud.bigtable" % "bigtable-hbase-1.x" % "1.8.0"

Node.js

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

PHP

Install and enable the gRPC extension for PHP, then run the following command:
composer require google/cloud-bigtable

Python

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

Ruby

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 other ways to authenticate, see the GCP authentication documentation.

GCP Console

  1. En GCP Console, ve a la página Crear clave de la cuenta de servicio.

    Ir a la página Crear clave de la cuenta de servicio
  2. Desde la lista desplegable de la Cuenta de servicio, selecciona Nueva cuenta de servicio.
  3. En el campo Nombre de cuenta de servicio, ingresa un nombre.
  4. En la lista desplegable Función, selecciona Proyecto > Propietario.

    Nota: El campo Función autoriza tu cuenta de servicio para acceder a los recursos. Puedes ver y cambiar este campo luego con GCP Console. Si desarrollas una aplicación de producción, especifica permisos más detallados que Proyecto > Propietario. Para obtener más información, consulta Cómo otorgar funciones a las cuentas de servicio.
  5. Haz clic en Crear. Se descargará un archivo JSON a tu computadora que contiene tus descargas de claves.

Línea de comandos

Puedes ejecutar los siguientes comandos con el SDK de Cloud en tu máquina local o dentro de Cloud Shell.

  1. Crea la cuenta de servicio. Reemplaza [NAME] con el nombre que le quieres poner a la cuenta de servicio.

    gcloud iam service-accounts create [NAME]
  2. Otorga permisos a la cuenta de servicio. Reemplaza [PROJECT_ID] con el ID del proyecto.

    gcloud projects add-iam-policy-binding [PROJECT_ID] --member "serviceAccount:[NAME]@[PROJECT_ID].iam.gserviceaccount.com" --role "roles/owner"
    Nota: El campo Función autoriza a tu cuenta de servicio para acceder a los recursos. Puedes ver y cambiar este campo luego con GCP Console. Si desarrollas una aplicación de producción, especifica permisos más detallados que Proyecto > Propietario. Para obtener más información, consulta Cómo otorgar funciones a las cuentas de servicio.
  3. Genera el archivo de claves. Reemplaza [FILE_NAME] con un nombre para el archivo de claves.

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

Proporciónale las credenciales de autenticación a tu código de la aplicación mediante la configuración de la variable de entorno GOOGLE_APPLICATION_CREDENTIALS. Reemplaza [PATH] con la ruta de acceso al archivo JSON que contiene la clave de tu cuenta de servicio y [FILE_NAME] con el nombre del archivo. Esta variable solo se aplica a la sesión actual de shell. Por lo tanto, si abres una sesión nueva, deberás volver a configurar la variable.

Linux o macOS

export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por ejemplo:

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

Windows

Con PowerShell:

$env:GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

Por ejemplo:

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

Con el símbolo del sistema:

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

C++


#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,
                                                cbt::ClientOptions()),
                   table_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;
}

C#


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

            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


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

import (
	"context"
	"flag"
	"log"

	"cloud.google.com/go/bigtable"
)

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

Java


import com.google.api.gax.rpc.NotFoundException;
import com.google.cloud.bigtable.data.v2.BigtableDataClient;
import com.google.cloud.bigtable.data.v2.BigtableDataSettings;
import com.google.cloud.bigtable.data.v2.models.Row;
import com.google.cloud.bigtable.data.v2.models.RowCell;

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 =
        BigtableDataSettings.newBuilder().setProjectId(projectId).setInstanceId(instanceId).build();

    // 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()) {
        System.out.printf(
            "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());
    }
  }
}

HBase

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

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

Node.js

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

const bigtable = Bigtable();

async function quickstart() {
  // 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(singleRow.data, null, 4);
  console.log(`Row key: ${singleRow.id}\nData: ${rowData}`);
}
quickstart();

PHP


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

Python

import argparse

from google.cloud import bigtable


def main(project_id="project-id", instance_id="instance-id",
         table_id="my-table"):
    # 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(
        description=__doc__,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('project_id', help='Your Cloud Platform project ID.')
    parser.add_argument(
        'instance_id', help='ID of the Cloud Bigtable instance to connect to.')
    parser.add_argument(
        '--table',
        help='Existing table used in the quickstart.',
        default='my-table')

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

Ruby

# 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 = Google::Cloud.new
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

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.

¿Te sirvió esta página? Envíanos tu opinión:

Enviar comentarios sobre…

Cloud Bigtable Documentation