Node.js 中的 DynamoDB BatchGetItem(AWS SDK v3)
BatchGetItem 在单次请求中按主键获取多达 100 个项目(上限 16 MB)。在 AWS SDK v3 中,你发送一个带有表 → 键 RequestItems 映射的 BatchGetItemCommand——而且你必须对 UnprocessedKeys 进行循环,因为一个批次在合规情况下也可能只返回你请求内容的一部分。
Code
import {BatchGetItemCommand, DynamoDBClient} from '@aws-sdk/client-dynamodb';
const client = new DynamoDBClient({region: 'us-east-1'});
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
let requestItems = {
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'}}
]
}
};
const items = [];
let attempt = 0;
do {
const response = await client.send(new BatchGetItemCommand({RequestItems: requestItems}));
items.push(...(response.Responses?.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.
requestItems = response.UnprocessedKeys;
if (requestItems && Object.keys(requestItems).length > 0) {
attempt += 1;
await sleep(Math.min(100 * 2 ** attempt, 5000));
}
} while (requestItems && Object.keys(requestItems).length > 0);
console.log(`Fetched ${items.length} items`);说明
RequestItems— 一个表名 →{ Keys: [...] }的映射;一次请求可以跨多张表。每个键都必须是完整主键(复合键则为分区键 + 排序键)。超过 100 个键,或同一个键出现两次,都会以ValidationException失败。Responses— 一个表名 → 找到的项目的映射。项目返回时没有特定顺序,不存在的键则根本不会出现——请根据键属性把结果与请求对应起来。UnprocessedKeys— 上面的重试循环不是可选的。如果响应超过 16 MB、吞吐量耗尽,或一次分区读取超过 1 MB,DynamoDB 会把剩余部分以RequestItems形式返回到这里,可以直接原样送回。AWS 强烈建议在两次重试之间使用指数退避——立即重试往往会再次撞上同样的限流。- 一致性 — 批量读取默认是最终一致性的;对每张表设置
ConsistentRead: true可进行强一致性读取。 - 每张表还可以传入
ProjectionExpression(配合ExpressionAttributeNames)只获取部分属性。 BatchGetItem可能在服务端并行检索项目——它节省的是往返次数,而非读取容量:DynamoDB 会把批次中的每个项目当作单独的GetItem计费。
可视化操作
不想手工拼装 DynamoDB-JSON 键映射?DynamoDB Expression Builder 会构建带类型的键/值映射并复制可运行代码,而项目大小计算器会显示一个批次距离 16 MB 上限还有多近。
想在 GUI 中跨表获取并检查项目——无需编写重试循环——请下载 DynoTable。
相关示例
- Python 中的 DynamoDB BatchGetItem — 用 boto3 完成同样的批量读取。
- 使用 AWS CLI 的 DynamoDB BatchGetItem — 在 shell 中完成同样的批量读取。
- Node.js 中的 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
- Error handling with DynamoDB — Amazon DynamoDB Developer Guide
- DynamoDB read and write operations (capacity unit consumption) — Amazon DynamoDB Developer Guide
Last verified 2026-07-13 against the official AWS documentation linked above.