Python hello world

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

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

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

設定驗證方法

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

  1. Install the Google Cloud CLI.

  2. If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.

  3. To initialize the gcloud CLI, run the following command:

    gcloud init
  4. If you're using a local shell, then create local authentication credentials for your user account:

    gcloud auth application-default login

    You don't need to do this if you're using Cloud Shell.

    If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.

詳情請參閱 Set up authentication for a local development environment

執行範例

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

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

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

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

安裝及匯入用戶端程式庫

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

google-cloud-bigtable==2.30.1
google-cloud-core==2.4.3

匯入模組。

Asyncio

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

同步

如要瞭解如何安裝及使用 Bigtable 的用戶端程式庫,請參閱這篇文章

如要向 Bigtable 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

import datetime

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

同步

如要瞭解如何安裝及使用 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 = "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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

print("Writing some greetings to the table.")
greetings = ["Hello World!", "Hello Cloud Bigtable!", "Hello Python!"]
mutations = []
column = "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.
    #
    # 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).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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

print("Writing some greetings to the table.")
greetings = ["Hello World!", "Hello Cloud Bigtable!", "Hello Python!"]
rows = []
column = "greeting".encode()
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).encode()
    row = table.direct_row(row_key)
    row.set_cell(
        column_family_id, column, value, timestamp=datetime.datetime.utcnow()
    )
    rows.append(row)
table.mutate_rows(rows)

建立篩選器

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

Asyncio

如要瞭解如何安裝及使用 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

row_filter = bigtable.row_filters.CellsColumnLimitFilter(1)

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

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

Asyncio

如要瞭解如何安裝及使用 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

掃描所有資料表列

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

Asyncio

如要瞭解如何安裝及使用 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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

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

刪除資料表

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

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

馬上開始全面整合吧!

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

Asyncio

如要瞭解如何安裝及使用 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 = "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 = ["Hello World!", "Hello Cloud Bigtable!", "Hello Python!"]
        mutations = []
        column = "greeting"
        for i, value in enumerate(greetings):
            row_key = "greeting{}".format(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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。



"""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

import datetime

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 = "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 = ["Hello World!", "Hello Cloud Bigtable!", "Hello Python!"]
        rows = []
        column = "greeting".encode()
        for i, value in enumerate(greetings):
            row_key = "greeting{}".format(i).encode()
            row = table.direct_row(row_key)
            row.set_cell(
                column_family_id, column, value, timestamp=datetime.datetime.utcnow()
            )
            rows.append(row)
        table.mutate_rows(rows)

        row_filter = bigtable.row_filters.CellsColumnLimitFilter(1)

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

        row = table.read_row(key, row_filter)
        cell = row.cells[column_family_id][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:
            cell = row.cells[column_family_id][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)