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
질문됨 일 년 전2455회 조회
2개 답변
0
수락된 답변

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
전문가
답변함 일 년 전
  • 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.

전문가
답변함 일 년 전
  • 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

로그인하지 않았습니다. 로그인해야 답변을 게시할 수 있습니다.

좋은 답변은 질문에 명확하게 답하고 건설적인 피드백을 제공하며 질문자의 전문적인 성장을 장려합니다.

질문 답변하기에 대한 가이드라인

관련 콘텐츠