incubator-couchdb-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Kai Griffin <>
Subject Re: Help with reduce function
Date Sun, 07 Oct 2012 18:09:37 GMT
Carl, your problem sounds very familiar to me, but I'm not really sure 
if it is quite the same as the problem I once had.  I had a fairly 
complex use-case that involved summarising multiple values from multiple 
document types, being able to search for these by date (in my case 
[year, month] or [year, week_nbr]).  So my map/reduce has so much going 
on, I'm not sure the heart of the issue is really same as yours or not.  
I've done my best to distill this down to your use-case... but there's 
one glaring issue in that my function wants to use the country name as a 
key, and your country names contain spaces, which won't work as keys.  
So, I'm going to assume that they're 2-letter country codes instead.  
Also, I'm sure someone might say that I'm abusing the reduce function... 
there might be a simpler way of doing this with just one value to be summed.

     var obj = {};
     obj[] = 1;
     emit ([date], obj)

     var sums = {};
     for (var i in values)
        for (var k in values[i])
            sums[k] = (sums[k] || 0) + values[i][k];
     return sums;

You can query using startkey,endkeys corresponding to the date range, 
and if you set group_level=0 in your query,  you should end up with 
something like this:

{"key":null, "value":{ UK:3, DE:1, HU:1, FR:2, US:1 }}

Which of course isn't quite the structure you might have been hoping 
for... but it does give the right answer in a single row.

On 06/10/2012 23:12, Carl Bourne wrote:
> Yes - exactly!
> Which was why I was hoping the reduce function would help. I have managed to do this
using some additional middleware (Ruby Sinatra), but that seems to defeat the purpose of using
something like Couch in the first place!
> Carl Bourne | Senior Sales Engineer | mobile: +44 (0) 7770 284294 |
> On 6 Oct 2012, at 21:58, Aurélien Bénel <> wrote:
>>> I still not understand why you need to count the docs with the same exact timestamp
>> Ah I think I understand now... You want to select by (exact) date but group by countries.
>> Hmm, then it's not hierarchical, you have two different dimensions. Then my solution
cannot help you. Sorry.
>> Regards,
>> Aurélien

View raw message