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
質問済み 2年前3085ビュー
2回答
1
承認された回答

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
エキスパート
回答済み 1年前
profile picture
エキスパート
レビュー済み 5ヶ月前
  • 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.

エキスパート
回答済み 2年前
  • 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

ログインしていません。 ログイン 回答を投稿する。

優れた回答とは、質問に明確に答え、建設的なフィードバックを提供し、質問者の専門分野におけるスキルの向上を促すものです。

質問に答えるためのガイドライン

関連するコンテンツ