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

心已入冬 提交于 2021-01-28 08:25:45

问题


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!


回答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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!