是否有必要在CouchDB中创建单独视图的所有组合

时间:2014-10-17 14:45:20

标签: javascript couchdb couchdb-python couchdb-lucene

我在CouchDB中存储了以下文档:

{
  "_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
}

更新 我想通过页面上的选择框为用户提供选择不同文档的选项,其中可以选择 type name sub_name 。但是,我找不到动态查询的任何示例e。我喜欢这样:

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

我是否要为所有doc.type,doc.name和doc.sub_name组合创建一个类似于下面的单独视图,或者有更好的方法吗?

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);
  }
}
...

1 个答案:

答案 0 :(得分:2)

您无法以您尝试的方式动态查询CouchDB - 在索引时(即创建或更新文档时)构建视图,并且只能通过传递键或键范围来查询。无法基于任何给定的文档属性动态查询。

您可以做的是发出一个复合键:

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

然后,您可以通过传递数组作为键来查询视图:

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