0
0
ElasticsearchHow-ToBeginner · 3 min read

How to Use Phrase Match in Elasticsearch for Exact Phrase Searches

Use the match_phrase query in Elasticsearch to search for exact phrases within text fields. This query ensures the words appear in the specified order and proximity, unlike the regular match query which searches for individual words anywhere in the text.
📐

Syntax

The match_phrase query syntax includes the field name and the phrase you want to search for. You can also specify slop to allow some flexibility in word positions.

  • field: The text field to search.
  • query: The exact phrase to match.
  • slop: Optional number of word movements allowed between terms.
json
{
  "query": {
    "match_phrase": {
      "field_name": {
        "query": "your phrase here",
        "slop": 0
      }
    }
  }
}
💻

Example

This example searches the description field for the exact phrase "quick brown fox". The slop is set to 1, allowing one word to appear between the phrase words.

json
{
  "query": {
    "match_phrase": {
      "description": {
        "query": "quick brown fox",
        "slop": 1
      }
    }
  }
}
Output
{ "hits": { "total": 2, "hits": [ {"_source": {"description": "The quick brown fox jumps over the lazy dog."}}, {"_source": {"description": "A quick, agile brown fox was seen."}} ] } }
⚠️

Common Pitfalls

Common mistakes include using match instead of match_phrase when you want exact phrase matching, which returns results with words in any order. Another pitfall is not setting slop when you want to allow some flexibility in word positions, causing missed matches.

Also, phrase matching works best on text fields analyzed with standard analyzers; using it on keyword fields will not work as expected.

json
{
  "query": {
    "match": {
      "description": "quick brown fox"
    }
  }
}

// This matches documents containing any of the words 'quick', 'brown', or 'fox' in any order.

{
  "query": {
    "match_phrase": {
      "description": {
        "query": "quick brown fox",
        "slop": 0
      }
    }
  }
}

// This matches documents containing the exact phrase 'quick brown fox'.
📊

Quick Reference

ParameterDescriptionDefault
field_nameThe text field to searchRequired
queryThe exact phrase to matchRequired
slopNumber of allowed word movements between terms0 (exact match)

Key Takeaways

Use match_phrase to find exact phrases in text fields.
Set slop to allow flexible word positions within the phrase.
Avoid using match when you need phrase order and proximity.
Phrase match works best on analyzed text fields, not keyword.
Test queries to ensure they return expected phrase matches.