在 Python(boto3)中使用 DynamoDB BatchGetItem
batch_get_item 在單一請求中依 primary key 抓取多達 100 個項目(上限 16 MB)。使用 boto3 低階 client 時,你傳入表格 → keys 的 RequestItems map — 而你必須對 UnprocessedKeys 進行迴圈,因為一次批次合法地可能只回傳你所要求的一部分。
Code
import time
import boto3
client = boto3.client("dynamodb")
request_items = {
"Music": {
"Keys": [
{"Artist": {"S": "Arturo Sandoval"}, "SongTitle": {"S": "Cubano Chant"}},
{"Artist": {"S": "Arturo Sandoval"}, "SongTitle": {"S": "A Mis Abuelos"}},
{"Artist": {"S": "Ella Fitzgerald"}, "SongTitle": {"S": "Misty"}},
]
}
}
items = []
attempt = 0
while request_items:
response = client.batch_get_item(RequestItems=request_items)
items.extend(response["Responses"].get("Music", []))
# A partial result is NOT an error: throttling, a >16 MB response, or an
# internal failure returns the leftovers in UnprocessedKeys. Retry them
# with exponential backoff.
request_items = response["UnprocessedKeys"]
if request_items:
attempt += 1
time.sleep(min(0.1 * 2**attempt, 5))
print(f"Fetched {len(items)} items")說明
RequestItems— 表格名稱 →{"Keys": [...]}的 map;一個請求可橫跨多個表格。每個 key 都必須是完整 primary key(composite key 需 partition + sort),並以 DynamoDB JSON 表示({"S": ...}、{"N": ...})。超過 100 個 key,或同一個 key 出現兩次,都會引發ValidationException。Responses— 表格名稱 → 找到的項目的 map。項目以沒有特定順序回傳,不存在的 key 就是不會出現 — 請以 key 屬性把結果對應回請求。UnprocessedKeys— 上方的重試迴圈並非選用。若回應超過 16 MB、吞吐量耗盡,或某個 partition 讀取超過 1 MB,DynamoDB 會把剩餘部分以RequestItems形式放在這裡回傳,可直接餵回(空 map 表示完成 — 在 Python 中為 falsy,正好結束while)。AWS 強烈建議在重試之間採用指數退避。- 一致性 — 批次讀取預設為最終一致;每個表格設定
"ConsistentRead": True可取得強一致讀取。 - 每個表格也可傳入
ProjectionExpression(搭配ExpressionAttributeNames)只抓取部分屬性。 - 偏好原生的 Python 型別而非 DynamoDB JSON?resource API 提供
dynamodb.batch_get_item(...)並使用單純的值,但重試契約相同 — 無論哪種方式,UnprocessedKeys都要由你排空。
改用視覺化操作
不想手動組裝 DynamoDB-JSON 的 key map?DynamoDB Expression Builder 會建立帶型別的 key/value map 並複製可執行的程式碼,而 項目大小計算機 會顯示一次批次距離 16 MB 上限有多近。
想在 GUI 中跨表格抓取並檢視項目 — 不需自己寫重試迴圈 — 下載 DynoTable。
相關範例
- 在 Node.js 中使用 DynamoDB BatchGetItem — 以 AWS SDK v3 執行相同的批次讀取。
- 使用 AWS CLI 執行 DynamoDB BatchGetItem — 從 shell 執行相同的批次讀取。
- 在 Python 中使用 DynamoDB GetItem — 這個批次所批的單一項目讀取。
- DynamoDB 的批次操作 — 上限、部分失敗,以及何時批次划算。
- "Too many items requested for the BatchGetItem call" — 一個請求中超過 100 個 key。
- "Provided list of item keys contains duplicates" — 同一個 key 在一次批次中出現兩次。
References
- BatchGetItem — Amazon DynamoDB API Reference
- DynamoDB.Client.batch_get_item — Boto3 documentation
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。