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)