Treat term-coverage thresholds as a candidate rule, keep authorization separate and define what happens when analysis removes every query token.
Lexical term coverage: require enough words without losing valid hits
Term coverage is a retrieval gate
A lexical query with several terms can use an all-terms rule, an any-term rule or a threshold between them. All terms can miss a useful document when one word is absent or stemmed differently. Any term can return a large set of weak matches dominated by a common word. A minimum-term threshold requires a chosen number of optional clauses to match before a passage becomes a candidate. The threshold controls eligibility, not just score. BM25 ranks the surviving lexical candidates; it cannot rescue a relevant document removed by a too-strict coverage rule.
Separate required constraints from optional evidence
Tenant, access level, deletion state and document type are hard filters with independent authority. They must never be converted into optional text clauses to raise recall. Likewise, a quoted part number or a user-requested exact phrase may be mandatory even when descriptive words are optional. Parse the query into typed constraints and text clauses before applying a threshold. Literal query parsing prevents punctuation and quotation marks from being silently rewritten into broad term matches. A rule such as 'two of three text words' cannot replace an exact serial-number check.
Analyzer output determines the denominator
Minimum-should-match settings act on the clauses produced after analysis, not necessarily on the number of words typed by the user. Stopword removal, stemming and multi-term synonyms can change clause counts or group clauses differently. A query reduced to zero terms needs an explicit policy: return no lexical matches, route to another safe branch or ask for clarification. A match-all fallback can turn a blank or stopword-only query into a costly full-corpus request and may expose unrelated navigation results. Analyzer contracts must be versioned with the query policy.
Test short and long queries separately
A two-word query requiring both words can be much stricter than a six-word query requiring four. Fixed percentages also round differently at small clause counts, so write out the exact rule per length. Evaluate rare identifiers, negation, spelling mistakes and long natural-language questions as distinct slices. Start with a bounded lexical candidate pool and measure recall before reranking. Candidate recall is the upper bound on what a downstream reranker can recover. If recall falls, broaden optional term coverage or add a semantic branch without weakening mandatory filters.
Keep operators explicit in diagnostics
A broad OR query is often useful for candidate generation, while an AND query can be appropriate for a narrow technical phrase. Neither is a universal default. Log analyzed clauses, required filters, threshold, candidate count and the ranker's winning terms so an engineer can explain why a page appeared. A user-visible advanced query language should escape reserved syntax rather than treating arbitrary user text as executable query operators. Phrase matching applies when order matters; term coverage alone cannot establish adjacency or source support.
Worked contract
import re
STOPWORDS = {"a", "of", "the"}
def lexical_candidates(query: str, passages: dict[str, str],
required_terms: set[str], minimum_optional: int
) -> list[tuple[str, int]]:
optional_terms = set(re.findall(r"[a-z0-9]+", query.casefold()))
required = {term.casefold() for term in required_terms}
optional_terms -= required
optional_terms -= STOPWORDS
if not optional_terms and not required:
return []
if minimum_optional < 0 or minimum_optional > len(optional_terms):
raise ValueError("invalid optional-term threshold")
matches = []
for passage_id, text in passages.items():
words = set(re.findall(r"[a-z0-9]+", text.casefold()))
if not required <= words:
continue
coverage = len(words & optional_terms)
if coverage >= minimum_optional:
matches.append((passage_id, coverage))
return sorted(matches, key=lambda item: (-item[1], item[0]))
passages = {"note-47": "Pressure seal replacement for pump P47",
"note-81": "Pressure regulator inspection for pump P81",
"note-94": "Seal inventory for pump P47"}
assert lexical_candidates("pressure seal", passages, {"p47"}, 1) == [
("note-47", 2), ("note-94", 1)]
assert lexical_candidates("the", passages, set(), 0) == []
assert lexical_candidates("", passages, set(), 0) == []Performance and operating cost
For N passages with T total tokens and Q query terms, this direct scan takes O(T + NQ) expected time for tokenization and set intersections and O(Q + maximum passage vocabulary plus output) extra space per passage if processed sequentially. A real inverted index intersects required postings and counts optional postings without scanning every document. This example intentionally omits authorization and stemming; its tiny stopword set only illustrates the zero-term policy. Apply a separate mandatory permission filter before returning candidates. A zero-term query returns no hits rather than scanning everything.
Common Mistakes
- Treating access-control conditions as optional clauses when trying to improve recall.
- Applying a percentage threshold to raw input words instead of analyzed clauses.
- Allowing a zero-term query to fall through to an unbounded match-all search.
- Assuming a document containing enough terms also contains the requested phrase or supports the answer.
Validation drill
Build 79 queries across one-word identifiers, two-word technical phrases and longer questions. Compare all-term, any-term and length-aware thresholds on authorized candidate recall at 30, false-match rate and lexical execution cost. Include stopword-only and quoted-identifier cases.
