javascriptcouchdbcouchdb-pythoncouchdb-lucene

Is it necessary to create all combination a separately view in CouchDB


I have the following documents in CouchDB stored:

{
  "_id":"1",
  "_rev":"1-e3ff3eb51ccf90e0446ef086fcc6a06c",
  "sub_name":"A01",
  "type":"Test",
  "name":"A",
  "pos":828288
}{
  "_id":"2",
  "_rev":"1-e3ff3eb51ccf90e0446ef086fcc6a06c",
  "sub_name":"A02",
  "type":"Test",
  "name":"A",
  "pos":828288
}{
  "_id":"3",
  "_rev":"1-ef83655c51f64daa4c074fed9beb8234",
  "sub_name":"B01",
  "type":"Test",
  "name":"B",
  "pos":171878
}{
  "_id":"4",
  "_rev":"1-ef83655c51f64daa4c074fed9beb8234",
  "sub_name":"B02",
  "type":"Test",
  "name":"B",
  "pos":171878
}{
  "_id":"5",
  "_rev":"1-52b91ba1577a11bf410999ceb2577206",
  "sub_name":"C01",
  "type":"Test",
  "name":"C",
  "pos":871963
}{
  "_id":"6",
  "_rev":"1-52b91ba1577a11bf410999ceb2577206",
  "sub_name":"C02",
  "type":"Test",
  "name":"C",
  "pos":871963
}{
  "_id":"7",
  "_rev":"1-807f46b501b237a6e0f2ba71ffd7f194",
  "sub_name":"D01",
  "type":"Test",
  "name":"D",
  "pos":1932523
}{
  "_id":"8",
  "_rev":"1-807f46b501b237a6e0f2ba71ffd7f194",
  "sub_name":"D02",
  "type":"Test",
  "name":"D",
  "pos":1932523
}

UPDATE I would like to give the user options to select different documents via select boxes on the page, where there can chose type, name and sub_name. However, I could not find any examples to do a query dynamically e. g like this:

function(doc, type, name, sub_name) {
  if (doc.type == type && doc.name == name && doc.sub_name == sub_name) {
    emit(doc._id, doc.pos);
  }
}

Have I to create for all doc.type, doc.name and doc.sub_name combination a separately view similar to the below ones or is there a better way to do it?

function(doc) {
  if (doc.type == "Test" && doc.name == "A" && doc.sub_name == "A01") {
    emit(doc._id, doc.pos);
  }
}

function(doc) {
  if (doc.type == "Test" && doc.name == "A" && doc.sub_name == "A02") {
    emit(doc._id, doc.pos);
  }
}

function(doc) {
  if (doc.type == "Test" && doc.name == "B" && doc.sub_name == "B01") {
    emit(doc._id, doc.pos);
  }
}
...

Solution

  • You can't query CouchDB dynamically in the way you're trying to - views are constructed at index-time (i.e. when documents are created or updated) and can only be queried by passing keys or key ranges. Querying dynamically based on any given document property is not possible.

    What you can do is emit a composite key:

    function(doc) {
        emit([doc.type, doc.name, doc.sub_name], doc.pos);
    }
    

    You can then query the view by passing an array as the key:

    /.../my_view?key=["Test","B","B01"]