0

I have json documents in Couchbase bucket that looks like this

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

I'm trying to create a query that fetches documents based on group by threadId and most recent document by createdDate.

I wrote a n1ql query like this but it is only return documentId like this.

SELECT max([mes.createdDate,meta(mes).id])
from `messages`  as mes
group  by mes.threadId


result: 
    [
      {
        "$1": [
          1553285245776,
          "11"
        ]
      },
      {
        "$1": [
          1553285245737,
          "12"
        ]
      }
    ]

But i want to result like this

[{
  "id":"10"
  "threadId": "thread1",
  "createdDate": 1553285245575,
}
{
  "id":"11"
  "threadId": "thread1",
  "createdDate": 1553285245776,
}]

Any help would be appreciated

mstzn
  • 2,881
  • 3
  • 25
  • 37

1 Answers1

1
SELECT m.*
FROM `messages` AS mes
WHERE mes.threadId IS NOT NULL
GROUP BY mes.threadId
LETTING m = MAX([mes.createdDate, mes])[1];

You can use following index and query which uses covering avoids fetch.

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];
vsr
  • 7,149
  • 1
  • 11
  • 10