Today was one of those “how did I not know about this?!” days.
At lunch @jchris mentioned that using the “builtin” sum reduce was up to 100x faster than using a JavaScript reduce function that does the same thing. Then of course my reaction was “wtf is a builtin reduce?”.
Apparently CouchDB has these awesome internal erlang functions for common reduce operations that you can use instead of a calling out to the view server that you just set in your design document instead of a JavaScript function. Since they don’t talk to the view server and can work on native erlang terms, skipping the JSON serialization steps, they are absurdly fast. Like so fast that there is very little reason to ever write another JavaScript reduce.
It’s all written up on the wiki but here is the gist of it.
{ "_id":"_design/company", "_rev":"12345", "language": "javascript", "views": { "all_customers": { "map": "function(doc) { if (doc.type == 'customer') emit(doc.id, 1) }", "reduce" : "_count" }, "total_purchases_by_customer": { "map": "function(doc) { if (doc.type == 'purchase') emit(doc.customer_id, doc.amount) }", "reduce": "_sum" } } }










