0
0
ElasticsearchHow-ToBeginner · 3 min read

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 true to 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_insensitive when 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

FeatureDescriptionExample
Wildcard characters* matches zero or more characters, ? matches exactly one characterjo*, te?t
Case insensitiveSet case_insensitive to true to ignore case"case_insensitive": true
Field typeUse keyword or non-analyzed fields for accurate matchingname.keyword
PerformanceAvoid 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.