What Is a Wildcard Query in Elasticsearch?

What Is a Wildcard Query in Elasticsearch?

A complete, zero-prior-knowledge walkthrough of pattern matching in Elasticsearch — how the wildcard query works internally, when it quietly becomes the slowest query in your cluster, and how to use it the way production teams actually do.

Picture a librarian who has memorized the exact title of every single book on every shelf. You walk up and say, “I’m looking for something, I think it starts with ‘Har’ and ends with ‘er’, but I can’t remember the middle part.” A librarian who only understands exact titles is stuck. But a librarian who understands patterns — who can scan every title on the shelf and mentally check “does this one fit the shape Har…er?” — can find “Harvester,” “Harbinger,” or “Harmonizer” without you ever remembering the full name. A wildcard query is Elasticsearch playing the role of that second librarian: instead of asking “does this field equal exactly this value?”, it asks “does this field’s value match this shape, with some parts left open?” In this article, we’ll build a complete, practical understanding of how that shape-matching actually works under the hood, why it can be dangerous if used carelessly, and how real engineering teams use it responsibly in production.

1Core Concepts

To understand a wildcard query, we first need to understand what Elasticsearch normally does when you search. Most of the time, when you run a term query or a match query, Elasticsearch is looking for an exact match against entries in its internal dictionary of known values (we’ll get to exactly what that dictionary is in the next chapter). You give it a precise value — "laptop", "USA", "ERR_404" — and it either finds documents containing that exact value, or it doesn’t.

A wildcard query breaks that exactness requirement on purpose. It lets you write a search pattern using two special placeholder characters: the asterisk *, which means “match zero or more of any characters here,” and the question mark ?, which means “match exactly one character of any kind here.” So a wildcard pattern like "lap*" matches “laptop,” “lapse,” and “lap” itself, because the asterisk happily absorbs whatever comes after “lap,” including nothing at all. A pattern like "te?t" matches “test” and “text,” but not “teest,” because the question mark insists on exactly one character in that position, no more, no less.

Everyday Analogy

Think of the asterisk as a rubber stretch of fabric you can pull as long or as short as you like — it fills whatever gap is left, whether that gap is empty or twenty characters long. Think of the question mark as a single, fixed-size puzzle piece — it must fill exactly one slot, no more, no less. If you tell a tailor “make the waist ★ inches” using a stretchy rubber band, that’s your asterisk. If you tell them “leave exactly one button-hole here,” that’s your question mark. Most real search patterns lean almost entirely on the asterisk, precisely because most people remember fragments of unknown length rather than a precise character count — which is exactly why understanding the asterisk’s behavior deeply matters more, in practice, than mastering the question mark’s narrower use case.

It’s worth being precise about where wildcard queries sit in Elasticsearch’s broader family of pattern-matching tools, because beginners frequently reach for wildcard when a different, better-suited tool exists. There’s the prefix query, which only matches values starting with a given string (a narrower, faster special case of a trailing wildcard). There’s the regexp query, which supports full regular expression syntax — far more powerful than wildcard’s two simple placeholders, but also far more expensive to execute. And there’s match_phrase_prefix, designed specifically for autocomplete-style “as-you-type” searching over analyzed text. The wildcard query sits in the middle of this family: more flexible than a plain prefix match, but far simpler — and generally cheaper — than a full regular expression.

i
Key Distinction

A wildcard query matches against terms already stored in Elasticsearch’s index — it does not scan raw document text character by character at query time the way a simple text editor’s “Find” feature does. This distinction is the key to everything that follows in this article, including why wildcard queries can be dangerously slow if you don’t understand it.

To make this concrete, imagine you’re searching a product catalog. If a product’s SKU field holds the value "SKU-88213-RED", a wildcard query for "SKU-882*" will match it — the asterisk absorbs “13-RED” and everything works as you’d expect. This is enormously useful for exactly the kind of “I remember part of it” search scenario our librarian analogy described: partial SKU lookups, partial hostname matches in infrastructure monitoring, partial email domain searches, and pattern-based log analysis are all classic, legitimate uses of the wildcard query — which is exactly why it’s worth understanding thoroughly rather than avoiding altogether.

