全部產品
Search
文件中心

Tablestore:批量讀取資料

更新時間:Aug 05, 2026

使用 Python SDK 在單次請求中按主鍵批量讀取一張或多張資料表的資料。

前提條件

安裝Tablestore Python SDK並初始化用戶端。

功能說明

調用 batch_get_row 方法批量讀取資料。每一行的讀取結果獨立返回。

def batch_get_row(self, request)

以下樣本讀取 example_table 中的兩行資料,僅返回每個屬性列的最新版本。

primary_keys = [
    [("partition", "device"), ("id", 1)],
    [("partition", "device"), ("id", 2)],
]
table_item = TableInBatchGetRowItem(
    "example_table",
    primary_keys,
    max_version=1,
)
request = BatchGetRowRequest()
request.add(table_item)

response = client.batch_get_row(request)
for item in response.get_succeed_rows():
    if item.row is not None:
        print(item.row.primary_key, item.row.attribute_columns)
說明

單次批量讀取最多支援 100 行資料。

參數說明

batch_get_row 方法包含以下參數。

名稱

類型

說明

request(必選)

BatchGetRowRequest

批量讀取請求。調用 add 方法為每張表添加一個 TableInBatchGetRowItem。請求內部以表名為鍵儲存配置,多次添加同一表會覆蓋該表之前的配置。

資料表讀取配置

request.items[] 的類型為 TableInBatchGetRowItem,包含以下參數。同一配置中的所有行共用屬性列、資料版本和過濾條件。

名稱

類型

說明

table_name(必選)

str

資料表名稱。

primary_keys(必選)

List[List[Tuple]]

要讀取的主鍵列表。每個主鍵必須包含全部主鍵列,且主鍵結構與資料表一致。

columns_to_get(可選)

List[str]

要返回的主鍵列或屬性列名稱。不設定時返回整行。

column_filter(可選)

ColumnCondition

過濾條件。有關配置方法,請參見過濾器

max_version(可選)

int

每個屬性列最多返回的版本數。max_versiontime_range 必須設定其中一個。如果合格版本數超過該值,按從新到舊的順序返回。

time_range(可選)

Tuple[int, int]

資料版本範圍,單位為毫秒,左閉右開。與 max_version 二選一。

start_column(可選)

str

寬行讀取的起始屬性列名稱。

end_column(可選)

str

寬行讀取的結束屬性列名稱。

token(可選)

bytes

寬行分頁讀取的起始位置。

傳回值

batch_get_row 返回 BatchGetRowResponse,可通過以下方法擷取結果。

方法

傳回型別

說明

is_all_succeed()

bool

所有行是否讀取成功。

get_succeed_rows()

List[RowDataItem]

讀取成功的行。每項包含表名、行資料和消耗的 CU;目標行不存在時,rowNone

get_failed_rows()

List[RowDataItem]

讀取失敗的行。每項包含表名、錯誤碼和錯誤資訊。

get_result_by_table(table_name)

List[RowDataItem]

指定資料表的逐行結果。

情境樣本

跨表批量讀取

以下樣本在同一請求中讀取兩張資料表。每張表通過一個 TableInBatchGetRowItem 配置讀取條件。

request = BatchGetRowRequest()
request.add(
    TableInBatchGetRowItem(
        "example_table",
        [[("partition", "device"), ("id", 1)]],
        max_version=1,
    )
)
request.add(
    TableInBatchGetRowItem(
        "another_table",
        [[("partition", "order"), ("id", 1)]],
        max_version=1,
    )
)

response = client.batch_get_row(request)

條件過濾讀取

以下樣本只返回 status 屬性列的最新值為 online 的行。同一表中的所有主鍵共用該過濾條件。

column_filter = SingleColumnCondition(
    "status",
    "online",
    ComparatorType.EQUAL,
    pass_if_missing=False,
)
table_item = TableInBatchGetRowItem(
    "example_table",
    primary_keys,
    column_filter=column_filter,
    max_version=1,
)
request = BatchGetRowRequest()
request.add(table_item)

response = client.batch_get_row(request)