Search code examples
elasticsearch

Elastic matchQuery for name


I have a elastic field which contains a user name, eg. my name would contain john doe.

I am trying to create a match query to be able to find my name by phrases like:

  • john d
  • john do
  • doe

My query:

      {
        "bool" : {
          "should" : [
            {
              "match" : {
                "keywords" : {
                  "query" : "john do",
                  "operator" : "AND",
                  "prefix_length" : 0,
                  "max_expansions" : 50,
                  "minimum_should_match" : "50%",
                }
              }
            }
          ]
        }
      }

the problem is that john and john do will not find anything because of the AND operator. If I switch to OR, searching for john doe will actually select every john in the database and my last name will not be even at the top result.

How should the query be formed for such search?


Solution

  • You should use the match phrase prefix query, tested it on below samples and seems to be working fine according to your use-case.

    Sample documents

    {
        "name" :  "john doe"
    }
    
    {
        "name" :  "john"
        
    }
    
    {
        "name" :  "john do"
    
    }
    

    Search query using match phrase prefix

    {
      "query": {
        "match_phrase_prefix": {
          "name": {
            "query": "john d"
          }
        }
      }
    }