I am using CouchDB. I would like to be able to count the values of the values of certain fields in a date range that can be specified at the time of the request. I seem to be able to do parts of this, but I am having trouble understanding the best way to put it all together.
Assuming documents that have a timestamp field and another field, for example:
{ date: '20120101-1853', author: 'bart' } { date: '20120102-1850', author: 'homer'} { date: '20120103-2359', author: 'homer'} { date: '20120104-1200', author: 'lisa'} { date: '20120815-1250', author: 'lisa'}
I can easily create a view in which filters documents using a flexible date range . This can be done with a view similar to the one below, with key range options, for example. _view/all-docs?startkey=20120101-0000&endkey=20120201-0000 .
all-docs / map.js:
function(doc) { emit(doc.date, doc); }
With the above data, this will return a CouchDB view containing only the first 4 documents (single documents in a date range).
I can also create a query in which it counts the occurrences of a given field , like this, is called with a grouping, i.e. _view/author-count?group=true :
Account author /map.js:
function(doc) { emit(doc.author, 1); }
Account author /reduce.js:
function(keys, values, rereduce) { return sum(values); }
This will give something like:
{ "rows": [ {"key":"bart","value":1}, {"key":"homer","value":2} {"key":"lisa","value":2} ] }
However, I cannot find a better way, either by date or by account . For example, with the above data, I would like to specify the range parameters, such as startkey=20120101-0000&endkey=20120201-0000 , and get a result similar to this, where the last document is excluded from the calculation because it is outside the specified date range:
{ "rows": [ {"key":"bart","value":1}, {"key":"homer","value":2} {"key":"lisa","value":1} ] }
What is the most elegant way to do this? Is this possible with a single request? Should I use a different CouchDB construct or is it enough for this view?