7

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.

6 Answers 6

4

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.

1
  • This does not answer the question. This just gets the documents, once you have figured out which documents you want. The trick is figuring out the list of documents you want. Nov 16, 2011 at 18:09
0

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.

1
  • 7
    Well, sure, if you know "key1" and "key2" in advance, but what if you want them to be "dynamic" parameters? Nov 16, 2011 at 18:01
0

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.

0

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.

0

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.

-2

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 )

1
  • 3
    It just won't work with big quantities of data. Intersection is O(n log n) and it will make clients choke with enough results
    – Andrea
    May 31, 2012 at 8:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.