代码之家  ›  专栏  ›  技术社区  ›  n8wrl

Azure Cosmos DB查询:如何跨文档连接阵列?

  •  0
  • n8wrl  · 技术社区  · 8 年前

    我的CosmosDB数据库中的文档都有这样一个数组元素:

    {
        id: 1,
        list: [1, 2, 3]
    },
    {
        id: 2,
        list: [2, 3, 4]
    },
    ...
    

    我想要一个跨所有文档连接数组“list”的查询(理想情况下,我想要一个唯一的连接,但我可以从所有文档开始)。

    我想要的结果是:

    [1, 2, 3, 2, 3, 4]
    

    甚至更好:

    [1, 2, 3, 4]
    

    这“感觉”像一个集合,但我似乎无法集中注意力。有什么想法吗?

    我知道我可以依次加载每个文档并进行迭代。我希望通过查询来实现这一点,避免依次加载每个文档的开销。

    2 回复  |  直到 8 年前
        1
  •  4
  •   Imre Pühvel    8 年前

    使用SQL查询

    您可以从数组中选择单个值,方法是使用 value 关键词:

    SELECT value i
    FROM c
    join i in c.list
    

    请注意,这将返回单个数组中的所有值,但遗憾的是,其中包含重复值。

    据我所知,目前没有服务器端独特的功能。但是有一个请求 "Provide support for DISTINCT"

    使用SP

    获取服务器端唯一列表的另一种方法是在documentDB集合中使用存储过程:

    function GetUniqueItems() {
        var collection = getContext().getCollection();
    
        var isAccepted = collection.queryDocuments(
            collection.getSelfLink(),
            'SELECT value i FROM c join i in c.list',
            function (err, feed, options) {
                if (err) throw err;
    
                var uniqueArray = feed
                    .filter(function(item, pos) { return feed.indexOf(item) == pos;});
                getContext().getResponse().setBody(uniqueArray);
            });
    
        if (!isAccepted) throw new Error('The query was not accepted by the server.');
    }
    

    您可以从中阅读更多关于如何利用DocumentDB服务器端编程的内容 "Azure Cosmos DB server-side programming: Stored procedures, database triggers, and UDFs" .

        2
  •  3
  •   Dezso Gabos Elvis Douglas Janegitz    7 年前

    您可以使用“Distinct”,现在支持它:

    SELECT distinct value i FROM c join i in c.list
    

    [1, 2, 3, 4]

    推荐文章