The ConditionExpression
can be used to check whether the key attribute values already exists in table and perform the PUT operation only if the key values are not present in the table.
When you run the below code, first time the put operation should be successful. In the second run, the put operation should fail with "Conditional request failed" exception.
My movies table has both partition and sort keys. So, I have used both the attributes in conditional expression.
Sample code with conditional put:-
var table = "Movies";
var year = 1502;
var title = "The Big New Movie";
var params = {
TableName:table,
Item:{
"yearkey": year,
"title": title,
"info":{
"plot": "Nothing happens at all.",
"rating": 0
}
},
ConditionExpression: "yearkey <> :yearKeyVal AND #title <> :title",
ExpressionAttributeNames: {
"#title" : "title"
},
ExpressionAttributeValues: {
":yearKeyVal" : year,
":title": {"S": title}
}
};
console.log("Adding a new item...");
docClient.put(params, function(err, data) {
if (err) {
console.error("Unable to add item. Error JSON:", JSON.stringify(err, null, 2));
} else {
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
Exception when put operation is performed second time:-
Unable to add item. Error JSON: {
"message": "The conditional request failed",
"code": "ConditionalCheckFailedException",
"time": "2017-10-02T18:26:26.093Z",
"requestId": "7ae3b0c4-3872-478d-908c-94bc9492a43a",
"statusCode": 400,
"retryable": false,
"retryDelay": 0
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…