2

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

Ashok Kumar Jayaraman
  • 2,887
  • 2
  • 32
  • 40
Callum
  • 33
  • 3

1 Answers1

1

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.

Juanjo Rodriguez
  • 2,103
  • 8
  • 19
  • Thanks Juanjo, The question linked helped me work out how I could implement what I was looking for. My actual data isnt quite as relational as shown above but was the easiest example I could come up with. I found this link given in the linked answer https://danielwertheim.se/couchdb-many-to-many-relations/ really usefull as an example implementation. – Callum Jan 23 '19 at 09:54