我的 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
}
]
我想实现两件事,但不知道如何查看数组内部。
返回
log[n].e = "purchase"
所在位置的用户(记录)。我想我已经用SELECT * from c WHERE ARRAY_CONTAINS(c.log, {"e": "atb"}, true)
实现了这一点返回用户 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.');
}
输出:
关于sql - 如何使用 SQL 在 CosmosDB 中搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58684210/