Hello World da API HappyBase

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

  • Configurar a autenticação
  • Conecte 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 os exemplos do Python nesta página em um ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e configure o Application Default Credentials com suas credenciais de usuário.

  1. Instale a Google Cloud CLI.

  2. Ao usar um provedor de identidade (IdP) externo, primeiro faça login na CLI gcloud com sua identidade federada.

  3. Se você estiver usando um shell local, crie credenciais de autenticação local para sua conta de usuário:

    gcloud auth application-default login

    Não é necessário fazer isso se você estiver usando o Cloud Shell.

    Se um erro de autenticação for retornado e você estiver usando um provedor de identidade (IdP) externo, confirme se você fez login na CLI gcloud com sua identidade federada.

Para mais informações, consulte 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.17.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 a bigtable.Client para a 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 ..utils import wait_for_table

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

        wait_for_table(instance.table(table_name))

        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")]))

    finally:
        print("Deleting the {} table.".format(table_name))
        connection.delete_table(table_name)
        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)