首页 > 解决方案 > 如何使用 SQL 在 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. e="purchase"在日志中找到第一个事件之后返回用户的 ID、“其他信息”和部分日志。(在这种情况下,view2、view3、purchase、view4)。

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

标签: sqlarraysazureazure-cosmosdb

解决方案


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

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.');
}

输出:

在此处输入图像描述


推荐阅读