DocumentDB子查询

时间:2016-06-28 14:16:08

标签: azure-cosmosdb

我正在尝试从包含双嵌套数组的大型文档投影到数组的展平表示中,我仍然坚持如何继续。

我有类似的文件:

{
    "id": "1",
    "themeId": "e4d3549c-2785-4067-83d6-f396d2212776",
    "enabled": false,
    "archived": false,
    "componentGroups": [
      [
        {
          "componentType": "header",
          "enabled": true,
          "configurationVariables": {
            "text1": "AAA",
            "text2": "BBB"
          }
        }
      ],
      [
        {
          "componentType": "prompt",
          "enabled": true,
          "configurationVariables": {
            "text1": "AAA",
            "text2": "BBB"
          }
        },
        {
          "componentType": "proactive",
          "enabled": true,
          "configurationVariables": {
            "text1": "AAA",
            "text2": "BBB"
          }
        }
      ],
      [
        {
          "componentType": "product-feed",
          "enabled": true,
          "configurationVariables": {
            "text1": "AAA",
            "text2": "BBB"
          }
        }
      ]
    ]
  }

我正在尝试将其投影到以下结构:

{
    "id": "275973",
    "themeId": "e4d3549c-2785-4067-83d6-f396d2212776",
    "enabled": false,
    "archived": false,
    "components": [
        {
          "componentType": "header",
          "enabled": true
        },
        {
          "componentType": "prompt",
          "enabled": true,
        },
        {
          "componentType": "proactive",
          "enabled": true,
        },
        {
          "componentType": "product-feed",
          "enabled": true
        }
      ]
    ]
  }

我使用以下查询取得了一些成功:

SELECT T.id, 
    T.themeId, 
    T.enabled, 
    T.archived, 
    [ { type: C.componentType, enabled: C.enabled } ] AS components
FROM Panels T 
JOIN CG IN T.componentGroups
JOIN C IN CG
WHERE T.id IN ("275973")

但是,这会为每个组件类型返回单独的记录。我试图将它们全部折叠起来,以便所有组件都在包含文档的单个实例中。我希望能够做一些类似于嵌套SELECT的东西,我可以在其中加入外部文档,类似于:

SELECT T.id, 
T.themeId,
T.enabled, 
T.archived, 
[ 
    SELECT C.componentType, C.enabled
    FROM CG IN T.componentGroups
    JOIN C IN CG 
] AS components
FROM Panels T
WHERE T.id IN ("275973")

但这是无效的。我正在寻找有关子/嵌套选择和通过钻入嵌套数组返回数据的信息。

1 个答案:

答案 0 :(得分:0)

计划了对子查询的DocumentDB支持,但目前不支持。同时,UDF或将数据客户端拉为N条记录,然后重新格式化是今天这样做的最佳方式。对于其他感兴趣的人来说,这是一个用于在查询中返回结果的UDF,

function transform(doc) {
    var result = {};

    for (var prop in doc) {
        if (prop != "componentGroups") {
            result[prop] = doc[prop];
        } else {
            result["components"] = [];
            for(var cgidx in doc["componentGroups"]) {
                var componentGroup = doc["componentGroups"][cgidx];
                for (var cidx in componentGroup) {
                    var component = componentGroup[cidx];
                    result["components"].push({componentType: component.componentType, enabled: component.enabled });
                }
            }
        }
    }

    return result;
 }