Exemplo simples da API HappyBase

Este exemplo é uma aplicação "hello world" muito simples, escrita em Python, que ilustra como:

  • Configure a autenticação
  • Estabeleça ligação a uma instância do Bigtable.
  • Criar uma nova tabela.
  • Escreva dados na tabela.
  • Ler os dados novamente.
  • Eliminar a tabela.

Configure a autenticação

Para usar os Python exemplos nesta página num ambiente de desenvolvimento local, instale e inicialize a CLI gcloud e, em seguida, configure as Credenciais predefinidas da aplicação com as suas credenciais de utilizador.

    Instale a CLI Google Cloud.

    Se estiver a usar um fornecedor de identidade (IdP) externo, primeiro tem de iniciar sessão na CLI gcloud com a sua identidade federada.

    If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

Para mais informações, consulte Set up authentication for a local development environment.

Executar o exemplo

Este exemplo usa o pacote HappyBase da biblioteca cliente do Google Cloud para Python, uma implementação das APIs HappyBase, para comunicar com o Bigtable. Use o pacote HappyBase se precisar de mover uma carga de trabalho do HBase existente para o Bigtable. Para novas aplicações, consulte o exemplo"Olá, mundo!" que usa o pacote Bigtable.

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

Usar as APIs HappyBase com o Bigtable

A aplicação de exemplo liga-se ao Bigtable e demonstra algumas operações simples.

Instalar e importar a biblioteca de cliente

Os pacotes Python necessários podem ser instalados através do PIP num ambiente virtualenv. O exemplo inclui um ficheiro 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

Em seguida, os módulos podem ser importados.

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

Associar ao Bigtable

Ligue-se ao Bigtable transmitindo um bigtable.Client a um 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)

Criar uma tabela

Use Connection.create_table() para criar uma tabela e as respetivas famílias de colunas.

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

Escrever linhas numa tabela

Obtenha um Table existente com Connection.table(). Use Table.put() para escrever 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")})

Ler uma linha pela respetiva chave

Obtenha uma linha diretamente através da respetiva 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")]))

Analisar todas as linhas da tabela

Use Table.scan() para obter 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")]))

Eliminar uma tabela

Elimine uma tabela com Connection.delete_table().

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

A reunir tudo

Segue-se 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)