What are the steps to get Maximum value of an attribute of type number in Dynamodb

DynamoDb is a fully managed proprietary AWS Service which provide No-SQL Database solution out of box which stores data in Key-Value pair format and offers features like replication, auto-scaling, automatic-backup, etc.

As DynamoDB is very cheap AWS service and offers 25 GB of free storage per month therefore it's widely used for small scale application as well as in serverless architecture.

DynamoDB stores data in a table format where we must have a primary key and most of the developers coming from relational database world will design a table with Id column with number type as Primary key of the table.

Now problem arises when we want to get the maximum of the Id column/attribute value of type number in a DynamoDB table to store next row of data because DynamoDB doesn't provide auto-increment feature for any attribute out of the box as provided by many relational databases like SQL Server, etc...

One of the workarounds is that we can use Scan operations in DynamoDB to fetch all the rows and get the maximum of the attribute value but it's very costly operation and Scan operation is not recommended for any Production application.

As part of the industry best practices, it's recommended to use Query method in DynamoDB to fetch the data but here also we don't have any API method provided by DynamoDB to fetch the maximum of an attribute value of number type, so I am going to demonstrate a way to get the maximum of any attribute value of number type in DynamoDB. 

We know DynamoDB supports the creation of Global Secondary Index which helps us to retrieve data faster from the table so we will be using the same in our approach to find the maximum value of an attribute of type number from DynamoDB table.

Please find the procedure below to get the max value of an attribute of type number in DynamoDB table.


Step 1: Create attribute with name such as "StaticNumber" (you can give any name of your choice here) which will store the same number value for all the rows of your DynamoDB table.


static_number_dynamodb_1.png

As we can see in above table, we have a StaticNumber attribute which stores value 1 for all rows in the table.

Step 2: Next, we have to create a Global Secondary Index in the table keeping StaticNumber as Partition Key and Id as Sort Key as shown in the below screenshot.


global_secondary_index.PNG


Step 3: Now we can query the DynamoDB as below to get the maximum of Id value as per the below code written in C# programming language which you can convert to other programming languages using many AI tool.

private async Task<int> GetMaxBlogIdentifier()
{
AmazonDynamoDBClient client = new AmazonDynamoDBClient();


var menuRequest = new QueryRequest
{
TableName = MenutableName,
IndexName = "StaticNumber-Id-index", // Giving the name of Global Secondary Index
KeyConditionExpression = "StaticNumber = :staticnum",
ExpressionAttributeValues = new Dictionary<string, AttributeValue>
{
{ ":staticnum", new AttributeValue { N = "1" } } // Value of the Partition Key of the GSI
},
Limit = 1, // Limiting the result to 1 to get the one row only
ProjectionExpression = "Id", // Limiting our Select clause to only Id column/attribute
ScanIndexForward = false, // Scanning the result in descending order so that we get max id row in first row
};


var menuResponse = await client.QueryAsync(menuRequest).ConfigureAwait(false);
var maxIdVal = Convert.ToInt32(menuResponse.Items.SingleOrDefault().SingleOrDefault().Value.N);
return (maxIdVal + 1);
}




To explain the above code, we are querying the DynamoDb table based on the index named "StaticNumber-Id-index"  and giving the value of StaticNumber as 1 and limit our result to 1 to get only one row.
Also, giving ScanIndexForward property as false to get the data in descending order and ProjectionExpression to Id to get only the value of single attribute.


I have converted above C# code to javascript using ChatGpt which we can use in AWS Lambda function 



const AWS = require('aws-sdk');


async function getMaxBlogIdentifier() {
  const dynamoDB = new AWS.DynamoDB.DocumentClient();


  const menuParams = {
    TableName: 'YourMenutableName',
    IndexName: 'StaticNumber-Id-index',
    KeyConditionExpression: 'StaticNumber = :staticnum',
    ExpressionAttributeValues: {
      ':staticnum': 1,
    },
    Limit: 1,
    ProjectionExpression: 'Id',
    ScanIndexForward: false,
  };


  try {
    const menuResponse = await dynamoDB.query(menuParams).promise();
    const maxIdVal = parseInt(menuResponse.Items[0].Id);
    return maxIdVal + 1;
  } catch (error) {
    console.error('Error getting max blog identifier:', error);
    throw error;
  }
}


// Example usage
getMaxBlogIdentifier().then((result) => {
  console.log('Max Blog Identifier:', result);
}).catch((error) => {
  console.error('Error:', error);
});




Hope this article helps you to get the maximum identifier value from DynamoDB database.
For any feedback on this article, you can add the relevant comment.

Share This Post

Linkedin
Fb Share
Twitter Share
Reddit Share

Support Me

Buy Me A Coffee