Python hello world

本範例是以 Python 編寫的「hello world」應用程式,說明如何執行以下操作:

  • 設定驗證方法。
  • 連線至 Bigtable 執行個體。
  • 建立新的資料表。
  • 將資料寫入資料表。
  • 讀取資料。
  • 刪除資料表。

Bigtable 的 Python 用戶端程式庫提供兩種 API,即 asyncio 和同步 API。如果應用程式是非同步,請使用 asyncio

設定驗證方法

如要在本機開發環境中使用本頁的 Python 範例,請安裝並初始化 gcloud CLI,然後使用您的使用者憑證設定應用程式預設憑證。

  1. 安裝 Google Cloud CLI。

  2. 若您採用的是外部識別資訊提供者 (IdP),請先使用聯合身分登入 gcloud CLI

  3. 如果您使用本機殼層,請為使用者帳戶建立本機驗證憑證:

    gcloud auth application-default login

    如果您使用 Cloud Shell,則不需要執行這項操作。

    如果系統傳回驗證錯誤,且您使用外部識別資訊提供者 (IdP),請確認您已 使用聯合身分登入 gcloud CLI

詳情請參閱 這篇文章,瞭解如何設定本機開發環境的驗證機制。

執行範例

本範例使用 Python 適用的 Cloud 用戶端程式庫Bigtable 套件,與 Bigtable 進行通訊。新應用程式最適合使用 Bigtable 套件。如要將現有的 HBase 工作負載移至 Bigtable,請參閱使用 HappyBase 套件的「hello world」範例

如要執行這個範例程式,請依照 GitHub 網頁上的說明操作。

搭配 Bigtable 使用 Cloud 用戶端程式庫

這個應用程式範例會連線至 Bigtable,示範部分作業。

安裝及匯入用戶端程式庫

使用 PIP 將需要的 Python 套件安裝到 virtualenv 環境中。範例包含定義必要套件的需求檔案

google-cloud-bigtable==2.35.0
google-cloud-core==2.5.0

匯入模組。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

from google.cloud import bigtable
from google.cloud.bigtable.data import row_filters

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

from datetime import datetime, timezone

from google.cloud import bigtable
from google.cloud.bigtable import column_family
from google.cloud.bigtable import row_filters

連線至 Bigtable

使用 bigtable.Client 連線至 Bigtable。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

client = bigtable.data.BigtableDataClientAsync(project=project_id)
table = client.get_table(instance_id, table_id)

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 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)

建立資料表

使用 Instance.table() 將資料表物件例項化。建立資料欄系列並設定其垃圾回收政策,然後將資料欄系列傳遞至 Table.create() 以建立資料表。

print("Creating the {} table.".format(table_id))
table = instance.table(table_id)

print("Creating column family cf1 with Max Version GC rule...")
# Create a column family with GC policy : most recent N versions
# Define the GC policy to retain only the most recent 2 versions
max_versions_rule = bigtable.column_family.MaxVersionsGCRule(2)
column_family_id = b"cf1"
column_families = {column_family_id: max_versions_rule}
if not table.exists():
    table.create(column_families=column_families)
else:
    print("Table {} already exists.".format(table_id))

將資料列寫入資料表

循環處理問候語字串清單,以在資料表中建立一些新的資料列。在每個疊代中,使用 Table.row() 定義資料列並指派資料列索引鍵;呼叫 Row.set_cell() 為目前儲存格設定值;並將新資料列附加到資料列陣列。最後呼叫 Table.mutate_rows(),將資料列新增到資料表。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

print("Writing some greetings to the table.")
greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
mutations = []
column = b"greeting"
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.
    #
    # We recommend that you use bytestrings directly for row keys
    # where possible, rather than encoding strings.
    #
    # 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 = f"greeting{i}".encode()
    row_mutation = bigtable.data.RowMutationEntry(
        row_key, bigtable.data.SetCell(column_family_id, column, value)
    )
    mutations.append(row_mutation)
await table.bulk_mutate_rows(mutations)

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

print("Writing some greetings to the table.")
greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
rows = []
column = b"greeting"
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.
    #
    # We recommend that you use bytestrings directly for row keys
    # where possible, rather than encoding strings.
    #
    # 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 = f"greeting{i}".encode()
    row = table.direct_row(row_key)
    row.set_cell(
        column_family_id, column, value, timestamp=datetime.now(timezone.utc),
    )
    rows.append(row)
table.mutate_rows(rows)

建立篩選器

讀取已寫入的資料前,請先使用 row_filters.CellsColumnLimitFilter() 建立篩選器,藉此限制 Bigtable 傳回的資料。即使資料表中含有每個資料欄尚未在垃圾回收期間移除的較舊儲存格,篩選器仍能指示 Bigtable 僅傳回每個資料欄的最新儲存格。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

# Create a filter to only retrieve the most recent version of the cell
# for each column across entire row.
row_filter = bigtable.data.row_filters.CellsColumnLimitFilter(1)

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

row_filter = bigtable.row_filters.CellsColumnLimitFilter(1)

依資料列索引鍵讀取資料列

呼叫資料表的 Table.read_row() 方法,透過特定資料列索引鍵取得資料列的參考資料並傳入索引鍵和篩選器,即可取得該資料列中每個資料值的一個版本。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

print("Getting a single greeting by row key.")
key = "greeting0".encode()

row = await table.read_row(key, row_filter=row_filter)
cell = row.cells[0]
print(cell.value.decode("utf-8"))

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

print("Getting a single greeting by row key.")
key = b"greeting0"

row = table.read_row(key, row_filter)
cell = row.cells[column_family_id.decode("utf-8")][column][0]
print(cell.value.decode("utf-8"))

