Elasticsearch Elasticsearch Match Phrase Query

By Opster Team

Updated: Aug 28, 2023

| 2 min read

Quick links

Introduction

Elasticsearch Match Phrase Query allows users to perform precise text searches by matching exact phrases or word sequences in the provided text. This is particularly useful when the exact sequence of words matters, such as in the case of a quote or a specific phrase.

The Match Phrase Query is different from the Match Query, which operates on the principle of term matching. While the Match Query breaks down the search text into individual terms and returns documents that contain those terms, the Match Phrase Query ensures that the terms are in the exact order as specified in the search query.

Let’s delve deeper into the workings of the Match Phrase Query and how to use it effectively.

Syntax of Match Phrase query

The basic syntax of a Match Phrase Query is as follows:

{
  "match_phrase": {
    "<field>": "<query>"
  }
}

Here, `<field>` is the field you want to search, and `<query>` is the exact phrase you want to match.

Using Match Phrase query

Consider a scenario where you have a collection of documents, and you want to find all documents that contain the exact phrase “quick brown fox”. A Match Phrase Query for this would look like:

{
  "match_phrase": {
    "content": "quick brown fox"
  }
}

This query will return all documents where the phrase “quick brown fox” appears exactly as it is, in the same order.

Slop parameter in Match Phrase query

The Match Phrase Query also supports a `slop` parameter. The `slop` parameter specifies how far apart the terms can be while still considering the document a match. For example, if you set `slop` to 1, the terms can be one position apart.

Here’s how you can use the `slop` parameter:

{
  "match_phrase": {
    "content": {
      "query": "quick fox",
      "slop":  1
    }
  }
}

In this case, the query will match documents that contain “quick” followed by “fox”, even if there is one term in between.

Analyzer in Match Phrase query

The Match Phrase Query uses the same analyzer as that of the field on which the query is performed. However, you can override this by specifying a different analyzer in the query. Here’s an example:

{
  "match_phrase": {
    "content": {
      "query": "quick brown fox",
      "analyzer": "english"
    }
  }
}

In this case, the query will use the “english” analyzer instead of the default analyzer of the “content” field.

Boosting in Match Phrase query

You can also apply boosting in Match Phrase Query to increase the relevance score of the matching documents. Here’s how you can do it:

{
  "match_phrase": {
    "content": {
      "query": "quick brown fox",
      "boost": 2
    }
  }
}

In this case, the relevance score of the matching documents will be multiplied by 2.

How helpful was this guide?

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?