Chapter 3. Design Documents

As we saw in Chapter 2, a MapReduce view is comprised of a Map JavaScript function and an optional Reduce JavaScript function. These functions can be run within a temporary view or they can be saved permanently as a view within a design document. Design documents are stored in your database alongside your other documents and can contain one or more views. They can be created, read, updated, and deleted, just like any other document. One difference between design documents and regular documents is that the ID of design documents must always begin with _design, followed by a forward slash (/), and then an identifier specific to the design document.

Titles View

Let’s save a slightly updated version of our titles view from Chapter 2 to a new design document with an ID of _design/default. We’ll map book documents to key/value pairs of titles and number of pages.

In Futon, navigate to the books database, select “Temporary view…” from the “View” drop-down menu, and paste the following JavaScript function into the “Map Function” text box, replacing the existing function:

function(doc) {
   if (doc.title) {
       emit(doc.title, doc.pages);
   }
}

Enter the name of the built-in _stats Reduce function in the “Reduce Function” text box:

_stats

Next, let’s test your Map and Reduce functions. Click “Run”, check or uncheck the “Reduce” checkbox as you’d like, and select “none” or “exact” from the “Grouping” drop-down menu. When you have verified that the output is as you’d expect, click ...

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.