Compound Keys

Compound keys are an essential tool for querying related documents. They can be used to perform the equivalent of an SQL join, as you’ll see in the next section. In a CouchDB view, a compound key is a key made up of more than one attribute. The most common type of compound key in CouchDB is a JSON array. Here is an example of a Map function that emits a compound key, as a JSON array:

function(doc) {
   if (doc.collection && doc.title) {
       emit([doc.collection, doc.title]);
   }
}

The above compound key has the effect of indexing documents first by collection, and then by title (only if the document has both a collection and a title). Later, we’ll see examples of using compound keys to retrieve data from related documents.

A JSON object can serve as a compound key as well. For example:

function(doc) {
   if (doc.collection && doc.title) {
       emit({"collection":doc.collection, "title": doc.title});
   }
}

JSON objects are more expressive, but they also make the resulting index larger.

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.