How to perform updateItem operation with JSON payload in Dynamo DB table

DB Dynamo document API allows operation using json payload

Item item = Item.fromJSON(payload);
table.putItem(item);

However, I could not find a similar way to execute updateItem with the Json payload.

Is there any DB Dynamo support for this?

+4
source share
3 answers

I struggled with this for a while, after all, you need to use a map.

UpdateItemOutcome updateItemOutcome = table.updateItem(
                new UpdateItemSpec()
                        .withPrimaryKey("id", "yourId")                            
                        .withUpdateExpression("SET document.field = :field")
                        .withValueMap(new ValueMap()
                                        .withMap(":field", "map of key value pairs that will get serialized to json")));
+1
source

Here is a snippet on how you will do this in Javascript.

let updateExpression = 'SET ';
let expressionAttributeValues = {};

const keys = Object.keys(payload);
for (const key of keys) {
  updateExpression += `${key}=:${key},`;
  expressionAttributeValues[`:${key}`] = payload[key];
}
updateExpression=updateExpression.slice(0,-1);

let params = {  
  TableName : 'your_table_name',
  Key: {
    id: id
  }, 
  UpdateExpression : updateExpression,
  ExpressionAttributeValues : expressionAttributeValues,
  ReturnValues: "ALL_NEW"
}

db.update(params,(err, result)=>{});
Run code
+1
source

UpdateItemSpec - json ( Item.fromJSON), AttributeUpdate, UpdateExpression, (SET, ADD ..)

Here is the documentation on using UpdateExpression to update an element http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/JavaDocumentAPIItemCRUD.html#JavaDocumentAPIItemUpdate

0
source

All Articles