Rohan Veer
Rohan Veer

Reputation: 1490

match query on elastic search with multiple or conditions

I have three fields status,type and search. What I want is to search the data which contains status equals to NEW or status equals to IN PROGRESS and type is equal to abc or type equals to xyz and search contains( partial match ).

My call looks like below -

{
 "query": {
  "bool" : {
      "must" : [{
                "match": {
                "status": {
                    "query": "abc",
                    }
                }
                }, {
                    "match": {
                    "type": {
                        "query": "NEW",
                        }
                    }
                },{
                    "query_string": {
                        "query": "*abc*",    /* for partial search */
                        "fields": ["title", "name"]
                    }
                }]
        }
    }
}

Upvotes: 0

Views: 8493

Answers (1)

Dennis Ich
Dennis Ich

Reputation: 3785

Nest your boolqueries. I think what you are missing is this:

"bool": { "should": [ 
   { "match": { "status": "abc" } }, 
   { "match": { "status": "xyz" } } 
]}

This is a query which MUST match one of the should clauses as only should clauses are given.

EDIT to explain the differences:

{
   "query": {
      "bool": {
         "must": [
            {
               "bool": {
                  "should": [
                     {
                        "match": {
                           "status": "abc"
                        }
                     },
                     {
                        "match": {
                           "status": "xyz"
                        }
                     }
                  ]
               }
            },
            {
               "terms": {
                  "type": [
                     "NEW",
                     "IN_PROGRESS"
                  ]
               }
            },
            {
               "query_string": {
                  "query": "*abc*",
                  "fields": [
                     "title",
                     "name"
                  ]
               }
            }
         ]
      }
   }
}

So you have a boolquery at top. Every of the 3 inner queries must be true.

  1. The first is a nested boolquery which is true if status matches either abc or xyz.
  2. The second is true if type matches exactly NEW or IN_PROGRESS - Note the difference here. The First one would also match ABC or aBc or potentially "abc XYZ" depending on your analyzer. You might want terms for both.
  3. The third is what you had before.

Upvotes: 5

Related Questions