How to Use Prefix Query in Elasticsearch: Syntax and Examples
Use the
prefix query in Elasticsearch to find documents where a field's value starts with a specified prefix. It matches terms beginning with the given string, making it useful for autocomplete or filtering by partial values.Syntax
The prefix query has a simple structure with two main parts:
- field name: The field you want to search.
- prefix value: The starting string to match in that field.
Optionally, you can add boost to increase the relevance score of matches.
json
{
"query": {
"prefix": {
"field_name": {
"value": "prefix_string",
"boost": 1.0
}
}
}
}Example
This example searches for documents where the user field starts with jo. It returns all users like "john", "joseph", or "joanna".
json
{
"query": {
"prefix": {
"user": {
"value": "jo"
}
}
}
}Output
{
"hits": {
"total": 3,
"hits": [
{"_source": {"user": "john"}},
{"_source": {"user": "joseph"}},
{"_source": {"user": "joanna"}}
]
}
}
Common Pitfalls
Common mistakes when using prefix query include:
- Using it on analyzed fields, which breaks terms into tokens and may not match prefixes as expected.
- Not considering case sensitivity; prefix queries are case-sensitive by default.
- Using very short prefixes, which can cause performance issues due to many matches.
Always use keyword or non-analyzed fields for prefix queries and choose prefixes carefully.
json
{
"query": {
"prefix": {
"message": {
"value": "Error"
}
}
}
}
// Wrong if 'message' is analyzed, use 'message.keyword' instead:
{
"query": {
"prefix": {
"message.keyword": {
"value": "Error"
}
}
}
}Quick Reference
| Part | Description |
|---|---|
| field_name | The field to search for the prefix |
| value | The prefix string to match at the start of the field value |
| boost (optional) | Increase relevance score of matching documents |
Key Takeaways
Use prefix query to find documents with fields starting with a specific string.
Apply prefix query on keyword or non-analyzed fields for accurate results.
Prefix queries are case-sensitive and can impact performance if prefix is too short.
Use the 'value' key to specify the prefix string in the query.
Boost can adjust the importance of prefix matches in search results.