DynamoDB key uniqueness in primary and global secondary index

I am working on creating a DynamoDB table to store comments related to a single object.

Comments are sent to the object at a specific time, I use the time posted as a range, so comments are sorted in descending order of time. I have a global secondary index userId of the user who posted the comment, this should allow me to get all the comments posted by this user.

My question is, will this key be unique? I am worried that since it is technically possible for two users to leave a comment on the same object at the same time, the comment hash and range key will be identical.

My hope is that since it should not be possible for the same user to post two comments on the same object, the global secondary index will make the key unique.

Comment table: Hash Key Range Key Global Secondary Index Hash --------------------------------------------------------------------------------------- | objectId | datePosted | userId | | (not unique) | (not unique if multiple users | (unique across objectId and | | | post for the same object @ same time) | datePosted) | --------------------------------------------------------------------------------------- 
+5
source share
1 answer

DynamoDB indices have nothing to do with uniqueness. Global and local indexes have the ability to have duplicate hash keys and range key pairs. Only the hash key and range key of the table itself are unique.

In your example, it would be possible for two different users to be able to comment on the object at the same moment and duplicate objectId, datePosted. There are several ways to handle this. You can use the PutItem request with the condition that the primary key is null, as indicated in the API reference . This will cause the second comment to fail, and you can report the error to the user or simply try again with the updated timestamp. Without a condition, the second comment will overwrite the first. In addition, you can make the table range key a composite datePosted value associated with userId. Thus, the range keys will always be unique, but will still be sorted by date. This is a common practice with DynamoDB.

+16
source

Source: https://habr.com/ru/post/1200534/


All Articles