15 May 2020

combining multiple condition fo refine your searching in elasticsearch

a good example to learn

Bool Query fields:
- must    (and)
- must_not
- should  (or)
- filter


example 1 :(field_1 = "mana" AND field_2 = "mari")
{ "query" : { "bool" : { "must": [{ "match": { "field_1": "mana" } }, { "match": { "field_2": "mari" } }] } } }



example 2 :(field_1 != "mana"  AND field_2 != "mari")
{ "query" : { "bool" : { "must_not": [{ "match": { "field_1": "mana" } }, { "match": { "field_2": "mari" } }] } } }



example 3 : (field_1 = "mana" OR field_2 = "mari")
{ "query" : { "bool" : { "should": [
{ "match": { "field_1": "mana" } },
{
"match": { "field_2": "mari" } }] } } }


example 4 : (field_1 = "mana")
{
  "query": {
    "bool" : {
      "filter"
: {          "term": {          "field_1": "mana"         }       }
    }
  }
}
### filter is much less expensive, as it will NOT have scoring



example 5: to combine filter and others:
(( field_1 = "mana" and field_2 = "mari") and field_3 = "arah")
{ "query" : { "bool" : { "must": [{ "match": { "field_1": "mana" } }, { "match": { "field_2": "mari" } }],
"filter" : { "term": { "field_3": "arah" } } }
} }
### again, 'filter' is less expensive compare to 'match', as it will NOT have scoring

ref:
https://www.elastic.co/blog/lost-in-translation-boolean-operations-and-filters-in-the-bool-query

No comments:

Post a Comment

Terima kasih