从Cosmos SQL获取值的分组(不同?!?)数组

时间:2019-10-12 12:42:23

标签: azure-cosmosdb azure-cosmosdb-sqlapi

给出与以下类似的Cosmos文档集合,我想使用Cosmos SQL生成“类别”的分组列表(不同?!?)。在这方面的任何帮助将不胜感激。

[
  {
    "id": "f0136e76-8e66-6a5a-3790-b577001d6420",
    "itemId": "analyze-and-visualize-your-data-with-azure-cosmos-db-notebooks",
    "title": "Built-in Jupyter notebooks in Azure Cosmos DB are now available",
    "categories": [
      "Developer",
      "Database",
      "Data Science"
    ]
  },
  {
    "id": "f0136e76-8e66-6a5a-3790-b577001d6420",
    "itemId": "analyze-and-visualize-your-data-with-azure-cosmos-db-notebooks",
    "title": "Built-in Jupyter notebooks in Azure Cosmos DB are now available",
    "categories": [
      "Developer",
      "Database",
      "Data Science"
    ]
  },
  {
    "id": "d98c1dd4-008f-04b2-e980-0998ecf8427e",
    "itemId": "improving-azure-virtual-machines-resiliency-with-project-tardigrade",
    "title": "Improving Azure Virtual Machines resiliency with Project Tardigrade",
    "categories": [
      "Virtual Machines",
      "Supportability",
      "Monitoring"
    ]
  }
]

1 个答案:

答案 0 :(得分:0)

到目前为止,Azure CosmosDB不支持

GroupBY。您也可以使用存储过程来实现您的要求。

根据您上面提供的示例文档,这是示例存储过程

function groupBy() {
    var collection = getContext().getCollection();
    var collectionLink = collection.getSelfLink();
    var isValid = collection.queryDocuments(
        collectionLink,
        'SELECT * FROM stackoverflow s',
        {EnableCrossPartitionQuery: true},
    function (err, feed, options) {
        if (err) throw err;
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            console.log(JSON.stringify(response));
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            var items = {};
             for(var i=0;i<feed.length;i++){
                 var categories = feed[i].categories;
                 for(var j=0;j<categories.length;j++){
                        items[categories[j]] = categories[j]
                 }
                 var distinctArray = [];
                 for(var distinctObj in items){
                    distinctArray.push(items[distinctObj]);
                }
             }
            response.setBody(distinctArray);
        }
    });

    if (!isValid) throw new Error('Kindly check your query, which not accepted by the server.');
}