HappyBase API Hello World

Dieses Beispiel ist eine sehr einfache "Hallo Welt"-Anwendung, geschrieben in Python, die veranschaulicht wie:

  • Authentifizierung einrichten
  • Mit einer Bigtable-Instanz verbinden.
  • Erstellen einer neuen Tabelle
  • Schreiben von Daten in die Tabelle
  • Lesen von Daten aus der Tabelle
  • Löschen einer Tabelle

Authentifizierung einrichten

Wenn Sie die Python Beispiele auf dieser Seite in einer lokalen Entwicklungsumgebung verwenden möchten, installieren und initialisieren Sie die gcloud CLI und richten dann die Standardanmeldedaten für Anwendungen mit Ihren Nutzeranmeldedaten ein.

  1. Installieren Sie die Google Cloud CLI.
  2. Führen Sie folgenden Befehl aus, um die gcloud CLI zu initialisieren:

    gcloud init
  3. Erstellen Sie lokale Anmeldedaten zur Authentifizierung für Ihr Google-Konto:

    gcloud auth application-default login

Weitere Informationen unter Set up authentication for a local development environment.

Beispiel ausführen

In diesem Beispiel wird über das HappyBase-Paket der Google Cloud-Clientbibliothek für Python, eine Implementierung der HappyBase, mit Bigtable kommuniziert. Verwenden Sie das HappyBase-Paket, wenn Sie eine vorhandene HBase-Arbeitslast in Bigtable verschieben möchten. Neue Anwendungen finden Sie im "Hello World"-Beispiel, das das Bigtable-Paket verwendet.

Folgen Sie der Anleitung zum Beispiel auf GitHub, um das Beispielprogramm auszuführen.

HappyBase APIs mit Bigtable verwenden

Die Beispielanwendung stellt eine Verbindung zu Bigtable her und zeigt einige einfache Vorgänge.

Client-Bibliothek importieren und installieren

Die benötigten Python-Pakete können mit PIP in einer virtualenv-Umgebung installiert werden. Das Beispiel enthält eine Anforderungsdatei, die die benötigten Pakete definiert.

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

Die Module können dann importiert werden.

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

Verbindung zu Bigtable herstellen

Stellen Sie eine Verbindung zu Bigtable her. Übergeben Sie dafür bigtable.Client an 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)

Tabelle erstellen

Verwenden Sie Connection.create_table(), um eine Tabelle und ihre Spaltenfamilien zu erstellen.

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

Zeilen in eine Tabelle schreiben

Rufen Sie mit Connection.table() ein vorhandenes Table ab. Verwenden Sie Table.put(), um eine Zeile in die Tabelle zu schreiben.

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

Zeile nach ihrem Schlüssel lesen

Rufen Sie eine Zeile direkt mit ihrem Schlüssel mit Table.row() ab.

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

Alle Tabellenzeilen scannen

Verwenden Sie Table.scan(), um einen Zeilenbereich abzurufen.

print("Scanning for all greetings:")

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

Tabelle löschen

Löschen Sie eine Tabelle mit Connection.delete_table().

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

Zusammenfassung

Hier ist das gesamte Beispiel ohne Kommentare:



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