3
votes

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://docs.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?

1
With unique key I mean a field like username that has to be unique, this field is not going to be the partitionkey. But in the same collection there must be possible to store different objects without an username. I hope this makes it clearapero

1 Answers

4
votes

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.