在DocumentDB查询中展开数组

时间:2016-08-02 02:04:50

标签: sql azure-cosmosdb

我的文件看起来像这样:

[
  {
    "id": "e1bb9b05-11f2-459e-37d3-9bf9fed56c96",
    "name": "bulbasaur",
    "type": [
      {
        "slot": 2,
        "type": {
          "url": "https://pokeapi.co/api/v2/type/4/",
          "name": "poison"
        }
      },
      {
        "slot": 1,
        "type": {
          "url": "https://pokeapi.co/api/v2/type/12/",
          "name": "grass"
        }
      }
    ]
  }
]

以下查询尽可能接近,但不完全是我希望的输出。

查询

SELECT
  c.id, c.name, t.type.name as type
FROM
  c
JOIN
  t IN c.types
WHERE
  c.name = "bulbasaur"

结果

[
  {
    "id": "e1bb9b05-11f2-459e-37d3-9bf9fed56c96",
    "name": "bulbasaur",
    "type": "poison"
  },
  {
    "id": "e1bb9b05-11f2-459e-37d3-9bf9fed56c96",
    "name": "bulbasaur",
    "type": "grass"
  }
]

希望

[
  {
    "id": "e1bb9b05-11f2-459e-37d3-9bf9fed56c96",
    "name": "bulbasaur",
    "types": ["poison", "grass"]
  }
]

这可以通过DocumentDB查询吗?

1 个答案:

答案 0 :(得分:1)

这需要使用DocumentDB UDFs,它可以使用自定义转换扩展查询功能。例如,注册:

  function unwindTypeArray(value) {
    var result = { id: value.id, name: value.name, types: []};
    for (var idx in value.type) {
      console.log(idx);
      var name = value.type[idx].type.name;
      result.types.push(name);
    }

    return result; 
}

然后在如下的查询中调用它:

SELECT udf.unwindTypeArray(c) FROM c WHERE c.name = "bulbasaur"