How to query for negated results in CouchDB (Python)

348 Views Asked by At

Does CouchDB have a way to return back the documents that do not meet a certain filter criteria? I am using Python' API and provided an example below:

couch['test_db'].view('doc/entrybyname', key=value, include_docs=True)

Say I wanted all the documents that didn't match the key value...does CouchDB offer a way to do this?

Right now I am getting all documents than filtering them as needed which is very inefficient, especially as the database grows in size.

Thanks for your help in advance.

Brian

1

There are 1 best solutions below

0
On

There is no way to return data from a that is not in an index, only data that is in the index. The Mango/Query mechanism does allow you to perform queries such as this:

{
  "selector": {
    "country_code": { "$ne": "UK"}
  }
}

which reads as "find my all of the documents where country_code is not equal to 'UK'", but the query would not be powered by an index - it would require a scan of all the documents - so would not be performant for large data volumes.

Depending on your use-case, you can create a custom Map/Reduce index that only includes the documents you are interested in e.g.

function(doc) {
  if (doc.country_code != 'UK') {
    emit(doc.country_code, null);
  }
}

which creates an index of all the documents which are not in the UK, keyed on the country code.