Search code examples
couchdbcloudant

How to combine multiple CouchDB queries into a single request?


I'm trying to query documents in a Cloudant.com database (CouchDB). The two following query requests work fine separately:

{ "selector": { "some_field": "value_1" } }

{ "selector": { "some_field": "value_2" } }

Cloudant's documentation seems to indicate I should be able to combine those two queries into a single HTTP request as follows:

{ "selector": { "$or": [ { "some_field": "value_1" }, 
                         { "some_field": "value_2" } ] } }

But when I try that I receive the following response:

{"error":"no_usable_index",
 "reason":"There is no operator in this selector can used with an index."}

Can someone tell me what I need to do to get this to work?


Solution

  • There doesn't seem to be a way to achieve this with Cloudant Query at the moment. However, you can use a view query instead using the index created with Cloudant Query. Assuming the index is in a design document named ae97413b0892b3738572e05b2101cdd303701bb8:

    curl -X POST \
    'https://youraccount.cloudant.com/db/_design/ae97413b0892b3738572e05b2101cdd303701bb8/_view/ae97413b0892b3738572e05b2101cdd303701bb8?reduce=false&include_docs=true' \
    -d '
    {
      "keys":[
        ["value_1"],
        ["value_2"]
      ]
    }'
    

    This will give you a response like this:

    {
      "total_rows": 3,
      "offset": 1,
      "rows": [
        {
          "id": "5fcec42ba5cad4fb48a676400dc8f127",
          "key": [
            "abc"
          ],
          "value": null,
          "doc": {
            "_id": "5fcec42ba5cad4fb48a676400dc8f127",
            "_rev": "1-0042bf88a7d830e9fdb0326ae957e3bc",
            "some_field": "value_1"
          }
        },
        {
          "id": "955606432c9d3aaa48cab0c34dc2a9c8",
          "key": [
            "ghi"
          ],
          "value": null,
          "doc": {
            "_id": "955606432c9d3aaa48cab0c34dc2a9c8",
            "_rev": "1-68fac0c180923a2bf133132301b1c15e",
            "some_field": "value_2"
          }
        }
      ]
    }