Hello world HappyBase API

Contoh ini adalah aplikasi "hello world" yang sangat sederhana, yang ditulis dalam Python, yang mengilustrasikan cara:

  • Menyiapkan autentikasi
  • Menghubungkan ke instance Bigtable.
  • Buat tabel baru.
  • Tulis data ke tabel.
  • Baca kembali data.
  • Hapus tabel.

Menyiapkan autentikasi

Untuk menggunakan contoh Python di halaman ini dalam lingkungan pengembangan lokal, instal dan lakukan inisialisasi gcloud CLI, lalu siapkan Kredensial Default Aplikasi dengan kredensial pengguna Anda.

  1. Install the Google Cloud CLI.
  2. To initialize the gcloud CLI, run the following command:

    gcloud init
  3. 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.

Untuk informasi selengkapnya, lihat Set up authentication for a local development environment.

Menjalankan contoh

Contoh ini menggunakan paket HappyBase dari Library Klien Google Cloud untuk Python, implementasi HappyBase API, untuk berkomunikasi dengan Bigtable. Gunakan paket HappyBase jika Anda perlu memindahkan workload HBase yang ada ke Bigtable. Untuk aplikasi baru, lihat contoh"hello world" yang menggunakan paket Bigtable.

Untuk menjalankan program contoh ini, ikuti petunjuk untuk contoh di GitHub.

Menggunakan HappyBase API dengan Bigtable

Aplikasi contoh terhubung ke Bigtable dan menunjukkan beberapa operasi sederhana.

Menginstal dan mengimpor library klien

Paket Python yang diperlukan dapat diinstal menggunakan PIP ke dalam lingkungan virtualenv. Contoh ini menyertakan file persyaratan yang menentukan paket yang diperlukan.

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

Kemudian, modul dapat diimpor.

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

Menghubungkan ke Bigtable

Hubungkan ke Bigtable dengan meneruskan bigtable.Client ke 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)

Membuat tabel

Gunakan Connection.create_table() untuk membuat tabel dan grup kolomnya.

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

Menulis baris ke tabel

Dapatkan Table yang ada dengan Connection.table(). Gunakan Table.put() untuk menulis baris ke tabel.

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

Membaca baris berdasarkan kuncinya

Dapatkan baris secara langsung menggunakan kuncinya dengan 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")]))

Memindai semua baris tabel

Gunakan Table.scan() untuk mendapatkan rentang baris.

print("Scanning for all greetings:")

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

Menghapus tabel

Menghapus tabel dengan Connection.delete_table().

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

Menggabungkan semuanya

Berikut adalah contoh lengkapnya tanpa komentar.



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