Hello World da API HappyBase

Este exemplo é um aplicativo "Hello World" muito simples, escrito em Python, que ilustra como:

  • Configurar a autenticação
  • Conectar-se a uma instância do Bigtable.
  • criar uma nova tabela;
  • Gravação de dados na tabela
  • Leitura dos dados
  • Exclusão da tabela

Configurar a autenticação

Para usar as amostras de Python nesta página de um ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure o Application Default Credentials com as credenciais de usuário.

  1. Instale a CLI do Google Cloud.
  2. Para inicializar a CLI gcloud, execute o seguinte comando:

    gcloud init
  3. Crie as credenciais de autenticação para sua Conta do Google:

    gcloud auth application-default login

Veja mais informações em: Configurar a autenticação para um ambiente de desenvolvimento local.

Como executar a amostra

Este exemplo usa o pacote do HappyBase da biblioteca de cliente do Google Cloud para Python, uma implementação das APIs do HappyBase para se comunicar com o Bigtable. Use o pacote do HappyBase se precisar mover uma carga de trabalho do HBase para o Bigtable. Para novos aplicativos, consulte o exemplo de"hello world" que usa o pacote do Bigtable.

Para executar este programa de amostra, siga as instruções do exemplo no GitHub.

Como usar as APIs HappyBase com o Bigtable

O aplicativo de amostra conecta-se ao Bigtable e demonstra algumas operações simples.

Como instalar e importar a biblioteca de cliente

Os pacotes necessários do Python podem ser instalados usando o PIP em um ambiente virtualenv. A amostra inclui um arquivo de requisitos que define os pacotes necessários.

google-cloud-happybase==0.33.0
six==1.16.0 # See https://github.com/googleapis/google-cloud-python-happybase/issues/128

Os módulos podem então ser importados.

from google.cloud import bigtable
from google.cloud import happybase

Como se conectar ao Bigtable

Conecte-se ao Bigtable transferindo um bigtable.Client para happybase.Connection.

# The client must be created with admin=True because it will create a
# table.
client = bigtable.Client(project=project_id, admin=True)
instance = client.instance(instance_id)
connection = happybase.Connection(instance=instance)

Como criar uma tabela

Use Connection.create_table() para criar uma tabela e os grupos de colunas dela.

print("Creating the {} table.".format(table_name))
column_family_name = "cf1"
connection.create_table(
    table_name, {column_family_name: dict()}  # Use default options.
)

Como gravar linhas em uma tabela

Receba um Table existente com Connection.table(). Use Table.put() para gravar uma linha na tabela.

print("Writing some greetings to the table.")
table = connection.table(table_name)
column_name = "{fam}:greeting".format(fam=column_family_name)
greetings = [
    "Hello World!",
    "Hello Cloud Bigtable!",
    "Hello HappyBase!",
]

for i, value in enumerate(greetings):
    # Note: This example uses sequential numeric IDs for simplicity,
    # but this can result in poor performance in a production
    # application.  Since rows are stored in sorted order by key,
    # sequential keys can result in poor distribution of operations
    # across nodes.
    #
    # For more information about how to design a Bigtable schema for
    # the best performance, see the documentation:
    #
    #     https://cloud.google.com/bigtable/docs/schema-design
    row_key = "greeting{}".format(i)
    table.put(row_key, {column_name.encode("utf-8"): value.encode("utf-8")})

Como ler uma linha pela chave

Receba uma linha diretamente usando a chave com Table.row().

print("Getting a single greeting by row key.")
key = "greeting0".encode("utf-8")
row = table.row(key)
print("\t{}: {}".format(key, row[column_name.encode("utf-8")]))

Como verificar todas as linhas da tabela

Use Table.scan() para receber um intervalo de linhas.

print("Scanning for all greetings:")

for key, row in table.scan():
    print("\t{}: {}".format(key, row[column_name.encode("utf-8")]))

Como excluir tabelas

Exclua uma tabela com Connection.delete_table().

print("Deleting the {} table.".format(table_name))
connection.delete_table(table_name)

Como tudo funciona em conjunto

Aqui está o exemplo completo sem comentários.



"""Demonstrates how to connect to Cloud Bigtable and run some basic operations.

Prerequisites:

- Create a Cloud Bigtable cluster.
  https://cloud.google.com/bigtable/docs/creating-cluster
- Set your Google Application Default Credentials.
  https://developers.google.com/identity/protocols/application-default-credentials
"""

import argparse

from google.cloud import bigtable
from google.cloud import happybase

def main(project_id, instance_id, table_name):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)
    connection = happybase.Connection(instance=instance)

    try:
        print("Creating the {} table.".format(table_name))
        column_family_name = "cf1"
        connection.create_table(
            table_name, {column_family_name: dict()}  # Use default options.
        )

        print("Writing some greetings to the table.")
        table = connection.table(table_name)
        column_name = "{fam}:greeting".format(fam=column_family_name)
        greetings = [
            "Hello World!",
            "Hello Cloud Bigtable!",
            "Hello HappyBase!",
        ]

        for i, value in enumerate(greetings):
            row_key = "greeting{}".format(i)
            table.put(row_key, {column_name.encode("utf-8"): value.encode("utf-8")})

        print("Getting a single greeting by row key.")
        key = "greeting0".encode("utf-8")
        row = table.row(key)
        print("\t{}: {}".format(key, row[column_name.encode("utf-8")]))

        print("Scanning for all greetings:")

        for key, row in table.scan():
            print("\t{}: {}".format(key, row[column_name.encode("utf-8")]))

        print("Deleting the {} table.".format(table_name))
        connection.delete_table(table_name)

    finally:
        connection.close()

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="Table to create and destroy.", default="Hello-Bigtable"
    )

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