Get a batch of DynamoDB items using an Amazon SDK - Amazon DynamoDB
Services or capabilities described in Amazon Web Services documentation might vary by Region. To see the differences applicable to the China Regions, see Getting Started with Amazon Web Services in China.

Get a batch of DynamoDB items using an Amazon SDK

The following code examples show how to get a batch of DynamoDB items.

Amazon SDK for .NET

To learn how to set up and run this example, see GitHub.

/// <summary> /// Gets information about an existing movie from the table. /// </summary> /// <param name="client">An initialized Amazon DynamoDB client object.</param> /// <param name="newMovie">A Movie object containing information about /// the movie to retrieve.</param> /// <param name="tableName">The name of the table containing the movie.</param> /// <returns>A Dictionary object containing information about the item /// retrieved.</returns> public static async Task<Dictionary<string, AttributeValue>> GetItemAsync(AmazonDynamoDBClient client, Movie newMovie, string tableName) { var key = new Dictionary<string, AttributeValue> { ["title"] = new AttributeValue { S = newMovie.Title }, ["year"] = new AttributeValue { N = newMovie.Year.ToString() }, }; var request = new GetItemRequest { Key = key, TableName = tableName, }; var response = await client.GetItemAsync(request); return response.Item; }
  • For API details, see BatchGetItem in Amazon SDK for .NET API Reference.

SDK for JavaScript V3

To learn how to set up and run this example, see GitHub.

Create the client.

// Create service client module using ES6 syntax. import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; // Set the AWS Region. const REGION = "REGION"; //e.g. "us-east-1" // Create an Amazon DynamoDB service client object. const ddbClient = new DynamoDBClient({ region: REGION }); export { ddbClient };

Get the items.

// Import required AWS SDK clients and commands for Node.js import { BatchGetItemCommand } from "@aws-sdk/client-dynamodb"; import { ddbClient } from "./libs/ddbClient.js"; // Set the parameters export const params = { RequestItems: { TABLE_NAME: { Keys: [ { KEY_NAME_1: { N: "KEY_VALUE" }, KEY_NAME_2: { N: "KEY_VALUE" }, KEY_NAME_3: { N: "KEY_VALUE" }, }, ], ProjectionExpression: "ATTRIBUTE_NAME", }, }, }; export const run = async () => { try { const data = await ddbClient.send(new BatchGetItemCommand(params)); console.log("Success, items retrieved", data); return data; } catch (err) { console.log("Error", err); } }; run();
SDK for JavaScript V2

To learn how to set up and run this example, see GitHub.

// Load the AWS SDK for Node.js var AWS = require('aws-sdk'); // Set the region AWS.config.update({region: 'REGION'}); // Create DynamoDB service object var ddb = new AWS.DynamoDB({apiVersion: '2012-08-10'}); var params = { RequestItems: { 'TABLE_NAME': { Keys: [ {'KEY_NAME': {N: 'KEY_VALUE_1'}}, {'KEY_NAME': {N: 'KEY_VALUE_2'}}, {'KEY_NAME': {N: 'KEY_VALUE_3'}} ], ProjectionExpression: 'KEY_NAME, ATTRIBUTE' } } }; ddb.batchGetItem(params, function(err, data) { if (err) { console.log("Error", err); } else { data.Responses.TABLE_NAME.forEach(function(element, index, array) { console.log(element); }); } });
SDK for Python (Boto3)

To learn how to set up and run this example, see GitHub.

import decimal import json import logging import os import pprint import time import boto3 from botocore.exceptions import ClientError logger = logging.getLogger(__name__) dynamodb = boto3.resource('dynamodb') MAX_GET_SIZE = 100 # Amazon DynamoDB rejects a get batch larger than 100 items. def do_batch_get(batch_keys): """ Gets a batch of items from Amazon DynamoDB. Batches can contain keys from more than one table. When Amazon DynamoDB cannot process all items in a batch, a set of unprocessed keys is returned. This function uses an exponential backoff algorithm to retry getting the unprocessed keys until all are retrieved or the specified number of tries is reached. :param batch_keys: The set of keys to retrieve. A batch can contain at most 100 keys. Otherwise, Amazon DynamoDB returns an error. :return: The dictionary of retrieved items grouped under their respective table names. """ tries = 0 max_tries = 5 sleepy_time = 1 # Start with 1 second of sleep, then exponentially increase. retrieved = {key: [] for key in batch_keys} while tries < max_tries: response = dynamodb.batch_get_item(RequestItems=batch_keys) # Collect any retrieved items and retry unprocessed keys. for key in response.get('Responses', []): retrieved[key] += response['Responses'][key] unprocessed = response['UnprocessedKeys'] if len(unprocessed) > 0: batch_keys = unprocessed unprocessed_count = sum( [len(batch_key['Keys']) for batch_key in batch_keys.values()]) "%s unprocessed keys returned. Sleep, then retry.", unprocessed_count) tries += 1 if tries < max_tries:"Sleeping for %s seconds.", sleepy_time) time.sleep(sleepy_time) sleepy_time = min(sleepy_time * 2, 32) else: break return retrieved
  • For API details, see BatchGetItem in Amazon SDK for Python (Boto3) API Reference.

For a complete list of Amazon SDK developer guides and code examples, see Using DynamoDB with an Amazon SDK. This topic also includes information about getting started and details about previous SDK versions.