Search code examples
elasticsearchelasticsearch-6

Optional terms in match_phrase elasticsearch


I am using elasticsearch 6 and have the following query

{  
 "query":{  
  "bool":{  
     "should":[  
        {  
           "match_phrase":{  
              "fieldOne":{  
                 "query":"One two three",
                 "slop":10
              }
           }
        },
        {  
           "match_phrase":{  
              "fieldTwo":{  
                 "query":"one two three",
                 "slop":10
              }
           }
        }

     ]
  }
 }
}

This works well when I want to match on the two fields with the terms in the query.

However if I have a document which has term 'one' and 'two' in fieldOne the above does not return results as 'three' is required

I cannot seems to find a way of making the terms in the query optional e.g. what I wanted is to say find any of the terms in those two fields

The reason I went with match_phrase is the use of the slop which allows the terms to be in different positions in the field which i also require


Solution

  • if the order is not important to use, you don't need to use match_phrase, a simple match query does the job

        {  
           "match":{  
              "fieldOne":{  
                 "query":"one two three"
              }
           }
        },
    

    Then if you need at least two terms to match you can do so using minimum_should_match:

        {  
           "match":{  
              "fieldOne":{  
                 "query":"one two three",
                 "minimum_should_match": 2
              }
           }
        },