使用 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(必选) |
|
批量读取请求。调用 |
数据表读取配置
request.items[] 的类型为 TableInBatchGetRowItem,包含以下参数。同一配置中的所有行共用属性列、数据版本和过滤条件。
|
名称 |
类型 |
说明 |
|
table_name(必选) |
|
数据表名称。 |
|
primary_keys(必选) |
|
要读取的主键列表。每个主键必须包含全部主键列,且主键结构与数据表一致。 |
|
columns_to_get(可选) |
|
要返回的主键列或属性列名称。不设置时返回整行。 |
|
column_filter(可选) |
|
过滤条件。有关配置方法,请参见过滤器。 |
|
max_version(可选) |
|
每个属性列最多返回的版本数。 |
|
time_range(可选) |
|
数据版本范围,单位为毫秒,左闭右开。与 |
|
start_column(可选) |
|
宽行读取的起始属性列名称。 |
|
end_column(可选) |
|
宽行读取的结束属性列名称。 |
|
token(可选) |
|
宽行分页读取的起始位置。 |
返回值
batch_get_row 返回 BatchGetRowResponse,可通过以下方法获取结果。
|
方法 |
返回类型 |
说明 |
|
|
|
所有行是否读取成功。 |
|
|
|
读取成功的行。每项包含表名、行数据和消耗的 CU;目标行不存在时, |
|
|
|
读取失败的行。每项包含表名、错误码和错误信息。 |
|
|
|
指定数据表的逐行结果。 |
场景示例
跨表批量读取
以下示例在同一请求中读取两张数据表。每张表通过一个 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)