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

45,032

Solution 1

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

Solution 2

You can use 'withReturnValues(ReturnValue.ALL_OLD)' that will return a Map from PutItemResult.getAttributes of the values that were there before the insertion.

If PutItemResult.getAttributes returns null, it was a new entry.

Share:
45,032
coder
Author by

coder

I am a learner

Updated on September 07, 2020

Comments

  • coder
    coder almost 4 years

    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.

  • Cristian Sepulveda
    Cristian Sepulveda over 6 years
    I think the safest way when you want to create an item is to never use putItem and always use UpdateItem . in my case I use updateItem only with the keys to create an object, if it already exits it makes nothing.
  • Cristiano Coelho
    Cristiano Coelho about 6 years
    What happens with batch writes? Does the same apply or does it fail?