Recover ordinary misspellings without silently rewriting part numbers, names or exact-match evidence.
Spelling correction in retrieval: suggest a fix, preserve the original
Correction is a candidate branch
A misspelled word can create a zero-result query even when the right document is indexed. A correction service proposes alternatives from a controlled vocabulary; it does not establish what the user intended. Search the original text first or alongside a suggested form, then present the correction explicitly when it changes results. A silent rewrite can retrieve the wrong part or person. Safe query parsing defines the user's literal request; correction must preserve that record for tracing and evaluation.
Protect identifier-shaped tokens
Maintenance IDs, invoice numbers, code symbols and legal clauses often differ by one character. Edit distance would call them close, but their meaning may be unrelated. Route tokens with digits, punctuation or recognized identifier patterns through exact fields, with correction disabled unless a domain-specific alias registry says otherwise. Ordinary words can be considered for correction after a lexical miss. Identifier-safe lexical search protects the corresponding index fields. Keep case and punctuation rules consistent with each identifier family.
Generate and rank alternatives conservatively
Edit distance is a candidate generator, not a relevance score. Limit candidate vocabulary by language, source status and permission scope, then use term frequency and contextual fit only within that allowed set. One edit in a short word may be more dangerous than two edits in a long word. Correct at most a bounded number of tokens so a long noisy query does not explode into combinations. The query expansion guardrail applies: record which branch added a candidate and what evidence it returned.
Choose the display contract
If the original search has strong exact matches, do not replace it. If correction produces better results, label them as results for the corrected text and offer a one-click return to the original. Show one or a few alternatives, not a hidden substitution chain. For a retrieval-based answer, a candidate corrected query still needs claim-level source support; higher result count alone does not justify an answer. Evidence-bound answering can abstain when both branches fail.
Evaluate false corrections explicitly
Build separate test slices for typos, rare names, serial numbers, multilingual terms and already-valid but uncommon words. Count successful recovery and harmful rewrites, not just suggestion acceptance. A model can over-correct rare valid terms toward popular words, especially after popularity ranking. Test newly added vocabulary and deleted documents, because a correction index can lag the retrieval index. A suggestion pointing to removed or forbidden content is still a leak. Private autocomplete has the same vocabulary and permission boundary.
Worked contract
import re
IDENTIFIER = re.compile(r"(?=.*[0-9])[A-Za-z0-9/-]{3,}$")
def edit_distance(left: str, right: str) -> int:
previous = list(range(len(right) + 1))
for row_number, left_char in enumerate(left, 1):
current = [row_number]
for column_number, right_char in enumerate(right, 1):
current.append(min(current[-1] + 1,
previous[column_number] + 1,
previous[column_number - 1]
+ (left_char != right_char)))
previous = current
return previous[-1]
def suggest_spelling(token: str, approved_terms: set[str]) -> str | None:
if IDENTIFIER.fullmatch(token) or len(token) < 4:
return None
candidates = [(edit_distance(token.casefold(), term.casefold()), term)
for term in approved_terms]
close = sorted((distance, term) for distance, term in candidates
if distance == 1)
return close[0][1] if close else None
assert suggest_spelling("presure", {"pressure", "seal"}) == "pressure"
assert suggest_spelling("P-47/AC", {"P-48/AC"}) is None
assert suggest_spelling("seal", {"seal"}) is NonePerformance and operating cost
The two-row edit-distance routine uses O(LR) time and O(R) space for token lengths L and R. Scanning V approved terms multiplies that work by V; a production dictionary uses length buckets, prefix indexes or a specialized candidate structure before exact distance checks. Preserve the original query branch so the suggestion can be rejected. The example returns one candidate only and does not implement contextual ranking, authorization or a search engine.
Common Mistakes
- Silently replacing a user's serial number with the nearest popular code.
- Treating edit distance alone as proof of intended meaning.
- Building the suggestion dictionary from restricted or deleted content.
- Measuring only recovered queries while ignoring harmful corrections of valid rare words.
Validation drill
Label 81 queries: ordinary typos, rare valid terms, multilingual words and one-character-different IDs. Measure recovered top-12 recall and harmful-rewrite rate with the original branch retained.
