Python(boto3)中的 DynamoDB BatchGetItem
batch_get_item 在单次请求中按主键获取多达 100 个项目(上限 16 MB)。使用 boto3 的低级 client,你传入一个表 → 键的 RequestItems 映射——而且你必须对 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": [...]}的映射;一次请求可以跨多张表。每个键都必须是完整主键(复合键则为分区键 + 排序键),并采用 DynamoDB JSON({"S": ...}、{"N": ...})。超过 100 个键,或同一个键出现两次,都会引发ValidationException。Responses— 一个表名 → 找到的项目的映射。项目返回时没有特定顺序,不存在的键则根本不会出现——请根据键属性把结果与请求对应起来。UnprocessedKeys— 上面的重试循环不是可选的。如果响应超过 16 MB、吞吐量耗尽,或一次分区读取超过 1 MB,DynamoDB 会把剩余部分以RequestItems形式返回到这里,可以直接原样送回(空映射表示完成——在 Python 中为假值,这正是终止while循环的条件)。AWS 强烈建议在两次重试之间使用指数退避。- 一致性 — 批量读取默认是最终一致性的;对每张表设置
"ConsistentRead": True可进行强一致性读取。 - 每张表还可以传入
ProjectionExpression(配合ExpressionAttributeNames)只获取部分属性。 - 更想用原生 Python 类型而非 DynamoDB JSON?resource API 提供了接受普通值的
dynamodb.batch_get_item(...),但重试契约是一样的——无论哪种方式,UnprocessedKeys都得由你自己排空。
可视化操作
不想手工拼装 DynamoDB-JSON 键映射?DynamoDB Expression Builder 会构建带类型的键/值映射并复制可运行代码,而项目大小计算器会显示一个批次距离 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 个键。
- "Provided list of item keys contains duplicates" — 同一批次中同一个键出现两次。
References
- BatchGetItem — Amazon DynamoDB API Reference
- DynamoDB.Client.batch_get_item — Boto3 documentation
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
Last verified 2026-07-13 against the official AWS documentation linked above.