In Azure Cosmos DB, there is support for unique keys. Each unique key is defined as a set of paths representing values in the stored documents. An example of such a path would be /contact/firstName
. It's not clear from the official docs (in fact it's not mentioned at all) how those paths apply down through embedded arrays within the document, or how unique key semantics apply when paths navigate into nested documents with a cardinality of more than one.
For example, let's say I have a document like this to store a user group and a set of member users:
{
"id": "ABCD1234",
"name": "Administrators",
"members":
[
{
"userId": 1,
"enabled": true
},
{
"userId": 2,
"enabled": true
}
]
}
I want the group name to be unique across the logical partition, so I add a unique key with path /groupName
.
I also want to ensure that the members are unique, i.e. that the same userId
value does not occur more than once within a given group. Naïvely, I might try creating a unique key with the paths /name
and /members/userId
. But that doesn't work, the unique key seems to have no effect.
I've tried a few different variations of this, but none of them had the effect I was expecting.
So my questions:
members
objects, and tried to save two different groups that both have zero members? Would those keys not then logically evaluate as null
or undefined
for both group, thereby preventing me from saving one of them?Thankful for any insights to help clear this up!
Unique keys do not traverse into arrays within documents which is why they are not documented as such.
For details on what a logical partition is please see our docs on partitions
If you want uniqueness like what you are describing then create as different documents within a logical partition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With