我在Couchbase存储桶中有看起来像这样的json文档
{
"id":"10"
"threadId": "thread1",
"createdDate": 1553285245575,
}
{
"id":"11"
"threadId": "thread1",
"createdDate": 1553285245776,
}
{
"id":"12"
"threadId": "thread2",
"createdDate": 1553285245575,
}
我正在尝试创建一个查询,该查询将根据group by threadId和最新的document by createdDate来获取文档。
我这样写了一个n1ql查询,但只返回了documentId这样的查询。
SELECT max([mes.createdDate,meta(mes).id])
from `messages` as mes
group by mes.threadId
result:
[
{
"$1": [
1553285245776,
"11"
]
},
{
"$1": [
1553285245737,
"12"
]
}
]
但是我想要这样的结果
[{
"id":"10"
"threadId": "thread1",
"createdDate": 1553285245575,
}
{
"id":"11"
"threadId": "thread1",
"createdDate": 1553285245776,
}]
任何帮助将不胜感激
答案 0 :(得分:1)
SELECT m.*
FROM `messages` AS mes
WHERE mes.threadId IS NOT NULL
GROUP BY mes.threadId
LETTING m = MAX([mes.createdDate, mes])[1];
您可以使用以下索引和查询,这些索引使用覆盖来避免获取。
CREATE INDEX ix1 ON `messages`(threadId, createdDate DESC, id);
SELECT m.*
FROM `messages` AS mes
WHERE mes.threadId IS NOT NULL
GROUP BY mes.threadId
LETTING m = MAX([mes.createdDate,{mes.threadId,mes.createdDate, mes.id}])[1];