Control term-dictionary fanout, reject broad patterns and keep expansion behind the same access and query-parsing boundaries as ordinary search.
Wildcard retrieval: bound prefix expansion and keep identifiers literal
A wildcard expands a query into terms
A trailing prefix pattern asks a search engine to find indexed terms that start with a given sequence, then search their postings. An infix or leading wildcard can require examining far more of the term dictionary. This differs from autocomplete, which suggests text to a user while typing; a wildcard query actually broadens the candidate set used for ranking or answering. A short pattern can match thousands of terms, creating a large Boolean expansion, latency spike or relevance drift. Treat the expansion as a bounded query-planning operation, not a harmless character in a string.
Do not run user syntax through an unrestricted parser
Accept an explicit, small pattern language rather than letting raw user text become a backend regular expression or query-string program. A conservative interface might allow one trailing star after at least three letters and reject leading stars, multiple wildcards, punctuation and overlong tokens. Escape or reject reserved syntax at the trust boundary. Safe query parsing keeps the user's literal request separate from search operators. For part numbers, route to an exact field unless the product has a documented prefix-search mode; a broad expansion of one digit can bring back a different device.
Expand only within the allowed vocabulary
An approved term dictionary must reflect tenant scope, published status and current deletion state. Generating a broad global list and filtering retrieved documents later can leak private vocabulary through expansion counts, logs or timing. Apply mandatory filters in the actual search backend as well; an authorized suggestion list alone does not authorize documents. Corpus lifecycle supplies the current eligibility rule. If the expansion limit is exceeded, return a clear request to narrow the prefix instead of silently taking the first few terms, which produces unstable and incomplete results.
Budget clauses and postings together
A limit on expanded term count is useful but not sufficient. Ten common expansions can touch more postings than a hundred rare ones. Set a query deadline, clause or automaton complexity cap, and maximum candidate work. Prefix indexes or specialized n-gram fields can reduce lookup cost, but they consume storage and may broaden matching semantics. Record expansion count, estimated postings, execution time and cancellation outcome. Deadline budgeting must include term expansion, not just document ranking. A timeout should not be disguised as an empty answer.
Judge recovery against accidental matches
Create tests for incomplete product names, valid rare codes, short prefixes and patterns containing punctuation. Compare recovered relevant documents with false positives and backend cost. A wildcard branch can complement spelling correction for exploratory search, but it does not prove that a user intended any particular expanded term. Show the interpreted query when it materially changes results. If the branch feeds an answer, keep the actual matched source span and do not imply that a wildcard match itself supports a factual claim.
Worked contract
import re
def expand_prefix(prefix: str, approved_terms: set[str],
max_terms: int) -> list[str]:
if max_terms < 1:
raise ValueError("positive expansion cap required")
if not re.fullmatch(r"[a-z]{3,24}", prefix):
raise ValueError("only bounded lowercase prefixes are supported")
expanded = sorted(term for term in approved_terms
if term.startswith(prefix))
if len(expanded) > max_terms:
raise OverflowError("narrow the prefix before searching")
return expanded
visible_vocabulary = {"sealing", "seal", "sealed", "sensor", "private-seal"}
assert expand_prefix("sea", visible_vocabulary, 3) == [
"seal", "sealed", "sealing"]
try:
expand_prefix("s", visible_vocabulary, 3)
except ValueError:
pass
else:
raise AssertionError("short prefixes must be rejected")
try:
expand_prefix("sea", visible_vocabulary, 2)
except OverflowError:
pass
else:
raise AssertionError("over-budget expansion must fail")Performance and operating cost
This standard-library demonstration scans V approved vocabulary terms in O(VP) worst-case prefix-comparison work for prefix length P, sorts M matches in O(M log M), and uses O(M) output space. A production ordered term dictionary can seek to a prefix and enumerate matching terms closer to O(log V + M) plus postings work. The toy approved set is already scoped; it does not implement access control or actual document search. A backend must enforce the same authorization at retrieval time and cap work beyond the term dictionary. Rejecting an over-budget expansion is safer than silently truncating its terms.
Common Mistakes
- Allowing a leading wildcard or unrestricted regular expression over a large text index.
- Truncating expansions to a few alphabetically first terms and presenting the results as complete.
- Expanding from a global vocabulary before applying tenant and deletion rules.
- Treating a serial-number prefix match as an exact device identity.
Validation drill
Replay 73 prefixes from real search tasks, including two-character strings, rare serials and terms with punctuation. Record expansion count, postings scanned, p95 latency and useful-result rate. Require explicit rejection for patterns above the agreed cost ceiling.
