Callum
Callum

Reputation: 33

CouchDB multi level view map function?

I'm not quite sure what to call what I'm trying to achieve, but will explain it as much as possible. I am trying to use a view to return information from separate documents that are related like a hierarchy. For example, I have these three documents.

{
  "_id" : "line_2c7e12d1",
  "docType" : "Line",
  "lineNumber": 30,
  "pageId" : "page_89bdd679f"
}

{
  "_id" : "page_89bdd679f",
  "docType" : "Page",
  "pageNumber" : 65,
  "bookId" : "book_3684caa2b"
}

{
  "_id" : "book_3684caa2b",
  "docType" : "Book",
  "bookName" : "Some Book Title",
}

And I would like to be able to create a view that allows finding information from about the Book based on the Line id.(multi level hierarchy).

For example, something like this for the View Map function.

function (doc) {
  if(doc.docType == 'Line'){
    emit([doc._id, 1], doc.lineNumber)
    emit([doc._id, 2], {_id : doc.pageId})
    emit([doc._id, 3], {_id : doc.pageId}.pageNumber)
    emit([doc._id, 4], {_id : {_id : doc.pageId}.bookId})
  }
}

I know the first two emit lines work correctly, but the second two do not. I am just wondering if this kind of functionality is possible within CouchDB or if I should structure my data differently. (Include all hierarchy information at the lowest level so it can be searched upwards). Or if anyone has any other suggestions.

Thanks Callum

Upvotes: 2

Views: 241

Answers (1)

Juanjo Rodriguez
Juanjo Rodriguez

Reputation: 2131

It seems that you are trying to include in the view information from related documents. In the map function you only have access to the current doc and you can not query the database for any other document.

You can obtain a kind of "join" functionality following this approach see.

Your data structure is keeping a strong relational flavour that could not be the best approach for CouchDB which is a document oriented database.

Upvotes: 1

Related Questions