在 Node.js(AWS SDK v3)中使用 DynamoDB BatchGetItem
BatchGetItem 在單一請求中依 primary key 抓取多達 100 個項目(上限 16 MB)。在 AWS SDK v3 中,你送出一個 BatchGetItemCommand,帶有表格 → keys 的 RequestItems map — 而你必須對 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: [...] }的 map;一個請求可橫跨多個表格。每個 key 都必須是完整 primary key(composite key 需 partition + sort)。超過 100 個 key,或同一個 key 出現兩次,都會以ValidationException失敗。Responses— 表格名稱 → 找到的項目的 map。項目以沒有特定順序回傳,不存在的 key 就是不會出現 — 請以 key 屬性把結果對應回請求。UnprocessedKeys— 上方的重試迴圈並非選用。若回應超過 16 MB、吞吐量耗盡,或某個 partition 讀取超過 1 MB,DynamoDB 會把剩餘部分以RequestItems形式放在這裡回傳,可直接餵回。AWS 強烈建議在重試之間採用指數退避 — 立即重試往往會再度撞上同一個節流。- 一致性 — 批次讀取預設為最終一致;每個表格設定
ConsistentRead: true可取得強一致讀取。 - 每個表格也可傳入
ProjectionExpression(搭配ExpressionAttributeNames)只抓取部分屬性。 BatchGetItem可能在伺服器端平行擷取項目 — 它省下的是往返,而非讀取容量:DynamoDB 會把批次中每個項目當作獨立的GetItem計費。
改用視覺化操作
不想手動組裝 DynamoDB-JSON 的 key map?DynamoDB Expression Builder 會建立帶型別的 key/value map 並複製可執行的程式碼,而 項目大小計算機 會顯示一次批次距離 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 個 key。
- "Provided list of item keys contains duplicates" — 同一個 key 在一次批次中出現兩次。
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
最後驗證於 2026-07-13,對照上方連結的 AWS 官方文件。