Database / CouchDB Interview Questions
How does the reduce function work in CouchDB views and what are the built-in reduce functions?
The reduce function in a CouchDB MapReduce view aggregates the values emitted by the map function within a key range. CouchDB implements reduce using a rereduce mechanism: values are first reduced in small groups (reduce pass), then those partial results are reduced again (rereduce pass) until a single value remains. This makes reduce scalable across large datasets but also means your reduce function must handle rereduce correctly.
CouchDB provides three built-in reduce functions implemented natively in Erlang (much faster than JavaScript):
_sum— sums all emitted values. Input values must be numbers or arrays of numbers._count— counts the number of emitted key-value pairs regardless of value._stats— returns a statistics object withsum,count,min,max, andsumsqr(for standard deviation).
# Query a view with reduce (default: group_level=0, returns grand total)
curl "http://localhost:5984/sales/_design/reports/_view/revenue_by_region"
# {"rows":[{"key":null,"value":1482390.50}]}
# Group by exact key (group=true)
curl "http://localhost:5984/sales/_design/reports/_view/revenue_by_region?group=true"
# {"rows":[{"key":"APAC","value":312450},{"key":"EMEA","value":589120},...]}
# Group by first element of a compound key array
curl "http://localhost:5984/sales/_design/reports/_view/by_date?group_level=1"
# Groups by year only when key is [year, month, day]
Custom JavaScript reduce functions are allowed but must handle the rereduceboolean parameter: when rereduce=true, the input values are partial reduce results rather than raw map values. Incorrect rereduce handling is a common source of wrong aggregation results.
More Related questions...