在 Python(boto3 batch_writer)中執行 DynamoDB 批次寫入
在 Python 中大量寫入 DynamoDB 項目的慣用方式是 boto3 的 batch_writer() context manager:它會緩衝你的 put 與 delete,以多達 25 個為一批的 BatchWriteItem 呼叫送出,並自動重送 unprocessed items — 也就是其他語言都要手寫的那個重試迴圈。
Code
import boto3
dynamodb = boto3.resource("dynamodb")
table = dynamodb.Table("Music")
songs = [
{"Artist": "Arturo Sandoval", "SongTitle": "Cubano Chant", "AlbumTitle": "Danzon", "Year": 1994},
{"Artist": "Arturo Sandoval", "SongTitle": "A Mis Abuelos", "AlbumTitle": "Danzon", "Year": 1994},
{"Artist": "Arturo Sandoval", "SongTitle": "Groovin' High", "AlbumTitle": "Swingin'", "Year": 1996},
]
with table.batch_writer() as batch:
for song in songs:
batch.put_item(Item=song)
batch.delete_item(Key={"Artist": "Ella Fitzgerald", "SongTitle": "Misty"})
print(f"Wrote {len(songs)} songs")說明
batch_writer()— 根據 boto3 文件,這個 handle 會「automatically handle buffering and sending items in batches」,並且「will also automatically handle any unprocessed items and resend them as needed」。離開with區塊會沖出仍在緩衝中的內容。- 單純的 Python 值 — 這是 resource API:沒有 DynamoDB JSON,數字為
int/Decimal。每個put_item項目都必須包含表格的完整 primary key;delete_item只需 key。 - 重複的 key — 原始的
BatchWriteItem呼叫會拒絕對同一個 key 的兩次寫入。若你的來源資料可能重複 key,請以table.batch_writer(overwrite_by_pkeys=["Artist", "SongTitle"])建構 writer — 它會為緩衝去重,保留每個 key 的最後一次寫入。 - 底層適用相同的服務上限:每個請求 25 個寫入、每個項目 400 KB、每個請求 16 MB。
batch_writer處理分塊;它無法解除每個項目的上限。 - 不支援更新、不支援條件 —
BatchWriteItem無法表達UpdateItem或ConditionExpression;對既有 key 的 put 會靜默取代該項目。需要全有或全無、或條件式寫入?請用 TransactWriteItems。 - 改走低階 client(
client.batch_write_item)?那麼UnprocessedItems就要由你排空 — 完全依照 Node.js 範例 以指數退避迴圈處理。
改用視覺化操作
在大量載入前檢查你的項目?項目大小計算機 會對照 400 KB 上限驗證每個項目,而 DynamoDB Expression Builder 會為後續的讀取與寫入複製可執行的 boto3 程式碼。
想在 GUI 中大量新增、編輯與刪除項目 — 內建 CSV/JSON 匯入 — 下載 DynoTable。
相關範例
- 在 Node.js 中使用 DynamoDB BatchWriteItem — batch_writer 所隱藏的手動重試迴圈。
- 使用 AWS CLI 執行 DynamoDB BatchWriteItem — 從 shell 執行相同的批次寫入。
- 在 Python 中使用 DynamoDB PutItem — 這個批次所批的單一項目寫入。
- DynamoDB 的批次操作 — 上限、部分失敗,以及何時批次划算。
- "Too many items requested for the BatchWriteItem call" — 一次批次中超過 25 個 put/delete 請求。
- "Provided list of item keys contains duplicates" — 一次批次中有兩個請求觸及同一個 key。
References
- Amazon DynamoDB guide (batch_writer) — Boto3 documentation
- BatchWriteItem — Amazon DynamoDB API Reference
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。