掃描所有資料表列

使用 Table.read_rows() 讀取資料表中特定範圍的資料列。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

print("Scanning for all greetings:")
query = bigtable.data.ReadRowsQuery(row_filter=row_filter)
async for row in await table.read_rows_stream(query):
    cell = row.cells[0]
    print(cell.value.decode("utf-8"))

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。

print("Scanning for all greetings:")
partial_rows = table.read_rows(filter_=row_filter)

for row in partial_rows:
    column_family_id_str = column_family_id.decode("utf-8")
    cell = row.cells[column_family_id_str][column][0]
    print(cell.value.decode("utf-8"))

刪除資料表

使用 Table.delete() 刪除資料表。

print("Deleting the {} table.".format(table_id))
table.delete()

馬上開始全面整合吧!

以下是沒有註解的完整範例。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。



"""Demonstrates how to connect to Cloud Bigtable and run some basic operations with the async APIs

Prerequisites:

- Create a Cloud Bigtable instance.
  https://cloud.google.com/bigtable/docs/creating-instance
- Set your Google Application Default Credentials.
  https://developers.google.com/identity/protocols/application-default-credentials
"""

import argparse
import asyncio
from ..utils import wait_for_table

from google.cloud import bigtable
from google.cloud.bigtable.data import row_filters

row_filters


async def main(project_id, instance_id, table_id):
    client = bigtable.data.BigtableDataClientAsync(project=project_id)
    table = client.get_table(instance_id, table_id)

    from google.cloud.bigtable import column_family

    print("Creating the {} table.".format(table_id))
    admin_client = bigtable.Client(project=project_id, admin=True)
    admin_instance = admin_client.instance(instance_id)
    admin_table = admin_instance.table(table_id)

    print("Creating column family cf1 with Max Version GC rule...")
    max_versions_rule = column_family.MaxVersionsGCRule(2)
    column_family_id = b"cf1"
    column_families = {column_family_id: max_versions_rule}
    if not admin_table.exists():
        admin_table.create(column_families=column_families)
    else:
        print("Table {} already exists.".format(table_id))

    try:
        wait_for_table(admin_table)
        print("Writing some greetings to the table.")
        greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
        mutations = []
        column = b"greeting"
        for i, value in enumerate(greetings):
            row_key = f"greeting{i}".encode()
            row_mutation = bigtable.data.RowMutationEntry(
                row_key, bigtable.data.SetCell(column_family_id, column, value)
            )
            mutations.append(row_mutation)
        await table.bulk_mutate_rows(mutations)

        row_filter = bigtable.data.row_filters.CellsColumnLimitFilter(1)

        print("Getting a single greeting by row key.")
        key = "greeting0".encode()

        row = await table.read_row(key, row_filter=row_filter)
        cell = row.cells[0]
        print(cell.value.decode("utf-8"))

        print("Scanning for all greetings:")
        query = bigtable.data.ReadRowsQuery(row_filter=row_filter)
        async for row in await table.read_rows_stream(query):
            cell = row.cells[0]
            print(cell.value.decode("utf-8"))
    finally:
        print("Deleting the {} table.".format(table_id))
        admin_table.delete()


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()
    asyncio.run(main(args.project_id, args.instance_id, args.table))

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱「Bigtable 用戶端程式庫」。

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。詳情請參閱「設定用戶端程式庫的驗證作業」。



"""Demonstrates how to connect to Cloud Bigtable and run some basic operations.

Prerequisites:

- Create a Cloud Bigtable instance.
  https://cloud.google.com/bigtable/docs/creating-instance
- Set your Google Application Default Credentials.
  https://developers.google.com/identity/protocols/application-default-credentials
"""

import argparse
from ..utils import wait_for_table

from datetime import datetime, timezone

from google.cloud import bigtable
from google.cloud.bigtable import column_family
from google.cloud.bigtable import row_filters


row_filters
column_family


def main(project_id, instance_id, table_id):
    client = bigtable.Client(project=project_id, admin=True)
    instance = client.instance(instance_id)

    print("Creating the {} table.".format(table_id))
    table = instance.table(table_id)

    print("Creating column family cf1 with Max Version GC rule...")
    max_versions_rule = bigtable.column_family.MaxVersionsGCRule(2)
    column_family_id = b"cf1"
    column_families = {column_family_id: max_versions_rule}
    if not table.exists():
        table.create(column_families=column_families)
    else:
        print("Table {} already exists.".format(table_id))

    try:
        wait_for_table(table)

        print("Writing some greetings to the table.")
        greetings = [b"Hello World!", b"Hello Cloud Bigtable!", b"Hello Python!"]
        rows = []
        column = b"greeting"
        for i, value in enumerate(greetings):
            row_key = f"greeting{i}".encode()
            row = table.direct_row(row_key)
            row.set_cell(
                column_family_id, column, value, timestamp=datetime.now(timezone.utc),
            )
            rows.append(row)
        table.mutate_rows(rows)

        row_filter = bigtable.row_filters.CellsColumnLimitFilter(1)

        print("Getting a single greeting by row key.")
        key = b"greeting0"

        row = table.read_row(key, row_filter)
        cell = row.cells[column_family_id.decode("utf-8")][column][0]
        print(cell.value.decode("utf-8"))

        print("Scanning for all greetings:")
        partial_rows = table.read_rows(filter_=row_filter)

        for row in partial_rows:
            column_family_id_str = column_family_id.decode("utf-8")
            cell = row.cells[column_family_id_str][column][0]
            print(cell.value.decode("utf-8"))

    finally:
        print("Deleting the {} table.".format(table_id))
        table.delete()


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)