Is there a way to enforce unique constraint on a property (field) other than the primary key in dynamodb

此生再无相见时 提交于 2019-11-27 20:23:50

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-mail
  • user_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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!