‫HappyBase API hello world

הדוגמה הזו היא אפליקציית hello world פשוטה מאוד, שנכתבה ב-Python, שממחישה איך:

  • מגדירים אימות
  • מתחברים למכונה של Bigtable.
  • ליצור טבלה חדשה.
  • כתיבת נתונים בטבלה.
  • קוראים את הנתונים בחזרה.
  • מוחקים את הטבלה.

מגדירים אימות

כדי להשתמש בסביבת פיתוח מקומית בדוגמאות של Python שבדף הזה, מתקינים ומפעילים את ה-CLI של gcloud, ואז מגדירים את Application Default Credentials באמצעות פרטי הכניסה של המשתמש.

  1. התקינו את ה-CLI של Google Cloud.

  2. הגדירו שה-CLI של gcloud ישתמש בזהות המאוחדת שלכם.

    איך נכנסים ל-CLI של gcloud באמצעות הזהות המאוחדת?

  3. יוצרים פרטי כניסה לאימות מקומי עבור חשבון המשתמש:

    gcloud auth application-default login

    אם מוחזרת שגיאת אימות, צריך לוודא ש נכנסתם ל-CLI של gcloud באמצעות הזהות המאוחדת שלכם.

מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

הרצת הדוגמה

בדוגמה הזו משתמשים בחבילת HappyBase של ספריית הלקוח של Google Cloud ל-Python, הטמעה של ממשקי ה-API של HappyBase, כדי לתקשר עם Bigtable. אם אתם צריכים להעביר עומס עבודה קיים של HBase אל Bigtable, אתם יכולים להשתמש בחבילת HappyBase. לגבי אפליקציות חדשות, אפשר לעיין בדוגמה 'hello world' שמשתמשת בחבילת Bigtable.

כדי להריץ את תוכנית הדוגמה הזו, פועלים לפי ההוראות לדוגמה ב-GitHub.

שימוש בממשקי ה-API של HappyBase עם Bigtable

האפליקציה לדוגמה מתחברת ל-Bigtable ומדגימה כמה פעולות פשוטות.

התקנה וייבוא של ספריית הלקוח

אפשר להתקין את חבילות Python הנדרשות באמצעות PIP בסביבת virtualenv. הדוגמה כוללת קובץ דרישות שמגדיר את החבילות הנדרשות.

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

אחר כך אפשר לייבא את המודולים.

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

התחברות ל-Bigtable

מתחברים ל-Bigtable על ידי העברת bigtable.Client אל 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)

יצירת טבלה

משתמשים ב-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.
)

כתיבת שורות בטבלה

קבלת מינוי קיים ל-Table עם Connection.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 ..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)