0
0
DynamodbHow-ToBeginner · 4 min read

How to Batch Get Items in DynamoDB: Syntax and Example

To batch get items in DynamoDB, use the BatchGetItem API which allows you to retrieve multiple items from one or more tables in a single request. You specify the table name and a list of primary keys for the items you want, and DynamoDB returns the matching items efficiently.
📐

Syntax

The BatchGetItem operation requires a request object with the following parts:

  • RequestItems: A map where each key is a table name and the value is an object containing the list of keys to retrieve.
  • Keys: An array of primary key objects identifying the items to get.
  • ProjectionExpression (optional): Specifies which attributes to return.

The response contains the items found and any unprocessed keys to retry.

json
BatchGetItem({
  RequestItems: {
    'TableName': {
      Keys: [
        { 'PrimaryKeyAttribute': { S: 'KeyValue1' } },
        { 'PrimaryKeyAttribute': { S: 'KeyValue2' } }
      ],
      ProjectionExpression: 'Attribute1, Attribute2' // optional
    }
  }
})
💻

Example

This example shows how to batch get two items from a DynamoDB table named Products using AWS SDK for JavaScript v3.

javascript
import { DynamoDBClient, BatchGetItemCommand } from "@aws-sdk/client-dynamodb";

const client = new DynamoDBClient({ region: "us-east-1" });

async function batchGetItems() {
  const params = {
    RequestItems: {
      Products: {
        Keys: [
          { ProductId: { S: "123" } },
          { ProductId: { S: "456" } }
        ],
        ProjectionExpression: "ProductId, ProductName, Price"
      }
    }
  };

  try {
    const command = new BatchGetItemCommand(params);
    const response = await client.send(command);
    console.log("Retrieved items:", JSON.stringify(response.Responses.Products, null, 2));
  } catch (error) {
    console.error("Error fetching items:", error);
  }
}

batchGetItems();
Output
Retrieved items: [ { "ProductId": { "S": "123" }, "ProductName": { "S": "Coffee Mug" }, "Price": { "N": "12.99" } }, { "ProductId": { "S": "456" }, "ProductName": { "S": "Tea Kettle" }, "Price": { "N": "29.99" } } ]
⚠️

Common Pitfalls

  • Exceeding the 100 item limit: BatchGetItem can only retrieve up to 100 items per request. If you need more, split requests.
  • UnprocessedKeys: Sometimes DynamoDB returns unprocessed keys due to throttling; you must retry those keys.
  • Incorrect key format: Keys must exactly match the table's primary key schema, including data types.
  • Missing attributes: If you use ProjectionExpression, only those attributes are returned.
javascript
/* Wrong: Exceeding 100 keys in one request */
const paramsWrong = {
  RequestItems: {
    Products: {
      Keys: new Array(150).fill({ ProductId: { S: "123" } })
    }
  }
};

/* Right: Split into multiple requests of 100 or fewer keys */
const paramsRight = {
  RequestItems: {
    Products: {
      Keys: new Array(100).fill({ ProductId: { S: "123" } })
    }
  }
};
📊

Quick Reference

ConceptDetails
Max items per request100 items
Unprocessed keysRetry them to get all items
Keys formatMatch primary key schema exactly
ProjectionExpressionOptional, limits returned attributes
API nameBatchGetItem

Key Takeaways

Use BatchGetItem to retrieve multiple items efficiently in one request.
Limit each batch to 100 items and handle unprocessed keys by retrying.
Ensure keys match the table's primary key schema exactly in type and name.
Use ProjectionExpression to fetch only needed attributes and reduce data size.
Always check for and retry unprocessed keys to get complete results.