Batch Query in DynamoDB Using Java (Guide w/ Code Examples)
Provided by Rafal Wilinski
DynamoDB offers a batchGetItem
method that allows you to retrieve multiple items from one or more tables in a single request.
In the snippet shown below, the batchGetItem
method retrieves items from two tables: "Table1" and "Table2". All keys to that need to be retrieved are specified in the requestItems
map. This maps table names to lists of item keys.
import com.amazonaws.services.dynamodbv2.AmazonDynamoDB; import com.amazonaws.services.dynamodbv2.AmazonDynamoDBClientBuilder; import com.amazonaws.services.dynamodbv2.document.DynamoDB; import com.amazonaws.services.dynamodbv2.document.TableKeysAndAttributes; import com.amazonaws.services.dynamodbv2.model.BatchGetItemRequest; import com.amazonaws.services.dynamodbv2.model.BatchGetItemResult; import java.util.HashMap; import java.util.List; import java.util.Map; public class BatchGetExample { public static void main(String[] args) { // Create a new client AmazonDynamoDB client = AmazonDynamoDBClientBuilder.standard().build(); DynamoDB dynamoDB = new DynamoDB(client); // Create a map of table name to keys Map<String, List<Map<String, Object>>> requestItems = new HashMap<>(); requestItems.put("Table1", Arrays.asList(new HashMap<String, Object>() {{ put("id", "123"); }},new HashMap<String, Object>() {{ put("id", "456"); }})); requestItems.put("Table2", Arrays.asList(new HashMap<String, Object>() {{ put("id", "789"); }},new HashMap<String, Object>() {{ put("id", "555"); }})); TableKeysAndAttributes tka = new TableKeysAndAttributes("Table1"); tka.addHashAndRangePrimaryKey("id", "123", "id", "456"); tka.addHashAndRangePrimaryKey("id", "789", "id", "555"); BatchGetItemRequest request = new BatchGetItemRequest() .withRequestItems(requestItems) .withReturnConsumedCapacity(ReturnConsumedCapacity.TOTAL); BatchGetItemResult result = client.batchGetItem(request); // process the result } }
Similar Code Examples
- Delete All Using DynamoDB Mapper
- Batch Get in DynamoDB Using Java
- Batch Put Item in DynamoDB Using Java
- Remove with DynamoDB Mapper
- Delete in DynamoDB Using Java
- Query Global Secondary Index in DynamoDB Using Java
- Remove Attribute in DynamoDB Using Java
- Batch Delete Using DynamoDB Mapper
- Batch Write Using DynamoDB Mapper
- Update Expression in DynamoDB Using Java
- Conditional Update in DynamoDB Using Java
- Delete by Hashkey Using DynamoDB Mapper
- Batch Load Using DynamoDB Mapper
- Update Item in DynamoDB Using Java
- Query Local Secondary Index in DynamoDB Using Java
Spend less time in the AWS console, use Dynobase.
Try 7-day free trial. No credit card needed.
Product Features
DynamoDB Tools
DynamoDB Info
© 2025 Dynobase