Database / CouchDB Interview Questions
What are MapReduce views in CouchDB and how do you define a map function?
MapReduce views are CouchDB's primary indexing mechanism. A view has a map phase (mandatory) and an optional reduce phase. The map function is a JavaScript function that CouchDB runs against every document in the database. For each document it emits zero or more key-value pairs. CouchDB stores these emissions in a B-tree index, kept sorted by key. The reduce function (when present) aggregates values within a key range.
Views are defined inside design documents under the views key:
{
"_id": "_design/products",
"views": {
"by_category": {
"map": "function(doc) { if (doc.type === 'product' && doc.category) { emit(doc.category, { name: doc.name, price: doc.price }); } }"
},
"price_by_category": {
"map": "function(doc) { if (doc.type === 'product') { emit(doc.category, doc.price); } }",
"reduce": "_sum"
},
"by_compound_key": {
"map": "function(doc) { if (doc.type === 'order') { emit([doc.year, doc.month, doc.day], 1); } }"
}
}
}
Key points about map functions:
- The
emit(key, value)call adds an entry to the index. A single document can emit multiple times, creating multiple index entries. - Keys can be strings, numbers, arrays, or null. Arrays support compound-key queries — range queries on
[year, month]work naturally. - The value can be any JSON. Emitting
nullas the value and usinginclude_docs=truein the query avoids duplicating the full document in the index. - Map functions must be pure (no side effects, no external HTTP calls) and deterministic.
Views are built lazily on first query and updated incrementally on subsequent queries — only documents changed since the last index update are re-processed.
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...
