Dynamodb : Updating Array of Maps using Index of map

Viewed 87

I am trying to update a singular value inside a map array for an object in Dynamodb, My code looks like this

var update_score = {
                    TableName: 'ABC',
                    Key:{
                        "SortKey": "ABC123",
                         "RangeKey": "abc_123_xyz"
                    },
                    UpdateExpression: "set #lp[0].#grd = :num",
                   
                    ExpressionAttributeNames :{
                        '#lp': 'scores',
                        '#grd':'score1'
                       
                    },
                    ExpressionAttributeValues:{
             
                    ':num': 35
                    },
                    ReturnValues:"UPDATED_NEW"
                };
            console.log("getting in params1", update_score);
            docClient.update(update_score, function(err, data) {
                if (err) {
                    console.error("Unable to update item. Error JSON:", JSON.stringify(err, null, 2));
                    callback(null,JSON.stringify(err, null, 2));
                } else {
                    console.log("UpdateItem succeeded:", JSON.stringify(data, null, 2));
                    callback(null,JSON.stringify(data, null, 2));
                }
            });

Is there a way of passing a variable in place of '0' in the UpdateExpression: "set #lp[0].#grd = :num",

Since I want to extend this logic to allow updating of values sent by frontend through a variable not just specific values such as [0]

I have tried

var update_score = {
                    TableName: 'ABC',
                    Key:{
                        "SortKey": "ABC123",
                         "RangeKey": "abc_123_xyz"
                    },
                    UpdateExpression: "set #lp[#index].#grd = :num",
                   
                    ExpressionAttributeNames :{
                        '#lp': 'scores',
                        '#grd':'score1',
                        '#index' : indexOf_score_to_be_updated
                       
                    },
                    ExpressionAttributeValues:{
             
                    ':num': 35
                    },
                    ReturnValues:"UPDATED_NEW"
                };

Thank you for your help !!

1 Answers

I think the answer is that you need to put an actual integer in the UpdateExpression itself. When I wrote the tests for Scylla Alternator, an open-source DynamoDB-compatible database, I noticed that unfortunately, you also cannot use an expressionattributevalue - set #lp[:index].#grd = :num doesn't work either.

Related