Views

The only way to query a CouchDB database (other than accessing individual documents directly) is through the use of views. Views are defined by a Map function and an optional Reduce function. Every view has exactly three columns (the doc column is technically not part of the view, but can optionally be returned as part of the result set):

key

This is the first argument to the emit function call(s) in your Map function. Any valid JSON value is allowed. The key argument is optional and will be null in the generated view row if omitted.

id

Whenever the emit function is called in a Map function, the document ID of the mapped document is automatically included as part of the generated view row.

value

This is the second argument to the emit function call(s) in your Map function. Any valid JSON value is allowed. The value argument is optional and will be null in the generated view row if omitted.

Once a view has been created, CouchDB offers a variety of ways to query the view. Queries are made against the view’s key field. Results can be further refined using the view’s id field. All three fields are returned as part of the results and the originating document can optionally be included as well (only if results are not reduced and not grouped). If a Reduce function is defined for the view, then results can be grouped and aggregate values can be returned. See Chapter 4 for more information about querying views.

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.