what will happen if we insert into dynamo DB with a duplicate hash key?

coder picture coder · Sep 17, 2012 · Viewed 35.1k times · Source

I am trying to insert into dynamo DB. When I call the putItem function what will happen if the hash key is already present in the DB? Does the PutItemResult object contain something which can tell us if a duplicate hash entry was attempted? I want to avoid running another query to check if there is an entry with the hash key I am using.

Answer

yadutaf picture yadutaf · Sep 17, 2012

If you insert an item on an existing primary key, it will be overwritten unless you use the "expected values". Here is the introduction of the official documentation:

http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_PutItem.html

Creates a new item, or replaces an old item with a new item (including all the attributes). If an item already exists in the specified table with the same primary key, the new item completely replaces the existing item. You can perform a conditional put (insert a new item if one with the specified primary key doesn't exist), or replace an existing item if it has certain attribute values.

Note

To ensure that a new item does not replace an existing item, use a conditional put operation with Exists set to false for the primary key attribute, or attributes.

Otherwise, you can also use UpdateItem to update fields of a pre-existing item: http://docs.amazonwebservices.com/amazondynamodb/latest/developerguide/API_UpdateItem.html