Reduce

The Map step generates a set of key/value pairs which can then optionally be reduced to a single value—or to a grouping of values—in the Reduce step. As previously discussed, the Map step generates rows that each contain the id of the mapped document, an optional key, and an optional value. The Reduce step primarily involves working with the keys and values, not document IDs. Either a single computed reduction of all values will be produced, or reductions of values grouped by keys will ultimately be produced. Grouping is controlled by parameters passed to your view, not by the Reduce function itself.

CouchDB has three built-in Reduce functions: _count, _sum, and _stats (shown in Table 2-5). In most situations, you will want to use one of these built-in Reduce functions. You can write your own custom Reduce functions, but you should rarely need to. Both the _sum and _stats built-in Reduce functions will only reduce sets of numbers. The _count function will count arbitrary values, including null values.

Table 2-5. Built-in Reduce functions

FunctionOutput
_countReturns the number of mapped values in the set
_sumReturns the sum of the set of mapped values
_statsReturns numerical statistics of the mapped values in the set including the sum, count, min, and max

Count

The built-in _count Reduce function will likely be the most common Reduce function you use. Since it counts arbitrary values, including null values, you can use it while still leaving out the value parameter in your calls ...

Get Writing and Querying MapReduce Views in CouchDB now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.