Batch Get in DynamoDB Using Java (Guide w/ Code Examples)
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
- Query Global Secondary Index in DynamoDB Using Java
- Get in DynamoDB Using Java
- Query Index in DynamoDB Using Java
- Batch Write Using DynamoDB Mapper
- GetItem in DynamoDB Using Java
- Delete Expression in DynamoDB Using Java
- Remove Attribute in DynamoDB Using Java
- Delete Multiple Items in DynamoDB Using Java
- Query Local Secondary Index in DynamoDB Using Java
- Conditional Update in DynamoDB Using Java
- Get All Items from DynamoDB Using Java
- Batch Update Using DynamoDB Mapper
- Update Multiple Attributes in DynamoDB Using Java
- Delete Table in DynamoDB Using Java
- Delete All Items in DynamoDB Using Java
Login to the AWS Console less. Use Dynobase.
First 7 days are. No credit card needed.
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase