Gustavo Matias
Gustavo Matias

Reputation: 3608

Elasticsearch phrase prefix query on multiple fields

I'm new to ES and I'm trying to build a query that would use phrase_prefix for multiple fields so I dont have to search more than once.

Here's what I've got so far:

{ 
    "query" : { 
        "text" : { 
            "first_name" : { 
                "query" : "Gustavo", 
                "type" : "phrase_prefix" 
            }
        } 
    }
}'

Does anybody knows how to search for more than one field, say "last_name" ?

Upvotes: 20

Views: 22854

Answers (2)

Musab Dogan
Musab Dogan

Reputation: 3690

If you realize some results are missing for phrase_prefix search, it's because of the max_expansions limitation.

While easy to set up, using the match_phrase_prefix query for search autocompletion can sometimes produce confusing results.

For example, consider the query string quick brown f. This query works by creating a phrase query out of quick and brown (i.e. the term quick must exist and must be followed by the term brown). Then it looks at the sorted term dictionary to find the first 50 terms that begin with f, and adds these terms to the phrase query.

The problem is that the first 50 terms may not include the term fox so the phrase quick brown fox will not be found. This usually isn’t a problem as the user will continue to type more letters until the word they are looking for appears.

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-match-query-phrase-prefix.html#match-phrase-prefix-autocomplete


As a workaround you can use multiple prefix under a bool query.

GET items/_search
{"query":{"bool":{"should":[
  {"prefix":{"name_en":{"value":"musab","case_insensitive":true}}},
  {"prefix":{"name_tr":{"value":"musab","case_insensitive":true}}},
  {"prefix":{"name_de":{"value":"musab","case_insensitive":true}}}
]}}}

Upvotes: 0

javanna
javanna

Reputation: 60245

The text query that you are using has been deprecated (effectively renamed) a while ago in favour of the match query. The match query supports a single field, but you can use the multi_match query which supports the very same options and allows to search on multiple fields. Here is an example that should be helpful to you:

{
    "query" : {
        "multi_match" : {
            "fields" : ["title", "subtitle"],
            "query" : "trying out ela",
            "type" : "phrase_prefix"
        }
    }
}

You can achieve the same using the Java API like this:

QueryBuilders.multiMatchQuery("trying out ela", "title", "subtitle")
    .type(MatchQueryBuilder.Type.PHRASE_PREFIX);

Upvotes: 52

Related Questions