Batch Get in DynamoDB Using Java (Guide w/ Code Examples)
![Rafal Wilinski](https://pbs.twimg.com/profile_images/1390706809548197895/SVCKpLNE_400x400.png)
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)); } }
Similar Code Examples
- Update Attribute in DynamoDB Using Java
- Batch Save Using DynamoDB Mapper
- Insert in DynamoDB Using Java
- Delete Multiple Items in DynamoDB Using Java
- Batch Put Item in DynamoDB Using Java
- Query Date Range in DynamoDB Using Java
- Delete Table in DynamoDB Using Java
- Remove with DynamoDB Mapper
- Update Item in DynamoDB Using Java
- Delete in DynamoDB Using Java
- Remove Attribute in DynamoDB Using Java
- Batch Read in DynamoDB Using Java
- Delete Record in DynamoDB Using Java
- Update Multiple Items in DynamoDB Using Java
- Get Multiple Items in DynamoDB Using Java
Tired of AWS Console? Try Dynobase.
First 7 days are. No credit card needed.
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase