如何在 CosmosDB 中为具有 nested/multiple 数组的 JSON 文档编写 SQL 查询

How to write a SQL query in CosmosDB for a JSON document which has nested/multiple array

我需要在 CosmosDB 查询编辑器中编写一个 SQL 查询,它将根据我的要求从 JSON 集合中存储的文档中获取结果

例子JSON

{
  "id": "abcdabcd-1234-1234-1234-abcdabcdabcd",
  "source": "Example",
  "data": [
    {
      "Laptop": {
        "New": "yes",
        "Used": "no",
        "backlight": "yes",
        "warranty": "yes"
      }
    },
    {
      "Mobile": [
        {
          "order": 1,
          "quantity": 2,
          "price": 350,
          "color": "Black",
          "date": "07202019"
        },
        {
          "order": 2,
          "quantity": 1,
          "price": 600,
          "color": "White",
          "date": "07202019"
        }
      ]
    },
    {
      "Accessories": [
        {
          "covers": "yes",
          "cables": "few"
        }
      ]
    }
  ]
}

要求: SELECT 'warranty'(笔记本电脑),'quantity'(移动设备),'color'(移动设备),'cables'(配件)特定 'date'(对于例如:07202019)

我试过以下查询

SELECT
c.data[0].Laptop.warranty,
c.data[1].Mobile[0].quantity,
c.data[1].Mobile[0].color,
c.data[2].Accessories[0].cables
FROM c
WHERE ARRAY_CONTAINS(c.data[1].Mobile, {date : '07202019'}, true)

上述查询的原始输出:

[
    {
        "warranty": "yes",
        "quantity": 2,
        "color": "Black",
        "cables": "few"
    }
]

但是我怎样才能得到这个预期输出,它在数组 'Mobile':

中包含所有订单详细信息
[
    {
        "warranty": "yes",
        "quantity": 2,
        "color": "Black",
        "cables": "few"
    },
    {
        "warranty": "yes",
        "quantity": 1,
        "color": "White",
        "cables": "few"
    }
]

因为我写了 c.data[1].Mobile[0].quantity 即 'Mobile[0]' 是硬编码的,所以输出中只返回一个条目(即第一个),但我想列出数组中的所有条目

请考虑在 sql:

中使用 JOIN 运算符
SELECT DISTINCT
c.data[0].Laptop.warranty,
mobile.quantity,
mobile.color,
c.data[2].Accessories[0].cables
FROM c
JOIN data in c.data
JOIN mobile in data.Mobile
WHERE ARRAY_CONTAINS(data.Mobile, {date : '07202019'}, true)

输出:


更新答案:

你的sql:

SELECT DISTINCT c.data[0].Laptop.warranty, mobile.quantity, mobile.color, accessories.cables FROM c 
JOIN data in c.data JOIN mobile in data.Mobile 
JOIN accessories in data.Accessories 
WHERE ARRAY_CONTAINS(data.Mobile, {date : '07202019'}, true)

我的建议:

不得不说,实际上,Cosmos DB JOIN 操作仅限于单个文档的范围。您可以在同一文档下将父对象与子对象连接起来。跨文档联接不是 supported.However,您的 sql 尝试实现多个并行 join.In 换句话说,Accessories 和 Mobile 是分层的,而不是嵌套的。

我建议你使用存储过程来执行两个 sql,而不是将它们放在一起。或者你可以在代码中实现上面的过程。

请看这个案例: