jo / couchdb-best-practices

Collect best practices around the CouchDB universe.
https://jo.github.io/couchdb-best-practices/
Other
321 stars 33 forks source link

What is the optimal and/or recommended way to store Hierarchical data on CouchDB #54

Open jofomah opened 9 years ago

jofomah commented 9 years ago

This should make it easy and possible to do the following in one request:

jofomah commented 9 years ago

Possible Answer:

i think i have found something that can work on CouchDB, i looked into patterns used to store hierarchical data on relational database

but in this case, i will just emit each ancestor array element as key

for(var i in doc.ancestors){
  var ancestorId = doc.ancestors[i];
  emit(ancestorId)
}
var healthFacility = {

  "ancestors": ["NG", "NW", "KN"]
}

if i now query with key = stateId, where stateid = 'KN', i will be able to get all state sub-levels that has 'KN' as one of their ancestors, which what the current adjacent list am using could not give me. (edited)

jo commented 9 years ago

This is a good solution. I recommend to emit the whole ancestors array:

function(doc) {
  emit(doc.ancestors)
}

This has two advantages over using one view per level:

But also a disadvantage:

If you now want to get a list of all docs in state KN you query for the full path:

{
  "startkey": ["NG", "NW", "KN"],
  "endkey": ["NG", "NW", "KN", {}]
}

The same view returns all documents for a higher level:

{
  "startkey": ["NG", "NW"],
  "endkey": ["NG", "NW", {}]
}