It’s also worth being clear about what a wildcard query is not. It is not a general “search anywhere inside this value” tool the way a database’s LIKE '%value%' operator might feel — although, with an asterisk at both ends, it can approximate that behavior. It is not aware of word boundaries, synonyms, or stemming the way a proper full-text match query is; a wildcard pattern of "run*" will match the literal term “runner” but has no built-in concept that “running” and “ran” are related forms of the same word the way analyzed full-text search does. And it is not inherently ranked by relevance in any sophisticated sense — a document either contains a matching term or it doesn’t, which is precisely why wildcard clauses are so often placed in a filter context rather than a scoring query context within a larger compound query, a distinction we’ll return to later in this article.

ToolSyntaxBest ForTypical Cost
termExact valueKnown, precise lookupsLowest — direct dictionary lookup
prefixStarts-with only“Begins with X” searchesLow — always prefix-anchored
wildcard* and ?Partial, shape-based matchesLow to very high, depending on pattern shape
regexpFull regular expressionsComplex structural patternsHighest — richest syntax, priciest to evaluate
matchNatural languageOrdinary full-text searchLow to moderate — optimized for this exact case

2Architecture & Components

A wildcard query in Elasticsearch’s Query DSL is a small JSON object, but each of its parts carries real behavioral weight — get one wrong and the query either fails to match what you expected, or becomes dramatically slower than it needs to be.

At its simplest, a wildcard query names a field to search and a value containing your pattern with * and/or ? placeholders. Beyond that minimal shape, several optional parameters shape both correctness and performance:

Required

field / value

The target field to search, and the pattern string itself, containing your * and ? placeholders mixed with literal characters.

Correctness

case_insensitive

When set to true, matching ignores letter case entirely — essential when searching keyword fields, which store values exactly as given, case and all, unlike analyzed text fields which are typically lowercased automatically.

Relevance

boost

A multiplier applied to this query’s contribution to a document’s relevance score, useful when combining a wildcard clause with other, more precise clauses in a compound query.

Performance

rewrite

Controls the internal algorithm Elasticsearch uses to translate your pattern into an efficient search strategy against the term dictionary — an advanced tuning knob most teams never need to touch, but worth knowing exists.

One architectural fact matters more than any single parameter: which field type you run a wildcard query against changes its behavior completely. Against a keyword field, the wildcard pattern is compared against the field’s single, complete, unmodified stored value — exactly as the field’s raw string looked in the source document. Against an analyzed text field, the pattern is instead compared against each individual token produced by that field’s analyzer — meaning a text field containing “Wireless Gaming Mouse” doesn’t store that phrase as one unit, it stores three separate lowercase tokens: “wireless,” “gaming,” “mouse.” A wildcard pattern like "gam*" would match the “gaming” token, but a pattern like "wireless gam*" — containing a literal space — would never match anything at all, because no single token contains a space. This single fact trips up more engineers than any other aspect of the wildcard query, and we’ll return to it repeatedly throughout this article.

It’s also worth knowing that the field mapping itself, not just the query, influences how much work a wildcard search will require. A field mapped as keyword with "index": true stores its values in a way that’s directly searchable by the wildcard automaton; a field with indexing disabled entirely cannot be wildcard-searched at all, regardless of what the query looks like, since there’s no term dictionary for Lucene to walk in the first place. This is a useful diagnostic starting point whenever a wildcard query mysteriously returns nothing: before questioning the pattern syntax, it’s worth confirming the target field is actually indexed and of a type wildcard queries can operate on.

