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
demandé il y a 2 ans3084 vues
2 réponses
1
Réponse acceptée

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
répondu il y a un an
profile picture
EXPERT
vérifié il y a 5 mois
  • 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
répondu il y a 2 ans
  • 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

Vous n'êtes pas connecté. Se connecter pour publier une réponse.

Une bonne réponse répond clairement à la question, contient des commentaires constructifs et encourage le développement professionnel de la personne qui pose la question.

Instructions pour répondre aux questions