【问题标题】:Combine VALUE keyword with other SELECT Elements in Document DB将 VALUE 关键字与 Document DB 中的其他 SELECT 元素结合使用
【发布时间】:2016-08-10 04:51:07
【问题描述】:

我正在尝试使用 VALUE 关键字结合其他特定字段来拼合 JSON 文档,但没有运气。

给定一个 Document DB 文档:

{
    "id": "Tenant-Test",
    "name": "Test",
    "timeZone": "Eastern Standard Time",
    "section1": {
        "section1Key1": "section 1 value 1",
        "section1Key2": "section 1 value 2",
        ...
    },
    "section2": {
        "section2Key1": "section 2 value 1"
    }
}

我想获取以下形状的数据子集:

{
    "id": "Tenant-Test",
    "name": "Test",
    "timeZone": "Eastern Standard Time",
    "section1Key1": "section 1 value 1",
    "section1Key2": "section 1 value 2"
}

理论上我可以查询这个

SELECT c.id, c.name, c.timeZone, VALUE c.section1 FROM c

这会在“VALUE”附近出现语法错误。如果我删除特定字段 c.id、c.name、c.timeZone,那么我可以展平 c.section1。

是否可以进行这种转换?

【问题讨论】:

    标签: sql azure azure-cosmosdb


    【解决方案1】:

    Aravind 的替代解决方案如下:

    SELECT c.id, c.name, c.timeZone, c.section1.section1Key1 AS section1Key1, c.section1.section1Key2 AS section1Key2 
    FROM c
    

    【讨论】:

    • 这行得通,但我的问题可能不清楚我不提前知道子部分的内容。
    • Aravind 是否删除了他的答案?为什么?
    【解决方案2】:

    您可以使用 UDF 执行此操作:

    function transform(o) { 
      output = {}
      output.id = o.id
      output.name = o.name
      output.timeZone = o.timeZone
      output.section1Key1 = o.section1.section1Key1
      output.section1Key2 = o.section1.section1Key2
      return output 
    }
    

    您可以将硬编码的部分投影替换为无论多宽或多深都会变平的循环。

    然后在这样的查询中使用 UDF:

    SELECT VALUE udf.transform(c) FROM collection c
    

    注意,上面示例中的关键字VALUE 会抑制添加到每个文档之前的 $1 前缀(如果您将其省略)。

    【讨论】:

    • 这适用于以下循环: for (var key in o.section1) { if (o.section1.hasOwnProperty(key)) { output[key] = o.section1[key]; } }
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-11
    • 1970-01-01
    • 2011-07-10
    相关资源
    最近更新 更多