Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In CouchDB you would write a map/reduce that outputs ALL of the cars and drivers with complex keys, and then use key ranges to pick both. For example, let's assume your documents look like these two...</p> <pre><code>{ "_id": "...", "_rev": "...", "docType": "driver" } { "_id": "...", "_rev": "...", "docType": "car", "driver": "driver's _id" } </code></pre> <p>You could use <a href="http://en.wikipedia.org/wiki/Duck_typing" rel="nofollow noreferrer">duck typing</a> instead of specifying the docType, but I like this method better.</p> <p>Your map function:</p> <pre><code>function(doc) { if(doc.docType == "driver") emit([doc.id, 0], doc); elseif(doc.docType == "car") emit([doc.driver, 1], doc]; } </code></pre> <p>Our complex key is an array, with the first item always being the driver's _id. The second item in the array prevents key collision, and allows us to reference the car or driver directly (more on this later). </p> <p>We can now use the key range query parameters to grab both of the docs.</p> <pre><code>?startkey=["driver _id"]&amp;endkey=["driver _id", {}] </code></pre> <p>This basically says "give me any array with the driver _id as the first item, and anything in the second. This works because objects - the second item in the <code>endkey</code>'s array - is sorted as the highest. See <a href="http://wiki.apache.org/couchdb/View_collation?redirect=ViewCollation#Collation_Specification" rel="nofollow noreferrer">http://wiki.apache.org/couchdb/View_collation?redirect=ViewCollation#Collation_Specification</a> for more information about how items get sorted/weighed in keys.</p> <p>This also scales quite nicely, because we can add more information into our map function without having to change our query in the client. Let's say we add a sponsor docType: we just add another <code>elseif</code> for the docType field and then <code>emit([doc.driver, 2], doc);</code>. Now we can pull all three documents in one request with the same key range query from above.</p> <p>Of course, you can also specify individual documents instead of pulling all of them. <code>?key=["driver's _id", 1]</code> would pull just the car for the specified driver.</p> <p>Cheers.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload