Keep text analysis and exact identifiers separate so keyword retrieval finds the right record without changing its identity.
Lexical retrieval: analyzers, fields and exact identifiers
Define an analyzer contract
A lexical analyzer converts source text and query text into comparable terms. Character cleanup, tokenization, case handling, stop words and synonym expansion all affect which documents can enter the candidate set. Record the analyzer version alongside the index; otherwise a query may be analyzed differently from the stored text after a configuration change. A simple token list is useful for an experiment, but a production inverted index also stores postings, field identity and often positions for phrase matching. Hybrid retrieval only benefits from its lexical arm when that arm can actually find the required term.
Do not normalize away identifiers
A part number such as P-47 is an identity constraint, not a bag of words. If punctuation splitting turns it into P and 47, a document about pump P-48 and drawing 47 can appear relevant. Store the canonical part ID in a keyword field with a deliberately narrow normalizer, and filter on it before ranking free text. Preserve the original display form for citations. Likewise, tenant, revision and document status belong in typed fields rather than prose. Entity linking may resolve aliases, but it must not silently replace a verified identifier with a nearby one.
Score fields for their job
A match in a reviewed title can deserve more weight than the same term buried in an attachment, but a title boost is not a permission or authority signal. Production BM25-style scoring accounts for term frequency, rarity and field length; field boosts then express how the application values each field. Apply hard eligibility filters first. Evaluate title-only, body-only and identifier-only queries separately so one tuned score does not hide a severe miss. Reranking cannot recover a document that lexical candidate generation excluded.
Treat synonyms as a release change
Search-time synonyms may improve recall for a controlled vocabulary, yet broad expansion can replace a specific engineering term with a general word and flood the candidate window. Test both index and search analysis with golden token streams, especially multiword synonyms, units and abbreviations. Version the rule set and record which rule produced an expanded term in the trace. Keep exact identity filters outside synonym expansion. Expansion drift tests should catch queries that begin retrieving a different asset family after a new synonym is deployed.
Measure candidate failure before answer failure
Build judged queries with misspellings, plural forms, hyphenated identifiers, long titles and repeated boilerplate. Measure eligible recall at the lexical candidate boundary and compare it with downstream supported answers. Inspect misses by analyzer version and field. A correct answer that came from a vector candidate does not prove the lexical index is healthy. During a migration, run old and new analyzers on the same snapshot and retain the old path until the new one passes the required slices.
Worked contract
from collections import Counter
from dataclasses import dataclass
import re
@dataclass(frozen=True)
class ManualRecord:
document_id: str
part_id: str
title: str
body: str
def terms(text: str) -> Counter[str]:
return Counter(re.findall(r"[a-z0-9]+", text.casefold()))
def rank_manuals(records: list[ManualRecord], query: str,
required_part_id: str) -> list[tuple[str, int]]:
query_terms = terms(query)
scores = []
for record in records:
if record.part_id.casefold() != required_part_id.casefold():
continue
title_terms, body_terms = terms(record.title), terms(record.body)
score = sum(min(count, title_terms[term]) * 4
+ min(count, body_terms[term])
for term, count in query_terms.items())
if score:
scores.append((record.document_id, score))
return sorted(scores, key=lambda item: (-item[1], item[0]))
manuals = [
ManualRecord("pump-p47-r4", "P-47", "P-47 seal pressure", "inspect the seal"),
ManualRecord("pump-p48-r4", "P-48", "P-48 seal pressure", "drawing 47"),
]
assert rank_manuals(manuals, "seal pressure", "P-47") == [("pump-p47-r4", 9)]
assert rank_manuals(manuals, "seal pressure", "P-49") == []Performance and operating cost
Building an inverted index is proportional to the indexed term count and stores postings in addition to source text. The standard-library demonstration scans N records with L terms each, costing O(NL) time and O(N) result space; it is intentionally a contract check, not a replacement for an inverted index or BM25. A keyword filter narrows the eligible set before ranking, while broader synonym rules increase postings visited and candidate pressure.
Common Mistakes
- Using a text analyzer for an exact part ID or tenant key.
- Changing query tokenization without testing compatibility with indexed terms.
- Treating a title boost as proof that a document is authoritative.
- Measuring only final answer quality while the lexical candidate pool loses required evidence.
Validation drill
Create 53 queries covering hyphens, aliases, plurals, units and title/body conflicts. Compare old and new analyzer token streams, exact-ID recall and eligible recall at the candidate boundary.
Read next
- Hybrid retrieval: fuse exact terms and semantic candidates by rank
- Entity linking for retrieval: resolve aliases before searching facts
- Query expansion: add recall terms without changing the user's question
- Retrieval design: compare lexical, semantic and reranked candidates
