HappyBase API の Hello World

この例は、以下の方法を示す、Python で記述された非常に単純な「Hello World」アプリケーションです。

  • 認証の設定
  • Bigtable インスタンスに接続する
  • 新しいテーブルを作成する
  • テーブルにデータを書き込む
  • そのデータを読み取る
  • テーブルを削除する

認証の設定

このページの Python サンプルをローカル開発環境から使用するには、gcloud CLI をインストールして初期化し、自身のユーザー認証情報を使用してアプリケーションのデフォルト認証情報を設定してください。

  1. Google Cloud CLI をインストールします。
  2. gcloud CLI を初期化するには:

    gcloud init
  3. Google アカウントのローカル認証情報を作成します。

    gcloud auth application-default login

詳細については、 ローカル開発環境の認証の設定 をご覧ください。

サンプルの実行

この例では、HappyBase API の実装である Python 用 Google Cloud クライアント ライブラリHappyBase パッケージを使用して Bigtable と通信します。既存の HBase ワークロードを Cloud Bigtable に移動する必要がある場合、HappyBase パッケージを使用してください。新しいアプリケーションについては、Bigtable パッケージを使用する「Hello World」の例をご覧ください。

このサンプル プログラムを実行するには、GitHub でのサンプルの手順に沿って操作してください。

Bigtable での HappyBase API の使用

このサンプル アプリケーションは Bigtable に接続して、いくつかの単純なオペレーションを行います。

クライアント ライブラリのインストールとインポート

必要な Python パッケージは、PIP を使用して virtualenv 環境にインストールできます。サンプルには、必要なパッケージを定義する要件ファイルが含まれています。

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

その後、このモジュールをインポートできます。

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

Bigtable への接続

bigtable.Clienthappybase.Connection に渡して Bigtable に接続します。

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

テーブルの作成

Connection.create_table() を使用して、テーブルとその列ファミリーを作成します。

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

テーブルへの行の書き込み

Connection.table() を使用して、既存の Table を取得します。Table.put() を使用して、テーブルに行を書き込みます。

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

キーによる行の読み取り

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

すべてのテーブル行のスキャン

Table.scan() を使用して、行の範囲を取得します。

print("Scanning for all greetings:")

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

テーブルの削除

Connection.delete_table() を使用して、テーブルを削除します。

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

すべてを組み合わせる

コメントなしの例を以下に示します。



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