dcangulo
dcangulo

Reputation: 2107

How to use OR inside a term in elasticsearch?

I am new to elasticsearch and I need help with adding an OR condition in my query. I current have this query.

{
  :query=>{
    :bool=>{
      :must=>[{
        :query_string=>{
          :default_operator=>"AND", 
          :query=>"*"
        }
      }]
    }
  }, 
  :filter=>{
    :and=>[{
      :term=>{
        :partner_id=>26
      }
    }, 
    {:term=>{
      :is_unpublished=>"false"}
    }]
  }
}

For now, it currently accepts 26 but what if I have 2 values? Eg. 26 and 36, how can I add 36 in OR condition?

If this is SQL it will be something like this:

SELECT * FROM table WHERE (partner_id = 26 OR partner_id = 36) AND is_unpublished = false

I have tried the following but no luck:

{:term => {:partner_id => 36}, :or => [:term => {:partner_id => 26}]}

Also this no luck:

{:term => {:or =>[{:partner_id => 26},{:partner_id => 36}]}}

Upvotes: 0

Views: 166

Answers (3)

Pratik Patel
Pratik Patel

Reputation: 6978

You can also use the following code.

 "should" : [
    { "term" : {
                 "fields": ["tag"],
                 "query: "wow OR elasticsearch" 
              } 
    }
  ]

Upvotes: 0

panchicore
panchicore

Reputation: 11922

Think about should as an OR operator, wrapped by the query bool map:

{
  "query": {
    "bool" : {
      "must" : {
        "term" : { "company" : "stackoverflow" }
      },
      "filter": {
        "term" : { "parner.is_published" : 1 }
      },
      "should" : [
        { "term" : { "partner.age" : 26 } },
        { "term" : { "partner.age" : 36 } }
      ],
      "minimum_should_match" : 1
    }
  }
}

minimum_should_match is key to understand, is how many conditions within the OR you want elasticsearch to match with.

Also, this is not part of the solution but I think would be relevant to you, if you feel thinking yet on SQL ways, take a look to the ES SQL style.

Upvotes: 1

ben5556
ben5556

Reputation: 3018

Using ‘should’ ?

 "should" : [
    { "term" : { "tag" : "wow" } },
    { "term" : { "tag" : "elasticsearch" } }
  ]

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-bool-query.html

Upvotes: 1

Related Questions