Elasticsearch in Action: Match Phrase Prefix Queries
The excerpts are taken from my book Elasticsearch in Action, Second Edition. The code is available in my GitHub repository. You can find executable Kibana scripts in the repository so you can run the commands in Kibana straight away. All code is tested against Elasticsearch 8.4 version.
In the last article, we learned about match_phrase
query; in this article, we look at match_phrase_prefix
query.
The match phrase prefix (match_phrase_prefix
) query is a slight variation of the match_phrase
query in that, in addition to matching the exact phrase, the query matches all the words, using the last word as a prefix. This is easiest to understand via an example. The following listing illustrates searching for the prefix Co in the title, which could mean Collections or Concurrency, etc.
GET books/_search
{
"query": {
"match_phrase_prefix": {
"tags": {
"query": "Co"
}
}
},
"highlight": {
"fields": {
"tags": {}
}
}
}
This query fetches all the books with tags matching Co. This includes prefixes such as Component, Core, Code, and so on.
Match phrase prefix using slop
Similar to the match_phrase
query, the order of the words is important in the match_phrase_prefix
query too. Of course, slop
is here to the rescue. For example, when we want to retrieve books with the phrase concepts and foundations across the tags
field, we can omit and by adding the keyword slop
as the following listing demonstrates.
GET books/_search
{
"query": {
"match_phrase_prefix": {
"tags": {
"query": "concepts found",
"Slop":1
}
}
}
}
Setting the keyword slop
as 1 queries the books with the tags concepts and found
*, but it ignores the word and. The query should return the book Kotlin Programming as the result because the query matches the phrase Kotlin concepts and foundational APIs in the tags
field.
Let’s say that we want to find the words Software Development across the title, synopsis,
and tags
fields. That’s exactly what happens when we use a multi_match
query.
We learn about multi_match
query in the next article.