CouchDB Returning None for Row Key (reduce function)

195 views Asked by At

I have a map function and reduce function to count all the occurrences of a key. The code is below for CouchDB 2.0 design document:

Map Function

function(doc) { emit(doc.domainID, 1); }

Reduce Function

_sum

Here is a snapshot of what the browser shows:

Map and reduce functions result

And here is the result when I run the following code in Python:

import couchdb
couch = couchdb.Server("http://localhost:5984/")    
counts = couch['event_db'].view('doc/eventbydomainid',
                                 reduce=True, descending=True)

Terminal result when printing key and value

Terminal result showing no key

I am expecting the following result, but not seeing it:

{"ad1": 32, "ad2": 1}

Any help would be appreciated.

Thank you,

Brian

1

There are 1 answers

4
Dominic Barnes On BEST ANSWER

When you are using a reduce function, the default behavior is to reduce the entire dataset to a single value. If you want grouping, add group=true to your request. (documentation)

And while you didn't ask about this specifically, you'll no doubt come across it while working with map/reduce in CouchDB. If you are emitting complex keys (eg: arrays), you can use the group_level parameter to group by the various parts of the array from left to right. (example)

An interesting use-case here is emitting a date as an array, such as: [2017, 8, 29, 22, 59, 16]. Using group_level=1 will group by year, group_level=2 will group by year+month, and so on. (pro tip: using group_level will set group=true implicitly)