在 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 無法表達 UpdateItemConditionExpression;對既有 key 的 put 會靜默取代該項目。需要全有或全無、或條件式寫入?請用 TransactWriteItems
  • 改走低階 clientclient.batch_write_item)?那麼 UnprocessedItems 就要由你排空 — 完全依照 Node.js 範例 以指數退避迴圈處理。

改用視覺化操作

在大量載入前檢查你的項目?項目大小計算機 會對照 400 KB 上限驗證每個項目,而 DynamoDB Expression Builder 會為後續的讀取與寫入複製可執行的 boto3 程式碼。

想在 GUI 中大量新增、編輯與刪除項目 — 內建 CSV/JSON 匯入 — 下載 DynoTable

相關範例

References

最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。

不必透過主控台就能操作 DynamoDB

DynoTable 是一款快速的 DynamoDB 桌面用戶端 — 瀏覽表格、執行 SQL 風格的查詢,並在本機編輯項目。