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
- Batch Delete Using DynamoDB Mapper
- Batch Query in DynamoDB Using Java
- Batch Save Using DynamoDB Mapper
- Query Hash Key Only in DynamoDB Using Java
- Update Expression in DynamoDB Using Java
- Update Attribute in DynamoDB Using Java
- Insert in DynamoDB Using Java
- Delete Table in DynamoDB Using Java
- Delete Expression in DynamoDB Using Java
- Delete All Using DynamoDB Mapper
- Remove with DynamoDB Mapper
- Batch Put Item in DynamoDB Using Java
- Get Item Request in DynamoDB Using Java
- Delete in DynamoDB Using Java
- GetItem in DynamoDB Using Java
Login to the AWS Console less. Use Dynobase.
First 7 days are on us. No strings attached.
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase