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 워크로드를 Bigtable로 이동해야 하는 경우 HappyBase 패키지를 사용하세요. 새 애플리케이션의 경우 Bigtable 패키지를 사용하는 "hello world" 예시를 참조하세요.

이 샘플 프로그램을 실행하려면 GitHub에서 샘플 안내를 따르세요.

HappyBase API를 Bigtable과 함께 사용

샘플 애플리케이션을 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()을 사용하여 테이블과 해당 column family를 만듭니다.

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)