With the year
as a Primary Key and the item being:
let item = {
"year": 2021,
"title": "Title A"
}
I can go ahead and add it to the DynamoDB using put
method:
var AWS = require('aws-sdk');
AWS.config.update({region: "us-east-1"});
const docClient = new DynamoDB.DocumentClient();
var params = {
TableName: TABLE_NAME,
Item: item,
ConditionExpression: "year <> :year",
ExpressionAttributeValues: {":year": 2021}
};
let promise = docClient.put(params).promise();
promise.then(res => {
console.log("res:", res);
});
Please note, that I am using ConditionExpression
here to assure that the item with the same Primary Key year
2021 does not already exist in the table. If the item exists, I will be getting the error. Otherwise, the item will be added and the empty dictionary is returned.
Instead of using the put
method I could get the same functionality using the update
command, such as:
let params = {
TableName: TABLE_NAME,
Key: {"year": year},
UpdateExpression: "SET year=:year",
ExpressionAttributeValues: {":year": year},
ConditionExpression: "year <> :year"
};
let promise = docClient.update(params).promise();
promise.then(res => {
console.log("res:", res);
});
While both put
and update
commands here do the job well, I tend to like the update
command more as it allows me to specify "ALL_NEW" as an argument to ReturnValues
parameter (for the put
command the option "ALL_NEW" is not available).
Is there any performance drop in using the update
command versus the put
? Is there any reason why I should be using put
instead of update
?