apero
apero

Reputation: 1154

Azure Cosmos db Unique Key on collection

I am trying to create an unique key for an whole collection in Cosmos DB. So not unique per _pk.

I read this article but here it only writes about Unique key per partition: https://learn.microsoft.com/en-us/azure/cosmos-db/unique-keys.

I Googled a lot but I can't find any result about a uk on collection. Is this even possible? And if it is, is there any documentation about it?

Upvotes: 4

Views: 7277

Answers (1)

Jay Gong
Jay Gong

Reputation: 23782

I think the official doc about cosmos db unique key is clearly stated.

I am trying to create an unique key for an whole collection in Cosmos DB.

Unique keys must be defined when the container is created, and the unique key is scoped to the partition key.

In the same collection there must be possible to store different objects without an username.

Sparse unique keys are not supported. If values for some unique paths are missing, they are treated as a special null value, which takes part in the uniqueness constraint.

If you do want to make the username field unique in the whole collection across the partitions and even null value is permitted, I think you need to check the uniqueness by yourself before inserting documents into cosmos db.I suggest you using pre-triggers to do the check.

Hope it helps you.

Upvotes: 5

Related Questions