How to Use Wildcard Query in Elasticsearch: Syntax and Examples
Use the
wildcard query in Elasticsearch to search text fields with patterns using * for multiple characters and ? for a single character. This query matches documents where the field contains values fitting the wildcard pattern.Syntax
The wildcard query uses a field name and a pattern with wildcards to find matching documents.
- field: The name of the field to search.
- value: The wildcard pattern using
*(any characters) and?(single character). - case_insensitive (optional): Set to
trueto ignore case.
json
{
"query": {
"wildcard": {
"field_name": {
"value": "pattern*?",
"case_insensitive": true
}
}
}
}Example
This example searches the name field for values starting with "jo" and ending with any characters, ignoring case.
json
{
"query": {
"wildcard": {
"name": {
"value": "jo*",
"case_insensitive": true
}
}
}
}Output
{
"hits": {
"total": {
"value": 2,
"relation": "eq"
},
"hits": [
{"_source": {"name": "John"}},
{"_source": {"name": "Joanna"}}
]
}
}
Common Pitfalls
Common mistakes when using wildcard queries include:
- Using wildcards at the beginning of the pattern (e.g.,
*term) can be slow because it scans many terms. - Not setting
case_insensitivewhen needed, causing missed matches. - Using wildcard queries on analyzed fields can give unexpected results; use keyword fields instead.
json
{
"query": {
"wildcard": {
"name": {
"value": "*doe"
}
}
}
}
// Better approach:
{
"query": {
"wildcard": {
"name.keyword": {
"value": "*doe"
}
}
}
}Quick Reference
| Feature | Description | Example |
|---|---|---|
| Wildcard characters | * matches zero or more characters, ? matches exactly one character | jo*, te?t |
| Case insensitive | Set case_insensitive to true to ignore case | "case_insensitive": true |
| Field type | Use keyword or non-analyzed fields for accurate matching | name.keyword |
| Performance | Avoid leading wildcards to keep queries fast | "value": "*term" is slow |
Key Takeaways
Use
wildcard query with * and ? to match patterns in text fields.Set
case_insensitive to true to ignore letter case in matches.Apply wildcard queries on keyword or non-analyzed fields for correct results.
Avoid leading wildcards to prevent slow searches.
Test queries to ensure they return expected documents.