0

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

Brian
  • 421
  • 3
  • 20

1 Answers1

2

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)

Dominic Barnes
  • 28,083
  • 8
  • 65
  • 90
  • Thank you so much Dominic! This is the solution I was looking for. – Brian Aug 30 '17 at 20:00
  • Can you also recommend how I can get the count based on a starting or ending document ID? Thanks in advance! – Brian Aug 30 '17 at 20:10
  • I believe you can do that via the `startkey_docid` and `endkey_docid` params. ([documentation](http://docs.couchdb.org/en/2.0.0/api/ddoc/views.html#db-design-design-doc-view-view-name)) – Dominic Barnes Aug 31 '17 at 03:49
  • Okay great. I will give it a try! – Brian Aug 31 '17 at 13:07