4
votes

I'm trying to write an elasticsearch (v5.1) query to check whether all tokens in a field match all tokens in a search term, but in any order.

For example the field could be:

full_name: 'Will Smith'

And the search terms Will Smith or Smith Will would match. However searching Will or Smith would not match.

I've tried match queries with the and operator and phrase queries with slop, but these all ensured that the terms search were all in the field, not that all terms in the field were in the search.

I could index with a new field like reversed_name but was wondering if there was a query option I was missing somewhere.

1

1 Answers

6
votes

You should take a look at the bool query with "minimum_should_match" parameter. It would look something like this in your case:

 {   
    "query":{
        "bool" : {
            "should" : [
               {"term" : { "name" : "Will" }},
               {"term" : { "name" : "Smith" }}
             ],
             "minimum_should_match" : 2
          }
       }
    }
}

This would match "Will Smith" and "Smith Will". If you would like to search only Will or Smith then you would need to change it to this:

 {   
    "query":{
        "bool" : {
            "should" : [
               {"term" : { "name" : "Will" }}
             ],
             "minimum_should_match" : 1
          }
       }
    }
}

Only "Will" will be matched this time. (exact match)