使用 Python SDK 在单次请求中对一张或多张数据表批量执行写入、更新和删除操作。
前提条件
安装Tablestore Python SDK并初始化客户端。
功能说明
调用 batch_write_row 方法批量操作数据。每一行的操作结果独立返回。
def batch_write_row(self, request)
以下示例在 example_table 中写入两行数据。
condition = Condition(RowExistenceExpectation.IGNORE)
row_items = [
PutRowItem(
Row([("partition", "device"), ("id", 1)], [("status", "online")]),
condition,
),
PutRowItem(
Row([("partition", "device"), ("id", 2)], [("status", "offline")]),
condition,
),
]
request = BatchWriteRowRequest()
request.add(TableInBatchWriteRowItem("example_table", row_items))
response = client.batch_write_row(request)
print(response.is_all_succeed())
单次批量数据操作最多支持 200 行,所有行的数据量总和不能超过 4 MB。如果服务端发现部分操作存在参数错误,将返回参数错误,整批操作均不执行。
参数说明
batch_write_row 方法包含以下参数。
|
名称 |
类型 |
说明 |
|
request(必选) |
|
批量数据操作请求。调用 |
数据表操作配置
request.items[] 的类型为 TableInBatchWriteRowItem,包含以下参数。
|
名称 |
类型 |
说明 |
|
table_name(必选) |
|
数据表名称。 |
|
row_items(必选) |
|
行操作列表。支持 |
行操作
row_items[] 包含以下公共参数。
|
名称 |
类型 |
说明 |
|
row(必选) |
|
行数据。 |
|
condition(必选) |
|
操作条件。有关配置方法,请参见条件更新。不需要判断行或列值时,设置为 |
|
return_type(可选) |
|
返回类型。 |
局部事务
调用 request.set_transaction_id(transaction_id) 可在批量请求中携带局部事务 ID。使用局部事务时,请求只能包含该事务对应数据表中的行,且所有行的分区键值必须与创建事务时一致。有关使用限制,请参见局部事务。
返回值
batch_write_row 返回 BatchWriteRowResponse,可通过以下方法获取结果。
|
方法 |
返回类型 |
说明 |
|
|
|
所有行操作是否成功。 |
|
|
|
写入操作的成功或失败结果。 |
|
|
|
更新操作的成功或失败结果。 |
|
|
|
删除操作的成功或失败结果。 |
|
|
|
指定数据表、指定操作类型的逐行结果。 |
每个 BatchWriteRowResponseItem 包含操作是否成功、错误码、错误信息、消耗的 CU 和主键信息。
场景示例
批量更新行数据
以下示例更新两行的 status 属性列。
condition = Condition(RowExistenceExpectation.EXPECT_EXIST)
row_items = [
UpdateRowItem(
Row([("partition", "device"), ("id", 1)], {"PUT": [("status", "online")]}),
condition,
),
UpdateRowItem(
Row([("partition", "device"), ("id", 2)], {"PUT": [("status", "online")]}),
condition,
),
]
request = BatchWriteRowRequest()
request.add(TableInBatchWriteRowItem("example_table", row_items))
response = client.batch_write_row(request)
批量删除行数据
以下示例删除两行数据。
condition = Condition(RowExistenceExpectation.EXPECT_EXIST)
row_items = [
DeleteRowItem(Row([("partition", "device"), ("id", 1)]), condition),
DeleteRowItem(Row([("partition", "device"), ("id", 2)]), condition),
]
request = BatchWriteRowRequest()
request.add(TableInBatchWriteRowItem("example_table", row_items))
response = client.batch_write_row(request)
跨表混合多种操作
以下示例在一个请求中向 example_table 写入一行,并更新 another_table 中的一行。
put_row = Row(
[("partition", "device"), ("id", 3)],
[("status", "online")],
)
update_row = Row(
[("partition", "order"), ("id", 1)],
{"PUT": [("status", "processed")]},
)
request = BatchWriteRowRequest()
request.add(
TableInBatchWriteRowItem(
"example_table",
[PutRowItem(put_row, Condition(RowExistenceExpectation.IGNORE))],
)
)
request.add(
TableInBatchWriteRowItem(
"another_table",
[UpdateRowItem(update_row, Condition(RowExistenceExpectation.EXPECT_EXIST))],
)
)
response = client.batch_write_row(request)