Elasticsearch in Action: Match Phrase Prefix Queries

Madhusudhan Konda
2 min readJan 27, 2023
Excerpts taken from my upcoming book: Elasticsearch in Action

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.

Me @ Medium || LinkedIn || Twitter || GitHub

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_phrasequery 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_phrasequery, the order of the words is important in the match_phrase_prefixquery too. Of course, slopis 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 slopas the following listing demonstrates.

GET books/_search
{
"query": {
"match_phrase_prefix": {
"tags": {
"query": "concepts found",
"Slop":1
}
}
}
}

Setting the keyword slopas 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.

Me @ Medium || LinkedIn || Twitter || GitHub

These short articles are condensed excerpts taken from my book Elasticsearch in Action, Second Edition. The code is available in my GitHub repository.

Elasticsearch in Action

--

--

Madhusudhan Konda

Madhusudhan Konda is a full-stack lead engineer, mentor, and conference speaker. He delivers live online training on Elasticsearch, Elastic Stack &Spring Cloud