Batch Query in DynamoDB Using Java (Guide w/ Code Examples)
![Rafal Wilinski](https://pbs.twimg.com/profile_images/1390706809548197895/SVCKpLNE_400x400.png)
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
- Update Multiple Items in DynamoDB Using Java
- Batch Get in DynamoDB Using Java
- Batch Delete Using DynamoDB Mapper
- Delete Record in DynamoDB Using Java
- Delete in DynamoDB Using Java
- Batch Write Using DynamoDB Mapper
- Batch Load Using DynamoDB Mapper
- Remove Item in DynamoDB Using Java
- Insert in DynamoDB Using Java
- Batch Read in DynamoDB Using Java
- Update Item in DynamoDB Using Java
- Delete All Using DynamoDB Mapper
- Delete by Hashkey Using DynamoDB Mapper
- Delete Table in DynamoDB Using Java
- Batch Write Item in DynamoDB Using Java
Tired of switching accounts and regions? Use Dynobase.
Start your 7-day free trial today
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase