sql - 如何使用 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
}
]
我想实现两件事,但不知道如何查看数组内部。
返回用户(记录)在哪里
log[n].e = "purchase"
。我想我已经做到了SELECT * from c WHERE ARRAY_CONTAINS(c.log, {"e": "atb"}, true)
e="purchase"
在日志中找到第一个事件之后返回用户的 ID、“其他信息”和部分日志。(在这种情况下,view2、view3、purchase、view4)。
我在 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.');
}
输出:
推荐阅读
- markdown - remark-gfm 脚注被忽略
- google-apps-script - 从作为用户“您无权访问请求的文档”执行的 Webapp 返回内容时出错。
- python - 您必须安装 pydot (`pip install pydot`) 并安装 graphviz 才能使 plot_model 工作
- python - 如何使用 API 将成员添加到电报组
- c# - 是否可以从 IEnumerable 方法中获取 NUnit TestContext MethodName?
- vue.js - vue composition API - ref变量内的计算属性
- python - Selenium firefox 配置文件下载目录首选项未实现
- webforms - NetSuite WebForm 加载缓慢
- python - Django - 尝试按最新订购 get_object_or_404
- python - python setup.py 在 nix-shell 中安装