Elasticsearch Match Phrase Query - Syntax, Example, and Tips

Pulse - Elasticsearch Operations Done Right

On this page

Syntax Example Query Common Issues Best Practices Frequently Asked Questions

The Match Phrase Query in Elasticsearch is used for exact phrase matching within full-text fields. It's particularly useful when you need to find documents containing an exact sequence of words in a specific order.

Syntax

The basic syntax for a Match Phrase Query is:

GET /your_index/_search
{
  "query": {
    "match_phrase": {
      "field_name": "exact phrase to match"
    }
  }
}

For more details, refer to the official Elasticsearch documentation.

Example Query

Here's an example of a Match Phrase Query searching for the phrase "quick brown fox" in a field named "content":

GET /my_index/_search
{
  "query": {
    "match_phrase": {
      "content": "quick brown fox"
    }
  }
}

Common Issues

  1. No results: This can occur if the exact phrase is not present in any documents or if there are slight variations in word order or punctuation.
  2. Unexpected results: Sometimes, stemming or other analyzers can affect phrase matching. Ensure your field mapping is appropriate for phrase queries.
  3. Performance: Match Phrase Queries can be slower than simple Match Queries, especially on large datasets.

Best Practices

  1. Use the slop parameter to allow for some flexibility in word order:
{
  "match_phrase": {
    "content": {
      "query": "quick brown fox",
      "slop": 1
    }
  }
}
  1. Consider using match with and operator for better performance if exact order is not crucial.
  2. Use highlighting to show where the phrase matches in the returned documents.

Frequently Asked Questions

Q: How does Match Phrase Query differ from Match Query?
A: Match Phrase Query requires all terms to be present in the same order, while Match Query treats terms independently and doesn't consider their order.

Q: Can I use wildcards in a Match Phrase Query?
A: No, Match Phrase Query doesn't support wildcards. For partial matching, consider using Wildcard Query or Regex Query instead.

Q: How can I make the Match Phrase Query case-insensitive?
A: By default, it's case-insensitive. This behavior is controlled by the analyzer used on the field. The standard analyzer, which is the default, performs lowercase tokenization.

Q: What is the purpose of the 'slop' parameter in Match Phrase Query?
A: The 'slop' parameter allows for a specified number of intervening unmatched positions between matching terms, providing some flexibility in the phrase matching.

Q: Can Match Phrase Query be used on numeric or date fields?
A: While it's possible, it's not recommended. Match Phrase Query is designed for text fields. For numeric or date ranges, use Range Query instead.

Subscribe to the Pulse Newsletter

Get early access to new Pulse features, insightful blogs & exclusive events , webinars, and workshops.