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.
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
