如何使用N1QL将值对象列表单个化为数组

问题描述 投票:0回答:1

我在Couchbase存储桶中有json文档,看起来像这样

{
  "id":"10"
  "threadId": "thread1",
  "createdDate": 1553285245575,
}
{
  "id":"11"
  "threadId": "thread1",
  "createdDate": 1553285245776,
}
{
  "id":"12"
  "threadId": "thread2",
  "createdDate": 1553285245575,
}

我正在尝试创建一个查询,该查询通过threadId获取基于group的文档,并通过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,
}]

任何帮助,将不胜感激

couchbase n1ql couchbase-view spring-data-couchbase
1个回答
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];
© www.soinside.com 2019 - 2024. All rights reserved.