使用 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)