DocumentDB子文档投影

时间:2017-01-18 00:39:02

标签: azure azure-cosmosdb

我用这种文件创建了一个集合:

{       
    "Date": 1481673600,
    "Name": "Test"
    "DailyCurve": [
      {
        "TimeStamp": 1481673600,
        "ACPower": 0,        
        "DCPower": 0
      },
      {
        "TimeStamp": 1481716800,
        "ACPower": 30.599999999999998,
        "DCPower": 0
      },
      {
        "TimeStamp": 1481717700,
        "ACPower": 50.099999999999994,
        "DCPower": 0
      },
      {
        "TimeStamp": 1481718600,
        "ACPower": 46.6,
        "DCPower": 0
      },
    ]
}

因为我想查询大量数据,我想使用投影来减少所需的RU。

我理解,例如,如果我只需要Date值,我只需使用此查询:

SELECT c.Date FROM c

但是现在我还要将子文档投影到DailyCurve属性下。

要收到我可以使用的全套:

SELECT c.Date, c.DailyCurve FROM c

但是,我必须做什么才能收到TimeStampACPower值?

我想要创建的结果应如下所示:

[{      
    "Date": 1481673600,
    "DailyCurve": [
      {
        "TimeStamp": 1481673600,
        "ACPower": 0,
      },
      {
        "TimeStamp": 1481716800,
        "ACPower": 30.599999999999998,
      },
      {
        "TimeStamp": 1481717700,
        "ACPower": 50.099999999999994,
      },
      {
        "TimeStamp": 1481718600,
        "ACPower": 46.6,
      },
    ]
},
...]

1 个答案:

答案 0 :(得分:1)

您需要用户定义的功能才能执行此操作。首先,为这样的项目注册一个UDF:

function project(document) {
  var result = {};
  result["Date"] = document["Date"];
  result["DailyCurve"] = [];

  var dailyCurve = document["DailyCurve"]; 
  for (var idx in dailyCurve) {
    var elem = dailyCurve[idx];
    result["DailyCurve"].push(
       { "TimeStamp": elem["TimeStamp"], 
         "ACPower": elem["ACPower"]});
  }  
  return result;
}

然后在DocumentDB查询中使用它,如:

SELECT udf.project(c) FROM c

如果您希望在DocumentDB中看到对子查询投影的原生支持(不需要UDF),请在此处提出/ upvote:https://feedback.azure.com/forums/263030-documentdb