3
votes

I'm trying to write a couchdb view that takes a created_at timestamp in a sortable format (2009/05/07 21:40:17 +0000) and returns all documents that have a greater created_at value.

I'm specifically using couch_foo but if I can figure out how to write the view I can create it in futon or in the couch_foo model instead of letting couch_foo do it for me.

I've searched all around and can't figure out the map/reduce to do this, if it's possible.

3

3 Answers

4
votes

This is the kind of problem I ran into initially before I fully understood how views work.

The key to the understanding is that the view is only run once for each (revision of) a document. In other words, when you query a view, you don't run the function, you simply look up the results of when the function ran. As such, there is no way to pass any user-submitted parameters into a view.

How then to compare a value in a view with a user-submitted value? The secret is to emit that field as a key in the map function and rely on letting couchdb order by the keys.

Your map function would be something like

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

and you would query it like so:

http://localhost:5984/db/_design/ddoc/_view/view?startkey=%222009/05/07%2021:40:17 +0000%22

I have taken the liberty of uriEncoding the quotes and spaces in the url so that it should be usable as is.

3
votes

You want to write a view that creates a key of the timestamp field in that format, then query it with the startkey parameter.

So the view would look something like:

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

And your URL would be something like:

http://mysever/database/_design/mydoc/_view/myview?startkey="2009/05/07 21:40:17 +0000"

The HTTP view API page on the Wiki has more info. You may also consider the User Mailing List.

1
votes

Please mind that couchdb works only on json values. If the timezone if the document stored in couchdb is different to the timezone of your startkey the query likely will fail.