Multiple key search in CouchDB

Emit both keys (or only one if equal):

function(doc) {
  if (doc.hasOwnProperty('key1')) {
    emit(doc.key1, 1);
  }
  if (doc.hasOwnProperty('key2') && doc.key1 !== doc.key2) {
    emit(doc.key2, 1);
  }
}

Query with (properly url-encoded):

?include_docs=true&key=123

or with multiple values:

?include_docs=true&keys=[123,567,...]

UPDATE: updated to query multiple values with a single query.


You could create a CouchDB view which produces output such as:

["key1", 111],
["key1", 123],
["key2", 111],
["key2", 123],
etc.

It is very simple to write a map view in javascript:

function(doc) {
    emit(["key1", doc["key1"]], null);
    emit(["key2", doc["key2"]], null);
}

When querying, you can query using multiple keys:

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

You can send that JSON as the data in a POST to the view. Or preferably use an API for your programming language. The results of this query will be each row in the view that matches either key. So, every document which matches on both key1 and key2 will return two rows in the view results.

Tags:

Couchdb