Best way to do one-to-many "JOIN" in CouchDB

Posted by mit on Stack Overflow See other posts from Stack Overflow or by mit
Published on 2010-06-13T18:43:04Z Indexed on 2010/06/14 7:22 UTC
Read the original article Hit count: 169

Filed under:
|

There are CouchDB documents that are list elements:

{ "type" : "el", "id" : "1", "content" : "first" } 
{ "type" : "el", "id" : "2", "content" : "second" } 
{ "type" : "el", "id" : "3", "content" : "third" } 

There is one document that defines the list:

{ "type" : "list", "elements" : ["2","1"] , "id" : "abc123" }

As you can see the third element was deleted, it is no longer part of the list. So it must not be part of the result. Now I want a view that returns the content elements including the right order.

The result could be:

{ "content" : ["second", "first"] }

In this case the order of the elements is already as it should be. Another possible result:

{ "content" : [{"content" : "first", "order" : 2},{"content" : "second", "order" : 1}] }

I started writing the map function:

map = function (doc) {
  if (doc.type === 'el') {
    emit(doc.id, {"content" : doc.content}); //emit the id and the content
    exit;
  }
  if (doc.type === 'list') {
    for ( var i=0, l=doc.elements.length; i<l; ++i ){
      emit(doc.elements[i], { "order" : i }); //emit the id and the order
    }
  }
}

This is as far as I can get. Can you correct my mistakes and write a reduce function? Remember that the third document must not be part of the result.

Of course you can write a different map function also. But the structure of the documents (one definig element document and an entry document for each entry) cannot be changed.

© Stack Overflow or respective owner

Related posts about couchdb

Related posts about mapreduce