8

I have been trying to figure out how to update an item in dynamoDB but have not had any success.

I know how to add and item and remove an item but not update.

Here Is my code:

dynamoDB.updateItem({
    "TableName": "mytable",
    "Key": {
        "thing_ID": {"S": "0000"}
    },
    "UpdateExpression": "SET",
    "ExpressionAttributeNames": {
        "SessionID": ""
    },
    "ExpressionAttributeValues": {
        "SessionID": {
            "S": "maybe this works",
        }
    }
})
mkobit
  • 43,979
  • 12
  • 156
  • 150
user1395152
  • 355
  • 2
  • 4
  • 13

3 Answers3

14

It looks like you are trying to update an item by using an Expression, and in this case, your UpdateExpression is incorrect. Both the ExpressionAttributeNames and ExpressionAttributeValues are used for placeholder substitution in your expression.

I think your code would look something like this, if you want to set an attribute for an item:

dynamoDB.updateItem({  
    "TableName" : "exampleTable",
    "Key" : {
        "hashAttributeName" : {
            "S" : "thing_ID"
        }
    },
    "UpdateExpression" : "SET #attrName =:attrValue",
    "ExpressionAttributeNames" : {
        "#attrName" : "SessionID"
    },
    "ExpressionAttributeValues" : {
        ":attrValue" : {
            "S" : "maybe this works"
        }
    }
});

This will update an item that looks like this:

{  
    "Item":{  
        "hashAttributeName":"thing_ID"
    }
}

To this:

{  
    "Item":{  
        "hashAttributeName" : "thing_ID",
        "SessionID" : "maybe this works"
    }
}
mkobit
  • 43,979
  • 12
  • 156
  • 150
  • How would I do this if I want to update multiple Arrtibutes? Can you please help? – Karthik Oct 15 '15 at 16:06
  • 1
    @Karthik Your `UpdateExpression` just has multiple attributes. Like `SET Brand = :b, Price = :p`. If you want to do multiple different actions (like `SET` and `REMOVE`) you can do that too. Look at [*Modifying Items and Attributes with Update Expressions*](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html), and ask a new question if you have trouble. – mkobit Oct 15 '15 at 16:18
  • What if I want to delete an attribute? Help please – void Oct 19 '15 at 09:53
  • @AswinJoseRoy That is what the [`REMOVE` action](http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Expressions.Modifying.html#Expressions.Modifying.UpdateExpressions.REMOVE) does. See the documentation I posted in my comment above and ask a new question if you have any problems. – mkobit Oct 19 '15 at 14:18
0

Here's an example using AWS SDK for JavaScript v2.1.33.

The complete example is here: https://github.com/mayosmith/HelloDynamoDB/blob/master/HelloDynamoDB.html

/*
-----------------------------------------------------------------
AWS configure
Note: this is a simple experiement for demonstration
purposes only. Replace the keys below with your own.
Do not include the secret key in an actual production
environment, because, then, it wont be secret anymore...
-----------------------------------------------------------------
*/
AWS.config.update({accessKeyId: 'AKIAJUPWRIYYQGDB6AFA', secretAccessKey: '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'});
// Configure the region
AWS.config.region = 'us-west-2';  //us-west-2 is Oregon
//create the ddb object
var ddb = new AWS.DynamoDB();
/*
-----------------------------------------------------------------
Update the Table
-----------------------------------------------------------------
*/
//update the table with this data
var params = {
  Key: {
    name: {S: 'John Mayo-Smith'},
    city: {S: 'New York'}
  },
  AttributeUpdates: {
    food: {
      Action: 'PUT',
      Value: {S: 'chocolate'}
    }
  },
  TableName: 'sampletable',
  ReturnValues: 'ALL_NEW'
};
//update the table
update();
/*
-----------------------------------------------------------------
Get Item from the Table
-----------------------------------------------------------------
*/
//attribute to read
var readparams = {

  Key: {
    name: {S: 'John Mayo-Smith'},
    city: {S: 'New York'}
  },
  AttributesToGet: ['food'],
  TableName: 'sampletable'
};
//get the item
read();
/*
-----------------------------------------------------------------
function update()
Description: Calls updateItem which is part of the AWS Javascript
SDK.
Returns: JSON object (the object is stringifyed so we can see 
what's going on in the javascript console)
-----------------------------------------------------------------
*/
function update(){
    ddb.updateItem(params, function(err, data) {
        if (err) { return console.log(err); }
        console.log("We updated the table with this: " + JSON.stringify(data));
    });
}
/*
-----------------------------------------------------------------
function read()
Description: Calls getItem which is part of the AWS Javascript
SDK.
Returns: JSON object (the object is stringifyed so we can see 
what's going on in the javascript console)
-----------------------------------------------------------------
*/
function read(){
    ddb.getItem(readparams, function(err, data) {
        if (err) { return console.log(err); }
        console.log(": " + data);       

    console.log("John's favorite food is: "+ JSON.stringify(data.Item.food.S)); // print the item data
});
}
John Mayo-Smith
  • 139
  • 1
  • 7
  • 2
    For those who get an error when they use AttributeUpdates. They should use the approach highlighted by mkobit since "AttributeUpdates" is a legacy parameter and would not work with the new params. However, It would be great if someone could suggest a simpler approach since building the ExpressionAtrribute and ExpressionValue objects is tedious when you would want to automate this – Kartik Sep 02 '15 at 02:12
  • @Kartik as far as I can tell there is no simpler approach. here's a snippet that automates building the required params though: https://gist.github.com/cmawhorter/1fe025393efc2545b2c7 – Cory Mawhorter Jan 01 '16 at 21:02
  • @CoryMawhorter Looks great! Actually I went ahead and wrote a wrapper around the DynamoDB library to make simple helper functions which make mundane DynamoDB Tasks easier, also made it promise based :D. The library is called Dynosaur(https://github.com/kartiklad/dynosaur), it doesnt have any documentation atm but the code has some basic comments in it – Kartik Mar 23 '16 at 04:16
  • for those still landing here, i've been using dynogels for some time now with pretty good success: https://github.com/clarkie/dynogels – Cory Mawhorter Jan 02 '18 at 16:12
  • If you link to your own content your are required to disclose. https://stackoverflow.com/help/promotion – Yunnosch May 16 '21 at 06:20
0

Below code is working for me, try once

 var item = {"endTime": "7pm", "imageName": "7abcd", "startTime": "7pm"};

dynamo.updateItem({
TableName:'tableName',
Key:{"primaryKey":"primaryKeyValue"},
AttributeUpdates: { images: { Action: "ADD", Value: item } }},function(err, data) {
    if (err)
        console.log(err);
    else
        console.log(data)
});
Jose G Varanam
  • 767
  • 8
  • 19