dynobase-icon
Dynobase

Batch Query in DynamoDB Using Java (Guide w/ Code Examples)

Rafal Wilinski

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 } }

Login to the AWS Console less. Use Dynobase.

First 7 days are on us. No strings attached.

Product Features

Download
/
Changelog
/
Pricing
/
Member Portal
/
Privacy
/
EULA
/
Twitter
© 2024 Dynobase
+
Login to the AWS Console less.
Try Dynobase to accelerate your DynamoDB workflow. Start your 7-day free trial today.