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
- Batch Delete Using DynamoDB Mapper
- Conditional Update in DynamoDB Using Java
- Get All Items from DynamoDB Using Java
- Delete Multiple Items in DynamoDB Using Java
- Batch Load Using DynamoDB Mapper
- Delete All Using DynamoDB Mapper
- Get Multiple Items in DynamoDB Using Java
- Delete Record in DynamoDB Using Java
- Batch Get in DynamoDB Using Java
- Batch Insert in DynamoDB Using Java
- Batch Put Item in DynamoDB Using Java
- Batch Update Using DynamoDB Mapper
- Delete in DynamoDB Using Java
- Update Multiple Attributes in DynamoDB Using Java
- Batch Read in DynamoDB Using Java
Tired of switching accounts and regions? Use Dynobase.
Try 7-day free trial. No credit card needed.
Product Features
DynamoDB Tools
DynamoDB Info
© 2024 Dynobase