0
votes

I am using a couchDB database.

I can get all documents by category and paginate results with a key like ["category","document_id"]and a query likestartkey=["category","document_id"]&endkey=["category",{}]`

Now I want to sort those results by date to have latest documents first.

I tried a lot of keys such as ["category","date","document_id"] but nothing works (or I can't get it working).

I would use something like startkey=["queried_category","queried_date","queried_document_id"]&endkey=["queried_category"]

but ignore the "queried_date" key part (sort but do not take documents where "document_id" > "queried_document_id")

EDIT: Example : With a key like : startkey=["apple","2012-12-27","ZZZ"]&endkey=["apple",{}]&descending=true

I will have (and it is the normal behavior)

"apple","2012-12-27","ABC"
"apple","2012-05-01","EFG"
 ...
"apple","2012-02-13","ZZZ"
...

But the result set I want should start with "apple","2012-02-13","ZZZ"

2

2 Answers

0
votes

Emit the category and the timestamp (you don't need the document_id):

emit(category, timestamp);

And then filter on the category:

?startkey=[":category"]&endkey=[":category",{}]

You must understand that this is only a sort, so you need the startkey to be before the first row, and the endkey to be after the last row.

Last but not least, don't forget to have a representation for the timestamp that is adequate to the sort.

0
votes

The problem with pagination with timestamp instead of doc ID is that timestamp is not unique. That's why you will have problem with paging Aurélien's solution.

I would stay with what you tried but use timestamp as the number (standard UNIX milliseconds since 1970). You can reverse the order of single numeric field just by multiplying by -1:

emit(category, -timestamp, doc_id)

This way result sorted lexicographically (ascending) will be ordered according to your needs:

  1. first dates descending,
  2. then document id's ascending.