DynamoDB BatchGetItem in Node.js (AWS SDK v3)
BatchGetItem recupera fino a 100 Item per chiave primaria in una sola richiesta (max 16 MB). In AWS SDK v3 invii un BatchGetItemCommand con una mappa RequestItems tabella → chiavi — e devi iterare su UnprocessedKeys, perché un batch può legittimamente restituire solo una parte di ciò che hai richiesto.
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`);Spiegazione
RequestItems— una mappa nome tabella →{ Keys: [...] }; una singola richiesta può interessare più tabelle. Ogni chiave deve essere la chiave primaria completa (partizione + ordinamento per una chiave composita). Più di 100 chiavi, o la stessa chiave due volte, fallisce con unaValidationException.Responses— una mappa nome tabella → gli Item trovati. Gli Item tornano in nessun ordine particolare, e le chiavi che non esistono semplicemente non compaiono — abbina i risultati alle richieste tramite i loro attributi chiave.UnprocessedKeys— il ciclo di retry qui sopra non è opzionale. Se la risposta supera i 16 MB, la capacità si esaurisce, o la lettura di una partizione supera 1 MB, DynamoDB restituisce qui il resto in formaRequestItems, pronto da reinserire direttamente. AWS raccomanda vivamente un backoff esponenziale tra i tentativi — un retry immediato tende a incontrare di nuovo lo stesso throttle.- Coerenza — le letture batch sono a coerenza eventuale per impostazione predefinita; imposta
ConsistentRead: trueper tabella per letture a coerenza forte. - Per ogni tabella puoi anche passare
ProjectionExpression(conExpressionAttributeNames) per recuperare solo alcuni attributi. BatchGetItempuò recuperare gli Item in parallelo lato server — fa risparmiare round trip, non capacità di lettura: DynamoDB fattura ogni Item del batch come un singoloGetItem.
Fallo visivamente
Preferisci non assemblare a mano le mappe di chiavi in DynamoDB JSON? Il DynamoDB Expression Builder costruisce mappe tipizzate chiave/valore e copia codice eseguibile, e il calcolatore delle dimensioni degli Item mostra quanto un batch si avvicina al limite di 16 MB.
Per recuperare e ispezionare gli Item tra le tabelle in una GUI — senza cicli di retry da scrivere — scarica DynoTable.
Esempi correlati
- DynamoDB BatchGetItem in Python — la stessa lettura batch con boto3.
- DynamoDB BatchGetItem con la AWS CLI — la stessa lettura batch dalla shell.
- DynamoDB GetItem in Node.js — la lettura di un singolo Item che questo raggruppa in batch.
- Operazioni batch in DynamoDB — limiti, fallimenti parziali e quando conviene il batching.
- "Too many items requested for the BatchGetItem call" — più di 100 chiavi in una sola richiesta.
- "Provided list of item keys contains duplicates" — la stessa chiave due volte in un batch.
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
Ultima verifica 2026-07-13 rispetto alla documentazione ufficiale AWS collegata sopra.