Get Max Partition Key Value from DynamoDb Table

0

I have MenuItem table in DynamoDb which has a partition key "Id" and I want the maximum value of Id column before inserting new record. Please share the code for the same.

Atif
asked a year ago2273 views
2 Answers
0
Accepted Answer

You'd first need a Global Secondary Index with Id as the sort key value, and a static value as the partition key:

GSI_PKGSI_SKData
1ID_01Data
1ID_02Data
1ID_03Data
1ID_14Data

Then you would Query your index with ScanIndexForward=False (DESC order) with a Limit=1 (return biggest ID).

        var client = new AmazonDynamoDBClient();

        var request = new QueryRequest
        {
            TableName = "Table_Name",
            IndexName = "Index_Name",
            KeyConditionExpression = "#pk = :pk",
            ExpressionAttributeValues = new Dictionary<string, AttributeValue>
            {
                { ":pk", new AttributeValue { N = "1" } }
            },
            ExpressionAttributeNames = new Dictionary<string, string>
            {
                { "#pk", "GSI_PK" }
            },
            ProjectionExpression = "GSI_SK",
            Limit = 1
        };

        var response = await client.QueryAsync(request);

        Console.WriteLine(response);
profile pictureAWS
EXPERT
answered 10 months ago
  • This worked for me

-1

You could scan the whole table, looking for the max value, but I'm assuming you want to avoid that. The best option I can think of is to add a Global Secondary Index (GSI) to your table that has "Id" as a Sort (Range) key, and query that index, e.g.:

# Use the Query operation to retrieve the first item in the index in descending order
response = dynamodb.query(
    TableName=table_name,
    IndexName=index_name,
    Select='SPECIFIC_ATTRIBUTES',
    AttributesToGet=[partition_key_name],
    Limit=1,
    ScanIndexForward=False
)

# Extract the maximum partition key value from the response
max_partition_key_value = response['Items'][0][partition_key_name]

You may need a dummy Hash (Partition) key for the GSI, always set to the same value, if nothing else suits your use case.

EXPERT
answered a year ago
  • I have created a GSI as per the above suggestion but when I am executing above I get the below error

    var blogRequest = new QueryRequest { TableName = "MenuItem", IndexName = "CategoryId-Id-index", Select = "SPECIFIC_ATTRIBUTES", AttributesToGet = { "Id" }, ScanIndexForward = false, Limit = 1, };

            var result = client.QueryAsync(blogRequest).GetAwaiter().GetResult();
    

    Error:

    Amazon.DynamoDBv2.AmazonDynamoDBException: 'Either the KeyConditions or KeyConditionExpression parameter must be specified in the request.'

    I am using C# language

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions