dynobase-icon
Dynobase

Batch Get in DynamoDB Using Java (Guide w/ Code Examples)

Rafal Wilinski

Provided by Rafal Wilinski

The following code example shows how to use the BatchGetItem method in DynamoDB to retrieve multiple items in a single request using the AWS SDK for Java, Please keep in mind that the BatchGetItem method can retrieve a maximum of 100 items per request. If the data you want to retrieve is more than that, you need to paginate through the results using the LastEvaluatedKey value from the previous request. It's also important to note that the BatchGetItem method can only retrieve items from a single table simultaneously.

import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.model.AttributeValue; import com.amazonaws.services.dynamodbv2.model.BatchGetItemRequest; import com.amazonaws.services.dynamodbv2.model.BatchGetItemResult; import com.amazonaws.services.dynamodbv2.model.KeysAndAttributes; import java.util.HashMap; import java.util.Map; public class BatchGetExample { public static void main(String[] args) { AmazonDynamoDB client = AmazonDynamoDBClientBuilder.defaultClient(); // Define the keys for the items you want to retrieve Map<String, AttributeValue> key1 = new HashMap<>(); key1.put("id", new AttributeValue().withS("itemId1")); Map<String, AttributeValue> key2 = new HashMap<>(); key2.put("id", new AttributeValue().withS("itemId2")); // Add the keys to the request Map<String, KeysAndAttributes> requestItems = new HashMap<>(); requestItems.put("MyTable", new KeysAndAttributes().withKeys(key1, key2)); // Create and execute the BatchGetItem request BatchGetItemRequest request = new BatchGetItemRequest().withRequestItems(requestItems); BatchGetItemResult result = client.batchGetItem(request); // Print the retrieved items result.getResponses().get("MyTable").forEach(item -> System.out.println(item)); } }

Login to the AWS Console less. Use Dynobase.

First 7 days are. No credit card needed.

Product Features

Download
/
Changelog
/
Pricing
/
Member Portal
/
Privacy
/
EULA
/
Twitter
/
Affiliates & Influencers
© 2024 Dynobase
+
Better DynamoDB Experience.
Try Dynobase to accelerate your DynamoDB workflow. Start your 7-day free trial today.