flowchart LR
    A["Pattern: lap*top"] --> B{Target field type?}
    B -- keyword --> C["Compared against the ENTIRE stored value
e.g. 'laptop-charger' as one string"] B -- text --> D["Compared against EACH individual token
produced by the field's analyzer"] C --> E[Match or no match, whole-value] D --> F["Match or no match, per token
(no single token can contain a space)"]
Fig. 1 — The same wildcard pattern behaves differently on keyword vs. text fields

3Internal Working

To really understand why wildcard queries can be slow, we need to understand the data structure they search against: the terms dictionary (sometimes called the term index), which lives inside Elasticsearch’s underlying search library, Lucene. When Elasticsearch indexes a field, it doesn’t store your data as a simple list of documents — it builds an inverted index: essentially, a sorted, alphabetized dictionary of every unique term that has ever appeared in that field, with each term pointing to the list of documents containing it. This is precisely why exact-match searches (like a term query) are extremely fast: finding a single known word in a sorted dictionary is a well-understood, efficient operation — similar to how you’d flip almost directly to the right page in a physical dictionary rather than reading every page from the start.

A wildcard query, however, doesn’t know one specific term to look up. It has to figure out which of the potentially millions of terms in that sorted dictionary actually match your pattern. Internally, Lucene converts your wildcard pattern into a structure called an automaton — think of it as a small state machine that can very efficiently answer the yes/no question “does this specific term match my pattern?” for any term you feed it. The genuinely clever part of Lucene’s implementation is that it doesn’t naively test every single term in the dictionary one by one; because the dictionary is sorted alphabetically, Lucene can use the automaton to intelligently skip large stretches of terms that couldn’t possibly match, jumping ahead rather than checking each one individually.

!
Where Performance Actually Breaks

That clever skipping trick works beautifully when your pattern has a fixed, literal prefix — like "lap*" — because the sorted dictionary lets Lucene jump directly to the “lap” section and only scan from there. It works far worse when your pattern starts with a wildcard — like "*top" — because there is no literal prefix to jump to, forcing Lucene to potentially examine every single term in the entire dictionary, checking each one against the automaton individually. This is called a leading wildcard, and it’s the single most common cause of a wildcard query becoming a serious performance problem.

The scale of this difference is not subtle. On a field with a few thousand unique terms, a leading wildcard might barely be noticeable. On a field with tens of millions of unique terms — a common reality for fields like full URLs, free-text log messages, or user-generated IDs — a leading wildcard query can force Lucene to evaluate every single one of those millions of entries for every single query execution, on every shard, for every search request. This is precisely why Elasticsearch, by default, actually disallows leading wildcards through the standard query_string search syntax (via the allow_leading_wildcard setting, defaulting to true historically but increasingly discouraged), and why experienced engineers treat any pattern starting with * or ? as a deliberate, carefully considered decision rather than a casual default.

There’s one more internal detail worth understanding: the distinction between running a wildcard clause in query context versus filter context. In query context (the default, when a wildcard clause sits directly at the top level of a search request), Elasticsearch computes a relevance score for every matching document, which adds a small amount of extra computation on top of the matching work itself. In filter context (when the same clause is nested inside a bool query’s filter array), Elasticsearch skips scoring entirely and only needs a yes/no answer per document — because most wildcard use cases genuinely don’t need nuanced relevance ranking (a SKU either matches the pattern or it doesn’t), placing wildcard clauses in filter context is both more semantically honest and measurably cheaper. Filter-context clauses are also eligible for Elasticsearch’s filter cache in a way that scored queries typically are not, though as noted earlier, the sheer variety of distinct wildcard patterns in practice still limits how often that cache actually pays off compared to a fixed, repeated exact-match filter.

4Data Flow & Lifecycle

Let’s trace a wildcard query’s complete journey, from the moment a request leaves a client application to the moment ranked results come back, because this full-circle view is what lets you reason about latency and load rather than treating the query as a black box.

1

Request Arrives

A client sends a search request containing a wildcard query clause to any node in the cluster, which acts as the coordinating node for this particular request, regardless of which node actually holds the relevant data.

2

Fan-out to Shards

The coordinating node forwards the query to a copy of every shard belonging to the target index (or index pattern), since each shard holds only a portion of the total data and must independently search its own subset.

3

Automaton Construction

On each shard, Lucene compiles the wildcard pattern into its internal automaton exactly once per query execution, ready to be tested against terms in that shard’s own local term dictionary.

4

Term Dictionary Walk

Lucene walks the sorted term dictionary, using the automaton to identify every matching term — quickly, if the pattern has a usable literal prefix; exhaustively, if it’s a leading wildcard.

5

Document Collection & Scoring

For every matching term found, Lucene retrieves the list of documents containing it, merges these lists, and computes a relevance score for each resulting document using the standard scoring algorithm (typically BM25).

6

Reduce & Return

Each shard returns its own top-scoring results back to the coordinating node, which merges all shard-level result sets into one final, globally ranked list, and returns it to the client.

“A wildcard query isn’t slow because pattern matching is inherently hard — it’s slow exactly to the degree that the term dictionary can’t be narrowed down before the matching starts.”

This lifecycle also explains why wildcard query cost scales with two independent factors that are easy to conflate: the number of documents in your index, and the cardinality (the count of distinct unique values) of the specific field you’re searching. A field with low cardinality — say, a status field with only five possible values — will always be fast to wildcard-search regardless of how many documents exist, because the term dictionary itself is tiny. A field with extremely high cardinality — like a raw log message field or a UUID field — can be slow to wildcard-search even on a relatively small index, because the term dictionary itself is enormous. Understanding cardinality, not just document count, is the real key to predicting whether a given wildcard query will be fast or slow in your specific dataset.

It’s also worth understanding why merging results across shards (step 6) is itself a meaningful part of the cost equation for high-fan-out wildcard searches. Because each shard independently determines its own top matches before the coordinating node merges them, a wildcard pattern that matches an unusually large number of distinct terms can produce a correspondingly large candidate result set on every shard, increasing both the memory pressure of holding those intermediate results and the network cost of shipping them back to the coordinating node for the final merge. This is a second, often-overlooked reason that broad, loosely-anchored wildcard patterns cost more than narrow, well-anchored ones — the expense isn’t confined to the term-dictionary walk alone, it compounds through every later stage of the request lifecycle as well.

5Advantages, Disadvantages & Trade-offs

Advantages

  • Enables genuinely useful “I remember part of it” search experiences — partial SKU lookups, partial hostname matches, fuzzy-feeling searches without the overhead of full fuzzy matching.
  • Simple, familiar syntax (* and ?) that most engineers and even non-technical power users already intuitively understand from everyday file-system searches.
  • Significantly cheaper than a full regexp query for the common case of simple prefix/suffix/infix pattern matching, since the automaton it builds is much simpler.
  • Works natively across both keyword and text fields without requiring any special index-time preprocessing, unlike n-gram-based alternatives.
  • Composes cleanly inside compound queries (bool, dis_max) alongside other, more precise clauses, letting you blend a broad pattern match with tighter filters.

Disadvantages & Trade-offs

  • Leading wildcards can force a full term-dictionary scan, making queries dramatically slower as field cardinality grows — the single biggest operational risk of this query type.
  • Behaves inconsistently across field types (whole-value on keyword, per-token on text) in ways that frequently surprise engineers new to Elasticsearch.
  • Provides no meaningful relevance nuance — a match is a match, with none of the fuzzy scoring gradients that a proper full-text match query offers.
  • Exposing raw wildcard input directly to end users creates a genuine performance and availability risk, since a single carelessly typed leading-wildcard search can consume disproportionate cluster resources.
  • Does not benefit as predictably from caching as exact-match queries, since the astronomically large space of possible wildcard patterns means cache hit rates tend to be low in practice.
Everyday Analogy

Asking “find every book whose title starts with ‘Har'” is a request a librarian can answer quickly, because books are shelved alphabetically — they simply walk to the “Har” section and stop reading once titles no longer match. Asking “find every book whose title ends with ‘er'” is a completely different task — there’s no “ends with ‘er'” section of the shelf, so the librarian is forced to walk past and inspect the title of every single book in the entire library. Both are wildcard-style requests; only one of them respects how the shelf is actually organized.

There’s a broader trade-off worth naming explicitly: wildcard queries optimize for recall — catching every possible match for a shape, even loosely — at the expense of precision and relevance nuance. A full-text match query, by contrast, is built to rank results by how well they satisfy a natural-language intent, factoring in term frequency, field length, and other relevance signals a wildcard query simply doesn’t consider. This means wildcard queries are best suited to situations where the user or system genuinely wants “everything that fits this shape, and I’ll sort through it myself” — an operator investigating an incident, an analyst hunting for a pattern, a catalog lookup with a known partial code — rather than situations where “give me the single best answer” is the actual goal, which is better served by full-text search’s richer relevance model.

6Security

The primary security concern with wildcard queries isn’t unauthorized data access in the traditional sense — it’s resource exhaustion, sometimes framed as a search-layer denial-of-service risk, which becomes a genuine concern the moment any part of a wildcard query’s pattern is influenced by untrusted, end-user input.

Consider a public-facing search box that passes whatever a user types directly into a wildcard query against a high-cardinality field, such as a free-text product description. A well-intentioned user searching for "*phone*" triggers exactly the expensive, full-dictionary-scan scenario described in Chapter 3. Now imagine this isn’t accidental — a malicious actor, aware of this behavior, deliberately submits a flood of concurrent leading-wildcard queries against your most expensive, highest-cardinality field, specifically to consume CPU and I/O across every shard simultaneously. Unlike a classic network-layer denial-of-service attack, this doesn’t require unusual traffic volume — a handful of carefully chosen, expensive queries per second can meaningfully degrade search latency for every other legitimate user on a shared cluster.

!
Real Protection Mechanisms

Elasticsearch offers several concrete levers here: setting "allow_leading_wildcard": false at the query_string level rejects leading-wildcard patterns outright before they can execute; per-request timeout parameters cap how long any single query — including a runaway wildcard scan — is allowed to run before being cut off and returning partial results; and search-layer circuit breakers and thread-pool queue limits provide a cluster-wide backstop against too many expensive queries running concurrently, rejecting new requests once capacity is genuinely exhausted rather than allowing the whole cluster to degrade.

A second, related concern is input validation at the application layer, sitting in front of Elasticsearch itself. Because wildcard syntax uses ordinary characters (* and ?) that a user might type incidentally, applications that build wildcard queries programmatically from raw user input should validate or sanitize that input — for example, escaping literal asterisks a user intended as plain text, capping the number of wildcard characters permitted per query, and rejecting or de-prioritizing patterns that resolve to a leading wildcard — rather than assuming every character a user types is safe to drop directly into a query pattern unexamined.

Practical Defense Pattern

Production search-facing APIs commonly enforce a minimum literal-prefix length (for example, requiring at least three non-wildcard characters before the first asterisk), reject patterns that begin with a wildcard character entirely, apply a strict per-request timeout, and route wildcard-style user searches toward purpose-built alternatives — like an edge_ngram-indexed field, discussed in the Design Patterns chapter — for genuinely high-traffic, user-facing autocomplete features, reserving raw wildcard queries for lower-traffic, internal, or operator-driven tools.

O(1)
PREFIX-ANCHORED PATTERN LOOKUP
O(n)
LEADING WILDCARD ACROSS n TERMS
3+
RECOMMENDED MIN. LITERAL PREFIX CHARS

It’s worth stressing that these defenses are cheap to implement and cost almost nothing for legitimate users, which is exactly why they’re considered standard practice rather than an optional hardening step reserved for high-security environments. A genuine user searching for a product they half-remember is rarely inconvenienced by a rule requiring three literal characters before a wildcard — in practice, most real searches already satisfy that constraint naturally. The rule exists specifically to close off the narrow, deliberately pathological cases that cost the most and benefit legitimate users the least, which is the same risk-versus-friction calculation behind most well-designed rate limits and input constraints across production systems generally, not something unique to Elasticsearch.

7Monitoring, Logging & Metrics

Because a wildcard query’s cost depends so heavily on pattern shape and field cardinality — factors invisible from the query’s JSON alone — production teams rely on a specific set of tools to observe actual, measured cost rather than guessing at it.

Query Breakdown

The Profile API

Attaching "profile": true to any search request returns a detailed, per-query, per-shard timing breakdown — the definitive way to confirm whether a specific wildcard clause is the actual bottleneck in a slow search, rather than something else in a larger compound query.

Cluster-wide Visibility

Slow Log

Elasticsearch’s configurable slow query log records any search exceeding a defined latency threshold, including its full query body — an essential tool for catching expensive leading-wildcard patterns being issued in production without anyone realizing it.

Resource Pressure

Thread Pool & Task Stats

GET /_nodes/stats/thread_pool and GET /_tasks reveal whether search threads are queuing or being rejected — a leading indicator that expensive queries, wildcard or otherwise, are outrunning available capacity.

Field Design Signal

Cardinality Checks

A cardinality aggregation run periodically against candidate fields tells you, in advance, which fields are safe for casual wildcard use and which ones warrant the stricter defenses discussed in the Security chapter.

A mature monitoring setup typically alerts not just on raw latency, but on the combination of high latency and a wildcard clause appearing in the slow log’s captured query body — because a slow term-level query on a low-cardinality field usually points to a different underlying problem (like general cluster load), while a slow wildcard query specifically points toward exactly the pattern-shape and cardinality issues this article has walked through, and is fixable at the query-design level rather than requiring more hardware.

Beyond reactive monitoring, some teams build a lightweight proactive check into their deployment pipeline: before a new field is exposed to wildcard-based search in a user-facing feature, an automated check queries that field’s cardinality via the aggregation mentioned above and flags it if the count exceeds a predefined threshold, prompting a design review before the feature ships rather than after a production incident reveals the problem. This shift-left approach mirrors how many teams already treat other performance-sensitive design decisions — catching an expensive query pattern during code review is dramatically cheaper than diagnosing it under production load, especially for a query type like wildcard whose cost is so sensitive to data characteristics that don’t fully reveal themselves until real-world scale is reached.

8Design Patterns & Anti-patterns

Proven Patterns

Pattern

“Prefix-First Design”

Whenever the underlying use case actually only needs a starts-with match, prefer the dedicated prefix query over a trailing-wildcard pattern — it expresses the same intent, is simpler to reason about, and Lucene can optimize it slightly more directly.

Pattern

“Index-Time Suffix Trick”

For genuinely frequent suffix searches (like “find all domains ending in .gov”), some teams index a reversed copy of the field at write time, converting an expensive leading-wildcard search into a cheap trailing-wildcard search against the reversed value.

Pattern

“Edge N-gram for Autocomplete”

For high-traffic, user-facing “search as you type” features, index text through an edge_ngram analyzer at write time, which pre-computes prefix fragments — trading a small amount of extra index size for dramatically faster query-time matching than repeated wildcard queries.

Pattern

“Keyword-Scoped Wildcards”

Deliberately restrict wildcard queries to keyword fields (or the .keyword sub-field of a text field) whenever whole-value matching is the actual intent, avoiding the token-splitting surprises that come with running wildcard against analyzed text.

Anti-patterns to Avoid

ANTI-PATTERN-01 Avoid
The Problem

Passing raw, unbounded user input directly into a leading-wildcard query against a high-cardinality field on a public-facing search endpoint, with no length restriction, no timeout, and no fallback strategy.

Why It Happens

Wildcard syntax feels intuitive and “just works” during local development on a small dataset, where the term dictionary is tiny and every query feels instant — the performance cliff only becomes visible once real production data volume and cardinality are reached.

The Fix

Treat any user-facing pattern search as untrusted input requiring the defenses covered in the Security chapter: minimum literal-prefix length, rejected leading wildcards, strict timeouts, and — for high-traffic paths — a purpose-built edge-ngram field instead.

ANTI-PATTERN-02 Avoid
The Problem

Running a wildcard query with a phrase-like pattern (containing spaces) against an analyzed text field, expecting it to behave like a whole-phrase match, and getting zero results with no obvious explanation.

Why It Happens

Engineers reasonably assume a text field stores the full original phrase, since that’s how it was written in the source document — the fact that analysis breaks it into separate single-word tokens is invisible unless you specifically inspect the field’s mapping and analyzer.

The Fix

Run wildcard patterns containing spaces against a non-analyzed keyword field or sub-field instead, or restructure the pattern into separate single-token wildcard clauses combined with a bool query if multiple tokens genuinely need to match.

9Best Practices & Common Mistakes

Best Practice

Avoid leading wildcards whenever possible

Redesign the search problem — via reversed fields, edge n-grams, or a different query type entirely — before reaching for a leading-wildcard pattern on any field with meaningful cardinality.

Best Practice

Always set a request timeout

Attach an explicit timeout to any search that includes a wildcard clause over user-influenced input, ensuring a pathological pattern degrades gracefully into partial results rather than tying up a search thread indefinitely.

Best Practice

Test against production-scale cardinality

Validate wildcard query performance against a realistic copy of production data volume and field cardinality, not a small development dataset, since the performance cliff described in Chapter 3 is often invisible at small scale.

Common Mistake

Confusing keyword and text field behavior

Forgetting that a wildcard pattern is evaluated per-token on analyzed text fields but whole-value on keyword fields is the single most common source of “my wildcard query isn’t matching what I expect” confusion.

Common Mistake

Assuming wildcard queries are cached like term queries

Elasticsearch’s query cache benefits filter-context term-level queries heavily, but the enormous variety of possible wildcard patterns means cache hits are comparatively rare — don’t rely on caching to mask a genuinely expensive pattern.

Common Mistake

Reaching for wildcard when regexp or match is a better fit

A wildcard query’s two simple placeholders can’t express alternation, character classes, or repetition counts — for genuinely complex pattern needs, a properly scoped regexp query (with its own performance caveats) is the more honest tool, and for ordinary natural-language search, a match query is usually both faster and more relevant.

Best Practice

Prefer filter context over query context

Nest wildcard clauses inside a bool query’s filter array whenever relevance scoring isn’t genuinely needed, skipping unnecessary scoring computation and making the query’s intent — a yes/no shape check — explicit to anyone reading it later.

Common Mistake

Ignoring index-time alternatives entirely

Treating wildcard queries as the only tool for pattern-style search, without ever considering whether a modest change at index time — a reversed field, an edge n-gram field, a dedicated wildcard field type — would eliminate the performance concern altogether for a genuinely high-frequency search pattern.

10Real-world & Industry Examples

Wildcard queries show up across a wide range of production systems — precisely the systems where users legitimately know only part of what they’re looking for, or where operators need flexible ad-hoc pattern matching over operational data.

IT Operations & Log Analysis

Platform and infrastructure teams running centralized log search frequently use wildcard queries to find hostnames, container IDs, or file paths where only a fragment is remembered — for example, searching *prod-web-0* across a fleet of thousands of servers when an engineer recalls part of a hostname during an incident but not the exact suffix. Because these searches are typically run by a small number of trusted internal operators rather than exposed to the public internet, the resource-exhaustion risk described in the Security chapter is far more manageable, and teams often accept occasionally slower queries as a reasonable trade-off for the flexibility during time-sensitive investigations.

E-commerce SKU & Inventory Search

Retail and warehouse management systems commonly use wildcard queries against structured, well-bounded keyword fields like SKUs or barcode fragments, where cardinality is high but the search is almost always anchored with a known literal prefix (a manufacturer or category code), keeping these queries comfortably in the fast, prefix-anchored case described in Chapter 3.

Security & SIEM Platforms

Threat-hunting and security investigation tools built on Elasticsearch use wildcard queries extensively for pattern matching against indicators of compromise — partial file hashes, partial domain names, partial IP ranges — where an analyst is deliberately searching broadly during an active investigation. These platforms typically pair wildcard support with the exact defenses covered in this article: strict per-query timeouts, dedicated resource pools separated from ordinary user-facing search traffic, and cardinality-aware field design established well in advance of any incident.

Domain and Email Pattern Matching

Anti-abuse and compliance systems that need to match against domain or email patterns (for example, flagging any address ending in a specific suspicious top-level domain) are a textbook case for the “index-time suffix trick” pattern described earlier — reversing the domain string at write time converts what would otherwise be an expensive leading-wildcard search into a fast, prefix-anchored one, at essentially no runtime cost.

Legal, Compliance, and E-discovery Search

Legal document review platforms often let reviewers search archives using partial names, partial case reference numbers, or partial file identifiers whose exact form isn’t known at search time, since documents originate from many different source systems with inconsistent naming conventions. Because accuracy and completeness of recall matter enormously in this domain — missing a relevant document during discovery carries real consequences — teams here are often willing to accept the performance cost of broader wildcard patterns in exchange for confidence that no matching document was silently excluded.

DNS and Network Monitoring

Network observability platforms that index DNS query logs or connection metadata use wildcard queries to identify traffic to or from families of related domains or subdomains — for example, all subdomains of a particular parent domain — which is a natural fit for the “keyword-scoped wildcard” pattern described earlier, since domain and hostname fields are typically stored as exact, unanalyzed keyword values rather than tokenized text.

“The teams that use wildcard queries safely at scale are rarely the ones avoiding them entirely — they’re the ones who know exactly which fields they’re safe on, and why.”

11Frequently Asked Questions

Q1Is a wildcard query the same thing as a regular expression?
No. Wildcard queries support only two placeholders, * and ?, and nothing else — no character classes, alternation, or repetition counts. Elasticsearch’s separate regexp query supports genuine regular expression syntax, but at a generally higher performance cost for equivalent patterns.
Q2Why did my wildcard query return zero results on a field I know contains matching text?
The most common cause is running a pattern containing a space against an analyzed text field, whose tokens never contain spaces — or a case mismatch on a keyword field without case_insensitive: true set, since keyword fields preserve original casing exactly.
Q3Are leading wildcards always slow?
Not always — on a field with genuinely low cardinality, even a leading-wildcard scan of the entire term dictionary can be fast simply because the dictionary itself is small. The risk scales specifically with the number of distinct terms in the field, not the raw document count.
Q4Can I use a wildcard query for numeric or date fields?
Wildcard queries operate on string-like term dictionaries; they are not meaningful for numeric or date field types, which use entirely different internal data structures (BKD trees) optimized for range queries instead of pattern matching.
Q5Does a wildcard query affect relevance scoring differently than a match query?
A wildcard query typically produces a simpler, more binary relevance contribution than a full-text match query, since it’s fundamentally testing term-shape rather than semantic or frequency-based relevance — in practice, most teams place wildcard clauses in a filter context rather than relying on their scoring behavior.
Q6What’s the difference between a wildcard query and the “wildcard” field type?
These are genuinely different features that share a name. The wildcard query is what this article covers — a way to search existing fields with pattern syntax. The wildcard field type is a specialized mapping optimized specifically for fast substring and regex-style matching on long, unstructured strings, trading some storage overhead for significantly better pattern-search performance than a standard keyword field.
Q7Can a wildcard pattern match an empty string?
A pattern consisting only of an asterisk ("*") matches every term in the field, including effectively empty or single-character terms, since the asterisk accepts zero or more characters — this is functionally equivalent to an “exists” check and is rarely what anyone actually intends to write.
Q8Should I put a wildcard clause in query context or filter context?
Filter context, in the vast majority of real cases. Since wildcard matching is fundamentally a yes/no shape check rather than a nuanced relevance signal, nesting it inside a bool query’s filter array skips unnecessary scoring work and better reflects what the query is actually being used for.

12Summary and Key Takeaways

A wildcard query lets you search Elasticsearch using simple pattern shapes — * for “anything, including nothing,” and ? for “exactly one character” — matched against the terms already sitting in a field’s inverted index, not against raw document text scanned fresh at query time. Its real-world cost is governed almost entirely by two factors: whether the pattern has a usable literal prefix that lets Lucene skip large sections of the sorted term dictionary, and how many distinct unique terms (cardinality) exist in the field being searched. Understanding both of these is what separates a wildcard query that returns in milliseconds from one that quietly becomes the slowest, most resource-hungry query on your entire cluster.

Key Takeaways

  • Wildcard queries match against stored terms in the inverted index, not raw text — * matches zero-or-more characters, ? matches exactly one.
  • Field type changes behavior completely: whole-value matching on keyword fields, per-token matching on analyzed text fields.
  • Leading wildcards are the primary performance risk, since they can force Lucene to scan the entire term dictionary instead of jumping to a known prefix.
  • Cost scales with field cardinality, not just document count — a small index with a high-cardinality field can still produce a slow wildcard query.
  • Untrusted user input needs real defenses: minimum prefix length, rejected leading wildcards, strict timeouts, and dedicated resource limits.
  • Purpose-built alternatives often beat wildcard for specific needs — prefix queries, reversed fields for suffix search, and edge_ngram analyzers for high-traffic autocomplete.
  • Real systems — log platforms, SIEM tools, e-commerce SKU search, and anti-abuse pipelines — rely on wildcard queries precisely where users or operators legitimately know only part of what they’re searching for.

None of this requires memorizing every internal detail of Lucene’s automaton implementation. What it requires is the mental model this article has built, chapter by chapter: think of the term dictionary as a sorted shelf of books, think of a literal prefix as the section label that lets you skip straight to the right shelf, and remember that a pattern with nothing to skip to means checking every single book by hand. Design your fields and your patterns with that shelf in mind, and wildcard queries become exactly what they should be — a genuinely useful, predictable tool rather than a hidden performance trap.

The engineers who get the most value out of wildcard queries over the long run tend to share a common habit: they ask “what shape is this search, and what shape is this field?” before they ever write the query itself. A trailing-wildcard pattern against a moderate-cardinality keyword field is almost always safe by default. A leading-wildcard pattern against a high-cardinality free-text field almost always deserves a second look — either a redesign at index time, a stricter guard at the application layer, or a deliberate, informed decision that the cost is acceptable for this particular, lower-traffic use case. That single habit of asking the question first is, in practice, the entire difference between wildcard queries as a reliable production tool and wildcard queries as a recurring incident.