【问题标题】:Azure Cosmos DB add related entities to the query resultAzure Cosmos DB 向查询结果添加相关实体
【发布时间】:2020-02-10 13:39:28
【问题描述】:

在我的 cosmos DB 集合中,我有这种类型的实体:

// Suppliers:

[{
    "id": "some_unique_str",
    "products": [
        "id_of_product1",
        "id_of_product2"
    ]
}]

// Products: 

[{
    "id": "id_of_product1",
    "name": "product name"
},
//...
]

我需要写一个查询来得到这样的结果:

[{
    "id": "some_unique_str",
    "products": [
        {
            "id": "id_of_product1",
            "name": "product 1 name"
        },
        {
            "id": "id_of_product2",
            "name": "product 2 name"
        }
    ]
}]

换句话说:我正在尝试实现 OData 扩展功能。 有可能吗?

【问题讨论】:

    标签: azure azure-cosmosdb


    【解决方案1】:

    您无法使用 cosmos db sql api 中的直接 sql 来实现。您的需求可以在关系数据库中使用外键来实现,而不是 no-sql 数据库。

    在cosmos db sql api中,你可以通过存储过程来实现。我试着写了一些代码供你参考:

    function sample(prefix) {
        var collection = getContext().getCollection();
    
        var isAccepted = collection.queryDocuments(
            collection.getSelfLink(),
            'SELECT c.id,c.products FROM c where is_defined(c.products)',
        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 returnArray = [];
                for (var i=0;i<feed.length;i++){  
                    var map = {};
                    map['id'] = feed[i].id;
                    mergeData(map,feed[i].products);
                    returnArray.push(map);
                }
                response.setBody(returnArray);
            }
        });
    
        if (!isAccepted) throw new Error('The query was not accepted by the server.');
    
        function mergeData(map,idArray){
            var sqlQuery = {
                "query":  'SELECT c.id,c.name FROM c where not is_defined(c.products) and '+
                 ' array_contains( @idArray,c.id,true) ',
                "parameters": [
                    {"name": "@idArray", "value": idArray}
                ]
            }
            var isAccepted = collection.queryDocuments(
            collection.getSelfLink(),
            sqlQuery,
            function (err, feed, options) {
            if (err) throw err;
    
            if (!feed || !feed.length) {
                map['products'] = [];
            }
            else {
               map['products'] = feed;
            }
        });
        }
    }
    

    您的样本数据的输出是:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2023-03-14
      • 2020-09-05
      • 1970-01-01
      • 2017-07-03
      相关资源
      最近更新 更多