简体   繁体   中英

DynamoDB - How to specify UNIQUE field that is not a PRIMARY key?

Most databases allow defining UNIQUE key (unique field) that is not a PRIMARY KEY, but DynamoDB does not seem to support unique key definitions.

For example, a model SampleModel defines an id field as a PRIMARY KEY ( id = UnicodeAttribute(hash_key=True) ). What if another field (let's say name ) must also be defined as unique? Given that DynamoDB does not offer unique field specification, and only one PK ( hash_key=True ) is allowed - how can name be defined as UNIQUE?

As you've already seen, there's no direct support for that in DynamoDB.

If this name attribute is immutable after you write it, you could do the following:

You can create a second DynamoDB table that only has a Partition Key (Partition Key = Primary Key) and stores each name there. When you add an item to the first table, you use a transaction and have a separate insert into the second table that has a condition of the key not already existing. If this transaction fails, you were trying to put an item whose name already existed in the table. If the transaction goes through, you've inserted a new unique name.

This will incur extra cost for the second table and transactions and only works in this narrow use case.

DynamoDB is not built for this pattern, enforce uniqueness in another way.

You create a PK out of whatever value has to be unique (in the same table or second table) and use transactions to enforce it on insert.

https://aws.amazon.com/blogs/database/simulating-amazon-dynamodb-unique-constraints-using-transactions/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM