Batch Operations - DynamoDB CRUD Operations
Batch operations are used for performing multiple operations on multiple items in a single request in DynamoDB. This makes it possible to reduce the number of round-trips between an application and a DynamoDB table. The following are the CRUD operations that can be performed using batch operations:
Syntax
The syntax for batch operations is as follows:
{
"RequestItems": {
"TableName": [
{
"PutRequest": {
"Item": {
"attribute_name": { "data_type": value },
/* more attributes */
}
}
},
{
"DeleteRequest": {
"Key": {
"attribute_name": { "data_type": value },
/* more keys */
}
}
},
{
"UpdateRequest": {
"Key": {
"attribute_name": { "data_type": value },
/* more keys */
},
"UpdateExpression": "set attribute_name=:value",
"ExpressionAttributeValues": {
":value": { "data_type": value },
/* more values */
}
}
},
/* more put, delete, or update requests */
]
}
}
Example
The following example illustrates how to use batch operations to perform multiple CRUD operations:
{
"RequestItems": {
"Table": [
{
"PutRequest": {
"Item": {
"id": { "S": "1" },
"name": { "S": "John Doe" },
"age": { "N": "35" },
"gender": { "S": "Male" }
}
}
},
{
"UpdateRequest": {
"Key": {
"id": { "S": "2" }
},
"UpdateExpression": "set #n=:new_name",
"ExpressionAttributeNames": { "#n": "name" },
"ExpressionAttributeValues": { ":new_name": { "S": "Jane Doe" } }
}
},
{
"DeleteRequest": {
"Key": {
"id": { "S": "3" }
}
}
}
]
}
}
Output
The output of the above example is:
{
"UnprocessedItems": {}
}
Explanation
In the above example, we performed three operations on the Table
table. We inserted a new item, updated an item with id
equal to 2
, and deleted an item with id
equal to 3
. The UnprocessedItems
attribute is returned if there are any items that were not processed due to exceeded provisioned throughput for the table or a failure to satisfy the business logic of the request.
Use
Batch operations are useful when you want to perform multiple CRUD operations in a single request. This can reduce the number of round-trips between the application and the table and improve the performance and efficiency of the application.
Important Points
- Maximum of 25 items can be processed in a single batch request.
- You can perform both put and delete operations in a single batch.
- Batch operations do not support conditional expressions.
- Batch operations can span multiple tables in a single request.
- You can use the TransactWriteItems API for ACID-compliant transactions on multiple tables.
Summary
Batch operations are used to perform multiple CRUD operations on multiple items in a single request in DynamoDB. This reduces the number of round-trips between an application and a table, improving performance and efficiency. You can perform up to 25 items in a single batch request, combine both put and delete operations, and span multiple tables in a single request if necessary.