Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference other documents in a couchDB view (joining like functionality)

Tags:

join

view

couchdb

We have a CouchDB representation of an XML database which we use to power a javascript based front-end for manipulating the XML documents. The basic structure is a simple 3 level hierarchy. i.e.

A -> B -> C

  • A: Parent document (type A)
  • B: any number of child documents of parent type A
  • C: any number of child documents of parent type B

We represent these 3 document types in CouchDB with a type attribute:

e.g.

{
"_id":"llgc-id:433",
"_rev":"1-3760f3e01d7752a7508b047e0d094301",
"type":"A",
"label":"Top Level A document",
"logicalMap":{
    "issues":{
        "1":{
            "URL":"http://hdl.handle.net/10107/434-0",
            "FILE":"llgc-id:434"
        },
        "2":{
            "URL":"http://hdl.handle.net/10107/467-0",
            "FILE":"llgc-id:467" 
        etc...
        }
    }
}
}


{
"_id":"llgc-id:433",
"_rev":"1-3760f3e01d7752a7508b047e0d094301",
"type":"B",
"label":"a B document",
}

What I want to do is produce a view which returns documents just like the A type but includes the label attribute from the B document within the logicalMap list e.g.

{
"_id":"llgc-id:433",
"_rev":"1-3760f3e01d7752a7508b047e0d094301",
"type":"A",
"label":"Top Level A document",
"logicalMap":{
    "issues":{
        "1":{
            "URL":"http://hdl.handle.net/10107/434-0",
            "FILE":"llgc-id:434",
            "LABEL":"a B document"
        },
        "2":{
            "URL":"http://hdl.handle.net/10107/467-0",
            "FILE":"llgc-id:467",
            "LABEL":"another B document" 
        etc...
        }
    }
}
}

I'm struggling to get my head around the best way to perform this. It looks like it should be fairly simple though!

like image 721
Surfrdan Avatar asked Jan 07 '11 11:01

Surfrdan


1 Answers

Have a look at the "Linked Document' Section in http://wiki.apache.org/couchdb/Introduction_to_CouchDB_views#Linked_documents

function(doc) {
    //....
    if (doc.logicalMap.issues) {
        for (var i in doc.logicalMap.issues) {
            emit([doc._id,doc.logicalMap.issues[i]['FILE']], 
                                 {_id: doc.logicalMap.issues[i]['FILE']});
        }
    }
}

(untested)

Then query with include_docs=true

like image 123
b_erb Avatar answered Sep 28 '22 21:09

b_erb