‫HappyBase API hello world

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

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

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

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

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

  2. אם אתם משתמשים בספק זהויות חיצוני (IdP), קודם אתם צריכים להיכנס ל-CLI של gcloud באמצעות המאגר המאוחד לניהול זהויות.

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

    gcloud auth application-default login

    אם אתם משתמשים ב-Cloud Shell, אין צורך לבצע את הפעולה הזו.

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

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

הרצת הדוגמה

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

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

שימוש בממשקי HappyBase API עם 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)