问题
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:
- Is it possible to create unique keys that "traverse" into arrays of embedded objects?
- If so, what is the correct path syntax for that?
- Given that unique keys mean "unique across the whole logical partition" as opposed to "unique across the document", what would happen if I actually did manage to define a unique key involving the properties on the embedded
members
objects, and tried to save two different groups that both have zero members? Would those keys not then logically evaluate asnull
orundefined
for both group, thereby preventing me from saving one of them?
Thankful for any insights to help clear this up!
回答1:
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.
来源:https://stackoverflow.com/questions/61312837/how-do-i-define-unique-keys-involving-properties-in-embedded-arrays-in-azure-cos