Is there a way to enforce unique constraint on a property (field) other than the primary key in dynamodb
Unique ConstraintAmazon DynamodbUnique Constraint Problem Overview
In dynamodb, if you want to enforce uniqueness in a field other than the primary key (like were you have a users table and want unique email addresses for users while primary key is a userid which is a number) is there a way other thans scanning the table to see if the email is already in use?
Unique Constraint Solutions
Solution 1 - Unique Constraint
Short answer: No.
DynamoDB is a key:value store. It is very good at quickly retrieving/saving Items because it does a couple of compromise. This is a constraint you have to handle yourself.
Nonethess, depending on your actual model, it might be a good idea to use this field as you hash_key
or consider using a range_key
If this is not possible, I advise you to de-normalize your data. You currently have something like:
UserTable
hash_key
:user_id
e-mail
- ...
To ensure unicity, add a new table with this schema:
EmailUser
hash_key
: e-mailuser_id
To make sure an e-mail is unique, just issue a GetItem
to EmailUser
before.
This kind of de-normalization is quite common with No-SQL databases.
Solution 2 - Unique Constraint
There is no such way you can enforce uniqueness on other attribute but using python's boto3 library you can use client to do transact item and use some composite key and try to duplicate your entry and insert all of them in a single go using transact_write_items(). There is very nice documentation by aws on this: https://aws.amazon.com/fr/blogs/database/simulating-amazon-dynamodb-unique-constraints-using-transactions/
Solution 3 - Unique Constraint
I don't think below mentioned approach is discussed or not, so posting the relevant link to ensure unique email(or any other attribute). This will not require creating another table but to add additional items into User table in primary key column.
Alternative approach to ensure unique attributes in DynamoDB
Solution 4 - Unique Constraint
The DynamoDB per se does not support unique constraints, but you can somehow ensure uniqueness by using atomic counter
and incorporate this counter value into your data.
In my case I have to make sure both username
and userId
do not have duplicates. username
is my partition key so I won't have any problems using the attribute_not_exists(username)
to prevent overwrites;
For userId
I will first retrieve a new value from the atomic counter and then put it as my userId value. It may not be completely sequential but it can guarantee uniqueness in this sense.