Cosmos DB Sql如何获取数组中不同的项目列表?

时间:2019-02-14 20:03:20

标签: azure-cosmosdb azure-cosmosdb-sqlapi

假设您将以下文档存储在cosmos db中,并希望获取分区p1中所有文档的关键字的不同列表。

[
    {
        "PartitionKey": "p1",
        "id": "i1",
        "Property1": "somevalue",
        "Keywords": [
            "k1"
        ]
    },
    {
        "PartitionKey": "p1",
        "id": "i2",
        "Property1": "some other value",
        "Keywords": [
            "k1",
            "k2"
        ]
    }
]

在这种情况下,我想获得一个返回k1, k2的列表。我知道您可以对单个属性进行区分,但是如何对这样的数组中的值进行区分呢?那可能吗?

1 个答案:

答案 0 :(得分:0)

我想,如果您不想使用distinct获得数组结果,则可以使用Cosmos DB Stored Procedure来实现您的要求。请参阅我的示例js代码:

// SAMPLE STORED PROCEDURE
function sample() {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT r.Keywords FROM root r where r.PartitionKey = "p1"',
    function (err, feed, options) {
        if (err) throw err;
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            var map = {};
             for(var i=0;i<feed.length;i++){
                 var keyArray = feed[i].Keywords;
                 for(var j=0;j<keyArray.length;j++){
                        map[keyArray[j]] = keyArray[j]
                 }
                 var returnArray = [];
                 for(var key in map){
                    returnArray.push(map[key]);
                }
             }
            response.setBody(returnArray);
        }
    });

    if (!isAccepted) throw new Error('The query was not accepted by the server.');
}

输出:

enter image description here