Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I define unique keys involving properties in embedded arrays in Azure Cosmos DB?

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:

  1. Is it possible to create unique keys that "traverse" into arrays of embedded objects?
  2. If so, what is the correct path syntax for that?
  3. 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 as null or undefined for both group, thereby preventing me from saving one of them?

Thankful for any insights to help clear this up!

like image 962
Daniel Rosenberg Avatar asked Sep 01 '25 04:09

Daniel Rosenberg


1 Answers

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.

like image 127
Mark Brown Avatar answered Sep 03 '25 09:09

Mark Brown