Mike Baranczak
Mike Baranczak

Reputation: 8374

A filtered and sorted view in CouchDB?

I have some items in CouchDB with a timestamp field and a group field. I use this view function to get a list of all items where group == "foo":

{
  "map" : "function(doc) { emit(doc.group, doc); }"
}

http://localhost:5984/my_database/_temp_view?key="foo"

Now I'd like to make the output sorted by the timestamp field. How do I do that? Basically, I want the equivalent of this SQL query:

SELECT * FROM SomeTable WHERE group=? ORDER BY timestamp

Upvotes: 2

Views: 387

Answers (1)

Victor Nicollet
Victor Nicollet

Reputation: 24587

Emit the timestamp as a second column:

function(doc) { emit([doc.group,doc.timestamp]); } 

Then, query with the following parameters:

view?startkey=["foo"]&endkey=["foo",""]

I am assuming that your timestamps are numbers, not strings. Read this to understand how the numeric timestamps will be sorted in-between ["foo"] and ["foo",""].

Also, don't emit doc as the value, it uses a lot of storage. If you really need the document, use include_docs=true in your query.

Upvotes: 2

Related Questions