Increment Number Values In DynamoDB With The ADD Operator
Easily increment number counters in your DynamoDB tables with this method
Have you ever needed to increment a number value in DynamoDB but weren’t sure how to?
I’ve seen many users fetch the previous value of that counter just to be able to increment it.
This method, while it works, isn’t efficient. It is costing you an extra read each time you need to update the item’s value.
There is however a DynamoDB API method that will allow you to increment number counters without knowing what the previous value was.
Let’s take a look at this.
The ADD Operator
The ADD operator in DynamoDB allows you to update an item’s number value.
This is typically done in an update expression using the ADD operator in the UpdateExpression of your UpdateCommand.
Here’s a code example:
UpdateExpression: 'ADD #count :incr',
ExpressionAttributeNames: {
'#count': 'count',
},
ExpressionAttributeValues: {
':incr': 1,
},
The ADD operator is defined in the UpdateExpression.
The count variable is defined in the ExpressionAttributeNames.
Then the ExpressionAttributeValues defines the amount to increment by.
Simple and efficient.
Let’s now take a look at implementing this on some actual data.
Demo Implementation
Creating an item in DynamoDB
Let’s start by creating a DynamoDB table and adding a new item to it.
Create the table and add a new item.
Next, let’s setup a Lambda function to increment that item’s count value.
Updating the item in Lambda
Create a new function in Lambda as you see below.
(I’m using the Node JS runtime).
Make sure to add the proper permissions role to update the DynamoDB table.
Here’s a quick guide on doing this.
Now let’s write the code in the code editor section below.
Code:
import { DynamoDBClient } from '@aws-sdk/client-dynamodb'
import { UpdateCommand } from '@aws-sdk/lib-dynamodb'
const client = new DynamoDBClient({})
export const handler = async (event) => {
try {
const command = new UpdateCommand({
TableName: 'store',
Key: {
pk: "order#101",
sk: "info",
},
UpdateExpression: 'ADD #count :inc',
ExpressionAttributeNames: {
'#count': 'count',
},
ExpressionAttributeValues: {
':inc': 1,
},
ReturnValues: 'UPDATED_NEW',
})
const response = await client.send(command)
return {
statusCode: 200,
body: JSON.stringify({ updatedCount: response.Attributes.count }),
}
} catch (error) {
return {
statusCode: 500,
body: JSON.stringify({ message: error.message }),
}
}
}
The code will identify the item to be updated (using the correct pk and sk values). It will then use the UpdateCommand to increment the count number value.
That’s all you need!
Deploy the function and click on Test to invoke it directly from the console.
When you run the function, go back to the DynamoDB table and you will see the item’s count value has been incremented.
Summary
DynamoDB allows you to efficiently increment number values without reading the existing value by using the ADD operator in an Update expression.
We went through implementing this simple number counter feature using DynamoDB and a simple Node JS Lambda function.
👋 My name is Uriel Bitton and I’m committed to helping you master Serverless, Cloud Computing, and AWS.
🚀 If you want to learn how to build serverless, scalable, and resilient applications, you can also follow me on Linkedin for valuable daily posts.
Thanks for reading and see you in the next one!