How to Use match_phrase Query in Elasticsearch
Use the
match_phrase query in Elasticsearch to search for exact phrases in text fields. It matches documents containing the words in the specified order and proximity, unlike match which searches for individual words anywhere.Syntax
The match_phrase query requires a field name and the phrase you want to find. You can also specify slop to allow some words between the phrase terms.
- field: The text field to search.
- query: The exact phrase to match.
- slop: Optional number of words allowed between phrase terms.
json
{
"query": {
"match_phrase": {
"field_name": {
"query": "your phrase here",
"slop": 1
}
}
}
}Example
This example searches the description field for the exact phrase quick brown fox. It will only match documents where these words appear together in this order.
json
{
"query": {
"match_phrase": {
"description": {
"query": "quick brown fox"
}
}
}
}Output
{
"hits": {
"total": 2,
"hits": [
{"_source": {"description": "The quick brown fox jumps over the lazy dog."}},
{"_source": {"description": "A quick brown fox was seen in the forest."}}
]
}
}
Common Pitfalls
One common mistake is using match instead of match_phrase when you want an exact phrase match. match finds documents with the words anywhere, not necessarily together.
Another pitfall is forgetting to adjust slop when you want to allow some words between phrase terms.
json
{
"query": {
"match": {
"description": "quick brown fox"
}
}
}
// This matches documents with all words but not necessarily as a phrase.
// Correct way:
{
"query": {
"match_phrase": {
"description": "quick brown fox"
}
}
}Quick Reference
| Parameter | Description |
|---|---|
| field_name | The text field to search for the phrase |
| query | The exact phrase to match |
| slop | Optional number of words allowed between phrase terms (default 0) |
Key Takeaways
Use
match_phrase to find exact phrases in text fields.Set
slop to allow flexibility in word positions within the phrase.Avoid using
match when you need phrase matching, as it matches words anywhere.Phrase queries are order-sensitive and match terms in sequence.
Test queries to ensure they return expected phrase matches.