Guide de démarrage rapide Bigtable

Guide de démarrage rapide pour Cloud Bigtable, qui montre la connexion à une instance et la lecture d'une ligne depuis une table.

En savoir plus

Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les pages suivantes :

Exemple de code

C++

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

#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::MakeDataConnection(),
                   cbt::TableResource(project_id, instance_id, 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::move(result).status();
  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 (google::cloud::Status const& status) {
  std::cerr << "google::cloud::Status thrown: " << status << "\n";
  return 1;
}

C#

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.


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;
import com.google.cloud.bigtable.data.v2.models.TableId;

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

    quickstart(projectId, instanceId, tableId);
  }

  public static void quickstart(String projectId, String instanceId, String tableId) {
    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.of(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());
    }
  }
}

Node.js

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

const bigtable = new 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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

use Google\Cloud\Bigtable\BigtableClient;

/** Uncomment and populate these variables in your code */
// $projectId = 'The Google project ID';
// $instanceId = 'The Bigtable instance ID';
// $tableId = 'The Bigtable table ID';

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

$columnFamilyId = 'cf1';
$columnId = 'c1';
// Get the Value from the Row, using the column_family_id and column_id
$value = $row[$columnFamilyId][$columnId][0]['value'];

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

Python

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

Pour savoir comment installer et utiliser la bibliothèque cliente pour Bigtable, consultez la page Bibliothèques clientes Bigtable.

Pour vous authentifier auprès de Bigtable, configurez les Identifiants par défaut de l'application. Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.

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

# Instantiates a client
bigtable = Google::Cloud::Bigtable.new

# Your Cloud Bigtable instance ID
# instance_id = "my-instance"

# Your Cloud Bigtable table ID
# table_id = "my-table"

# Get table client
table = bigtable.table instance_id, table_id

# Read and print row
p table.read_row "user0000001"

Étapes suivantes

Pour rechercher et filtrer des exemples de code pour d'autres produits Google Cloud, consultez l'exemple de navigateur Google Cloud.