Store positions when word order matters, keep analyzer behavior consistent and test phrase boundaries before using matches as evidence.
Phrase and proximity retrieval need a token-position contract
A term match forgets order
A record-level inverted index can find documents containing both words but cannot tell whether they occur together. A phrase query needs token positions, or a slower scan of candidate text. A proximity query also asks how far apart matching terms may be. These are materially different retrieval contracts: a maintenance note about a pressure seal and a note about pressure testing a different seal may share terms without containing the requested phrase. Lexical field mappings should declare which fields retain positions and which remain exact identifiers.
Index-time positions must match query analysis
Lowercasing, punctuation splitting, stemming, synonyms and stopword removal affect the position stream. If stopwords are removed, preserving their position gaps avoids treating two formerly separated words as adjacent. Query analysis must apply the intended counterpart of the index analyzer; mismatched tokenization can make a visible phrase unsearchable. Synonyms with multiple tokens need explicit position handling, not a string replacement that loses order. For code, part numbers and quoted literals, an exact subfield may be safer than a linguistic analyzer. Literal query parsing keeps quotation marks from becoming accidental broad search.
Scope positions to an evidence unit
A phrase must not cross from one field into another or from one unrelated document chunk into the next. Store positions within a field and keep a stable document or passage identity alongside them. If a long manual is split into passages, a phrase at the split boundary can be missed; controlled overlap or parent-document verification can recover it. Chunk boundary tests quantify that tradeoff. Conversely, concatenating unrelated fragments can manufacture a phrase that no source actually says. Show the source span that matched before using it in an answer.
Proximity is not proof of a relationship
Allowing a few positions between terms can improve recall for expressions such as 'seal at high pressure', but a wide window may join terms from separate clauses or opposite statements. Decide whether order matters, define an explicit distance or slop policy, and test negation and section boundaries. Backends differ in how they count a transposition or removed stopword; copy neither a numeric setting nor an intuition between engines without fixtures. Claim support checks still have to read the actual sentence. A positional hit is only a retrieval signal.
Measure the storage and latency price
Positions increase posting size compared with document-only or frequency-only indexing. Phrase evaluation first intersects candidate postings, then checks compatible positions; common terms and wide proximity windows can still be expensive. Keep the phrase field narrow when possible and add budgets for broad queries. Compare exact phrase recall, near-phrase recall and false joins on judged queries. A high match count may mean the analyzer removed discriminating tokens. Inspect the position stream and original character offsets separately; token positions locate a term order, whereas offsets locate text for highlighting. Snippet offsets have their own redaction rules.
Worked contract
import re
from collections import defaultdict
def tokenize(value: str) -> list[str]:
return re.findall(r"[a-z0-9]+", value.casefold())
def positional_index(notes: dict[str, str]
) -> dict[str, dict[str, list[int]]]:
postings = defaultdict(lambda: defaultdict(list))
for note_id, text in notes.items():
for position, term in enumerate(tokenize(text)):
postings[term][note_id].append(position)
return postings
def exact_phrase(postings: dict, phrase: str) -> set[str]:
terms = tokenize(phrase)
if not terms:
return set()
candidates = set(postings.get(terms[0], {}))
for term in terms[1:]:
candidates &= set(postings.get(term, {}))
return {note_id for note_id in candidates
if any(all(start + offset in postings[term][note_id]
for offset, term in enumerate(terms))
for start in postings[terms[0]][note_id])}
notes = {"work-47": "Inspect the pressure seal before restart",
"work-81": "Seal the valve after pressure testing"}
postings = positional_index(notes)
assert exact_phrase(postings, "pressure seal") == {"work-47"}
assert exact_phrase(postings, "seal pressure") == set()Performance and operating cost
Building positions for T tokens takes O(T) time and O(T) posting entries. This simple phrase check intersects document sets and then scans first-term positions; list membership is linear, so a document with many repeated terms can require O(P times Q times P) work for P first-term positions and Q phrase terms. Production engines use ordered or compressed positional postings and merge walks to avoid those repeated linear membership checks. Indexing offsets as well as positions raises storage further. Phrase query cost should be measured on common-term and long-field slices.
Common Mistakes
- Assuming a document-level term intersection proves that the words form a phrase.
- Removing stopwords while collapsing the position gaps they occupied.
- Allowing a phrase to span unrelated chunks or fields.
- Treating a proximity hit as proof that the retrieved sentence supports an answer.
Validation drill
Create 71 phrase queries that include punctuation, stopwords, part numbers, negation and a passage boundary. Compare exact matches against the visible source text, then measure false joins when allowing one and three extra positions.
