sql - 如何使用 SQL 在 CosmosDB 中搜索数组

标签 sql arrays azure azure-cosmosdb

我的 CosmosDB 文档中有一个简单的数组。一个例子 SELECT * FROM c 返回:

[
    {
        "id": "v1234567",
        "otherinfo": "othervalue",
        "log": [
            {
                "ts": 1572786079799,
                "e": "view1"
            },
            {
                "ts": 1572781436024,
                "e": "purchase"
            },
            {
                "ts": 1572786079799,
                "e": "view2"
            },
            {
                "ts": 1572786082033,
                "e": "view3"
            },
            {
                "ts": 1572781436024,
                "e": "purchase"
            },
            {
                "ts": 1572786082033,
                "e": "view4"
            }
        ],
        "_rid": "something",
        "_self": "something",
        "_etag": "\"something\"",
        "_attachments": "attachments/",
        "_ts": 1572786088
    }
]

我想实现两件事,但不知道如何查看数组内部。

  1. 返回 log[n].e = "purchase" 所在位置的用户(记录)。我想我已经用 SELECT * from c WHERE ARRAY_CONTAINS(c.log, {"e": "atb"}, true) 实现了这一点

  2. 返回用户 ID、“otherinfo”以及在日志中找到第一个 e="purchase" 事件之后的日志部分。 (在本例中为 View 2、 View 3、购买、 View 4)。

我正在 Azure 门户中使用文档资源管理器。尝试过联接查询,但它立即失败(因为我可能弄错了)。

最佳答案

请使用以下我测试成功的存储过程来实现您的需求:

function sample(prefix) {
    var collection = getContext().getCollection();

    var isAccepted = collection.queryDocuments(
        collection.getSelfLink(),
        'SELECT c.id,c.otherinfo,c.log from c WHERE ARRAY_CONTAINS(c.log, {"e": "view2"}, true)',
    function (err, feed, options) {
        if (err) throw err;

        // Check the feed and if empty, set the body to 'no docs found', 
        // else take 1st element from feed
        if (!feed || !feed.length) {
            var response = getContext().getResponse();
            response.setBody('no docs found');
        }
        else {
            var response = getContext().getResponse();
            for(var i=0;i<feed.length;i++){
                console.log(i)
                var logArray = [];
                for(var j=0;j<feed[i].log.length;j++){
                    console.log(feed[i].log[j].e)
                    logArray.push({"e":feed[i].log[j].e});
                }
                feed[i].log = logArray;
            }

            response.setBody(feed);
        }
    });

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

输出:

enter image description here

关于sql - 如何使用 SQL 在 CosmosDB 中搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684210/

相关文章:

sql - Oracle一次查询将INSERT插入两个表

sql - 如何在两个日期之间恢复 SQL 中的整个日期范围,即使没有数据?

c# - 我应该为整数对使用什么数据结构?

mysql - GROUP CONCAT 的替代方案

c++ - 用分配的最后一个值覆盖数组?

javascript - 使用javascript创建多个对象的二维数组,其中对象具有相同的属性

azure - 在 Windows Azure 中测试应用程序,无需创建试用帐户

azure - Sql Server 有没有办法找到 View 中哪些列没有索引

azure - MS azure 删除默认域

php - 如何将自定义 MySQL 查询添加到与 Prestashop 共享数据库的 userfrosting 页面?