Note that there are some explanatory texts on larger screens.

plurals
  1. POUsing a CouchDB view, can I count groups and filter by key range at the same time?
    primarykey
    data
    text
    <p>I'm using CouchDB. I'd like to be able to count occurrences of values of specific fields within a date range that can be specified at query time. I seem to be able to do parts of this, but I'm having trouble understanding the best way to pull it all together.</p> <p>Assuming documents that have a timestamp field and another field, e.g.:</p> <pre><code>{ 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'} </code></pre> <p>I can easily create a view that <strong>filters documents by a flexible date range</strong>. This can be done with a view like the one below, called with key range parameters, e.g. <code>_view/all-docs?startkey=20120101-0000&amp;endkey=20120201-0000</code>.</p> <p><em>all-docs/map.js:</em></p> <pre><code>function(doc) { emit(doc.date, doc); } </code></pre> <p>With the data above, this would return a CouchDB view containing just the first 4 docs (the only docs in the date range).</p> <p>I can also create a query that <strong>counts occurrences of a given field</strong>, like this, called with grouping, i.e. <code>_view/author-count?group=true</code>:</p> <p><em>author-count/map.js:</em></p> <pre><code>function(doc) { emit(doc.author, 1); } </code></pre> <p><em>author-count/reduce.js:</em></p> <pre><code>function(keys, values, rereduce) { return sum(values); } </code></pre> <p>This would yield something like:</p> <pre><code>{ "rows": [ {"key":"bart","value":1}, {"key":"homer","value":2} {"key":"lisa","value":2} ] } </code></pre> <p>However, I can't find the best way to <strong>both filter by date and count occurrences</strong>. For example, with the data above, I'd like to be able to specify range parameters like <code>startkey=20120101-0000&amp;endkey=20120201-0000</code> and get a result like this, where the last doc is excluded from the count because it is outside the specified date range:</p> <pre><code>{ "rows": [ {"key":"bart","value":1}, {"key":"homer","value":2} {"key":"lisa","value":1} ] } </code></pre> <p>What's the most elegant way to do this? Is this achievable with a single query? Should I be using another CouchDB construct, or is a view sufficient for this?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload