CouchDB and multiple keys

房东的猫 提交于 2019-12-23 08:29:08

问题


Is it possible to use similiar query in CouchDB? Like use two keys?

SELECT field FROM table WHERE value1="key1" OR value2="key2"

I was always using only one key.

function(doc) {

    emit(doc.title, doc);

}

Thank you.


回答1:


In CouchDB 0.9 and above you can POST to a view (or _all_docs) with a body like:

{"keys": ["key1", "key2", ...]}

In order to retrieve the set of rows with the matching keys.




回答2:


Yes. Something like this should do the trick if I understand your question:

function(doc) {
  a = (doc.value1 && doc.value1 == "key1");
  b = (doc.value2 && doc.value2 == "key2");
  if (a || b) {
    emit(doc._id,doc.title);
  }
}

Only emit the documents or values you need.




回答3:


I'd add this to duluthian's reply:

 emit(doc.title, null)

You can always pull out the "_id" and doc values using the view api.




回答4:


You could create a view like this:

function(doc){
    if(doc.value1) emit(doc.value1, doc.field);
    if(doc.value2) emit(doc.value2, doc.field);
}

Then query it using llasram's suggestion to POST to the view with:

{"keys": ["key1", "key2", ...]}

Your client will have to be wary of dups though. A document where doc.value1 == "key1" && doc.value2 == "key2" will show up twice. Just use _id to filter the results.




回答5:


One needs to expand a little bit on llasram's answer; the index must contain the values for both fields:

function(doc) {
  emit("value1:"+doc.value1); // add check for undefined, null, etc.
  emit("value2:"+doc.value2);
}

then query with

keys=["value1:key1","value2:key2"]

EDIT: This will however report the same document multiple times if it contains the matching value+key pairs.




回答6:


You could do this ( assuming you want "dynamic parameters" ) by using 2 separate views, and a little client-side processing:

You would have one view on "field1", which you would query with "value1". ( getting a list of document IDs )

Then you query a second view on "field2", passing "value2", and getting another list of Doc IDs.

Now, you simply have to find the "intersection" of the 2 lists of ID numbers ( left as an exercise for the reader )



来源:https://stackoverflow.com/questions/3549299/couchdb-and-multiple-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!