dynobase-icon
Dynobase

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

Rafal Wilinski

Provided by Rafal Wilinski

The batchWriteItem method allows you to write multiple items in a single request. This can be more efficient than making separate requests to write each item individually. The code example below writes 3 items to tables "Table1" and "Table2".

The batchWriteItem method returns a BatchWriteItemResult object, which includes the UnprocessedItems attribute. This attribute is a map of tables and requests that failed to be completed due to a lack of sufficient provisioned throughput on the tables. The failed requests can be retried using this attribute.

import software.amazon.awssdk.services.dynamodb.DynamoDbClient; import software.amazon.awssdk.services.dynamodb.model.AttributeValue; import software.amazon.awssdk.services.dynamodb.model.batchWriteItemRequest; import software.amazon.awssdk.services.dynamodb.model.batchWriteItemResponse; import software.amazon.awssdk.services.dynamodb.model.writeRequest; import java.util.HashMap; import java.util.Map; DynamoDbClient ddb = DynamoDbClient.create(); Map<String, writeRequest> requestItems = new HashMap<>(); Map<String, attributeValue> item1 = new HashMap<>(); item1.put("id", attributeValue.builder().n("101").build()); item1.put("title", attributeValue.builder().s("Book 101 Title").build()); item1.put("info", attributeValue.builder().s("Book 101 Info").build()); requestItems.put("Table1", writeRequest.builder().putRequest(r->r.item(item1)).build()); Map<String, attributeValue> item2 = new HashMap<>(); item2.put("id", attributeValue.builder().n("102").build()); item2.put("title", attributeValue.builder().s("Book 102 Title").build()); item2.put("info", attributeValue.builder().s("Book 102 Info").build()); requestItems.put("Table1", writeRequest.builder().putRequest(r->r.item(item2)).build()); Map<String, attributeValue> item3 = new HashMap<>(); item3.put("id", attributeValue.builder().n("103").build()); item3.put("title", attributeValue.builder().s("Book 103 Title").build()); item3.put("info", attributeValue.builder().s("Book 103 Info").build()); requestItems.put("Table2", writeRequest.builder().putRequest(r->r.item(item3)).build()); batchWriteItemRequest batchWriteItemRequest = batchWriteItemRequest.builder() .requestItems(requestItems) .build(); batchWriteItemResponse result = ddb.batchWriteItem(batchWriteItemRequest);

Dynobase is a Professional GUI Client for DynamoDB

Start your 7-day free trial today

Product Features

Download
/
Changelog
/
Pricing
/
Member Portal
/
Privacy
/
EULA
/
Twitter
/
Affiliates & Influencers
© 2024 Dynobase
+
Still using AWS DynamoDB Console?
Try Dynobase to accelerate your DynamoDB workflow. Start your 7-day free trial today.