How to Use Match Query in Elasticsearch: Syntax and Examples
Use the
match query in Elasticsearch to search text fields by matching analyzed terms. It works by breaking the search text into terms and finding documents that contain those terms in the specified field. The match query is simple and effective for full-text search scenarios.Syntax
The match query syntax includes the field to search and the query text. You can also add options like operator to control how terms are combined (e.g., and or or).
- field: The name of the text field to search.
- query: The text to search for.
- operator (optional): Defines if all terms (
and) or any term (or) must match.
json
{
"query": {
"match": {
"field_name": {
"query": "search text",
"operator": "or"
}
}
}
}Example
This example searches the description field for documents containing the words "quick brown fox". The operator is set to and, so all words must be present in the document.
json
{
"query": {
"match": {
"description": {
"query": "quick brown fox",
"operator": "and"
}
}
}
}Output
{
"hits": {
"total": 2,
"hits": [
{"_id": "1", "_source": {"description": "The quick brown fox jumps over the lazy dog."}},
{"_id": "3", "_source": {"description": "A quick brown fox is fast and clever."}}
]
}
}
Common Pitfalls
Common mistakes when using match query include:
- Using
matchon non-text fields like numbers or keywords, which won't analyze the input properly. - Not setting the
operatorwhen you want all terms to match, leading to unexpected results. - Confusing
matchwithtermquery, which does exact matching without analysis.
Example of wrong vs right usage:
json
{
"query": {
"match": {
"status": "active"
}
}
}
// Wrong if 'status' is a keyword field, use term query instead:
{
"query": {
"term": {
"status": "active"
}
}
}Quick Reference
| Option | Description |
|---|---|
| query | The text to search for in the field. |
| operator | Controls if all terms (and) or any term (or) must match. |
| fuzziness | Allows fuzzy matching for typos (e.g., 'auto'). |
| minimum_should_match | Minimum number of terms that must match. |
| analyzer | Specify a custom analyzer for the query text. |
Key Takeaways
Use
match query for full-text search on analyzed text fields.Set the
operator to 'and' if all terms must appear in results.Avoid using
match on keyword or numeric fields; use term query instead.You can add fuzziness to handle typos in search terms.
The
match query breaks input text into terms and searches for documents containing those terms.