Combining Multiple Queries with 'OR' or 'AND' in Elasticsearch

elasticsearch

Solution

You need to use a bool query Something like below will work fine -

{
  "query" : {
    "bool" : { 
      "must" : [
        { // Query1 },
        { // Query2}
      ]
    }
  }
}

Use must for AND and should for OR

Problem

I have two distinct query, and I want to combine them with an 'OR'/'AND' in between. How do I do that? For example, for the given queries I just want to run Query1 OR Query2 in the elasticsearch. Query1: ``` { "query": { "filtered": { "query": { "query_string":{ "query":"Batman", "default_operator":"AND", "fields"::[ "Movies._all" ] } }, "filter": { "bool": { "must": [ { "query":{ "filtered":{ "filter":{ "and":[ { "term":{ "cast.firstName":"Christian " } }, { "term":{ "cast.lastName":"Bale" } } ] } } } } ] } } } } } ``` Query2: ``` { "query": { "filtered": { "query": { "query_string":{ "query":"Dark Knight", "default_operator":"AND", "fields"::[ "Movies._all" ] } }, "filter": { "bool": { "must": [ { "query":{ "filtered":{ "filter":{ "and":[ { "term":{ "director.firstName":"Christopher" } }, { "term":{ "director.lastName":"Nolan" } } ] } } } } ] } } } } } ```

Original source