Python 中的 DynamoDB 批量写入(boto3 batch_writer)
在 Python 中批量写入 DynamoDB 项目的地道方式是 boto3 的 batch_writer() 上下文管理器:它会缓冲你的 put 和 delete,以每次至多 25 个的 BatchWriteItem 调用发送,并自动重发未处理项目——也就是其他语言都要手写的那个重试循环。
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 文档,这个句柄"会自动处理缓冲并按批次发送项目",且"还会自动处理任何未处理项目并按需重发"。退出with块会刷新所有仍在缓冲中的内容。- 普通 Python 值 — 这是 resource API:无需 DynamoDB JSON,数字用
int/Decimal。每个put_item的项目都必须包含表的完整主键;delete_item只需键即可。 - 重复键 — 原始的
BatchWriteItem调用会拒绝对同一个键的两次写入。如果你的源数据可能出现重复键,可以把写入器构造为table.batch_writer(overwrite_by_pkeys=["Artist", "SongTitle"])——它会对缓冲区去重,为每个键保留最后一次写入。 - 底层同样受服务限制约束:每次请求 25 个写入、每项 400 KB、每次请求 16 MB。
batch_writer负责分块;它无法突破单项上限。 - 无更新、无条件 —
BatchWriteItem无法表达UpdateItem或ConditionExpression;对已存在键的 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" — 一个批次中两个请求触及同一个键。
References
- Amazon DynamoDB guide (batch_writer) — Boto3 documentation
- BatchWriteItem — Amazon DynamoDB API Reference
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
Last verified 2026-07-13 against the official AWS documentation linked above.