Reputation: 2516
I have the following entity:
class Terms {
//hash key
private String code;
private String region;
private String market;
private String brand;
private String productType
}
Which is persisted to Dynamo DB table. I need to implement a constraint that would restrict a possibility to create Terms with the same region, market, brand and productType
so that this combination of fields is unique. I'm new to DynamoDB and the first thing that comes to my mind is implementing this restriction on a application level e.g. implementing a service layer function that checks if Term
with given combination of field values region = X, market = Y, brand = U, productType = Z
already exists and in case if it exists throw an exception.
However, I wonder if there is a way to implement this restriction on a DynamoDB layer - is there a way to make this combination of fields unique on a table definition level?
Any help is appreciated,
Thanks,
Cheers
Upvotes: 2
Views: 721
Reputation: 21
DynamoDB guarantee only uniqueness of primary key. I had write an article how to implement unique indexes by yourself. Hope it will help you
In short you need to create 2 records for each user. One would include the term value and the second one unique index value. Also it would be required to check conditional expression each time when you insert new or update the record.
Here the example of a single terms records
{
pk: 'some-user-id',
record_type: 'record', // you need it to find record with you user props
region: 'some-region',
brand: 'some-brand',
market: 'some-market',
}
{
pk: 'unique-index#some-region#some-brand#some-market',
record_type: 'unique-index'
}
Each time when you would insert new terms to db, you would need to insert both records using DynamoDB write transaction and check that there is no any other record with the same pk
.
Upvotes: 0
Reputation: 14799
This kind of feature isn't supported in DynamoDB. Further more, implementing such a feature will not be scalable in DynamoDB.
If you need to validate a new (or updated) item against all other items in the table, you will need to perform a Scan of the entire table every time you save an item. This means your performance and costs will scale non-linearly with your table size.
There is one option you might consider. Each item in DynamoDB must have a unique primary key. A primary key must have a partition key and can optionally have a sort key. If you created a composite key using your fields, and incorporated them into some combination of partition and sort key, that would effectively enforce uniqueness. For example, if you partition key was code, and your sort key was region+market+brand+producttype
. You would also need some kind of versioning to prevent new requests unexpectedly overwriting existing items.
Upvotes: 1