在 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

相關範例

References

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

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

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