Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent a DynamoDB item being overwritten if an entry already exists

Im trying to write a lambda function to add new data to a DynamoDB Table. From reading the docs at:

http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#put-property The PUT method: "Creates a new item, or replaces an old item with a new item by delegating to AWS.DynamoDB.putItem()."

Other than doing a check for an object before 'putting' is there a setting or flag to fail the object exists when the PUT is attempted?

I can see in

params -> Expected -> Exists (Bool) 

but can't see any documentation on what this does.

What would be the best architecture (or fasted) to prevent an item overwrite?

Query the table first and if no item exists then add the item 

or

Attempt to insert the item and on failure because of duplicate entry report this back? (Is there a way to prevent item overwrite?) 
like image 317
Mathew Jenkinson Avatar asked Oct 02 '17 18:10

Mathew Jenkinson


People also ask

What DynamoDB feature would prevent the most number of overwrite?

What DynamoDB feature would prevent the most number of overwrite bug reports? Include a condition-expression in the UpdateItem command. A recent increase in the amount of users of an application hosted on an EC2 instance that you manage has caused the instances OS to run out of CPU resources and crash.

Does DynamoDB put item overwrite?

Conditional writes. By default, the DynamoDB write operations ( PutItem , UpdateItem , DeleteItem ) are unconditional: Each operation overwrites an existing item that has the specified primary key.

How do you enforce uniqueness in DynamoDB?

In DynamoDB, each record in a table is uniquely identified by the primary key for your table. You can use this primary key to ensure there is not an existing record with the same primary key. To do so, you would use a Condition Expression to prevent writing an item if an item with the same key already exists.

Does Amazon DynamoDB support conditional operations?

Yes, like all the other database management systems, DynamoDB also supports all the conditional operators, User can specify a condition that is satisfied for a put, update, or delete operation to work on an item.


1 Answers

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 } 
like image 154
notionquest Avatar answered Oct 11 '22 01:10

notionquest