Elasticsearch - combining query_string and bool query in filter

Deepak picture Deepak · Dec 29, 2014 · Viewed 15.3k times · Source

Is it possible to combine query_string and bool query in filter query?

For Example -

{
  "filter": {
    "query_string": {
      "query": "field:text"
    }
  },
  "bool": {
    "should": {
      "match": {
        "field": "text"
      }
    }
  }
}

Answer

Vineeth Mohan picture Vineeth Mohan · Dec 29, 2014

bool is meant to be used to club various queries together into a single bool query. You can use bool to combine multiple queries in this manner -

{
  "query": {
    "bool": {
      "must": [
        {
          "query_string": {
            "query": "field:text"
          }
        },
        {
          "match": {
            "field": "text"
          }
        }
      ]
    }
  }
}

The must clause will make sure all the conditions are matched. You can also use should which will make sure either one of the query is matched in case of only should is used.

As bool is just another query type , you can also club bool queries inside bool queries as follows -

{
  "query": {
    "bool": {
      "must": [
        {
          "bool": {
            "must": [
              {
                "query_string": {
                  "query": "field:text"
                }
              },
              {
                "match": {
                  "field": "value"
                }
              }
            ]
          }
        },
        {
          "match": {
            "field": "text"
          }
        }
      ]
    }
  }
}