Sub topic 7
Lexical Retrieval: Matching the Words
This chapter assumes you know what retrieval-augmented generation is, and that a system may split one prompt into several sub-queries (query fan-out). You don't need to program. The short code sketches are there to make the ideas concrete.
What lexical retrieval is
Lexical retrieval finds documents by matching the words in a query against the words in a document. It does not try to understand meaning. If the query contains "stability" and a passage contains "stability", that is a match. If the passage says "pronation support" and never uses the word "stability", a purely lexical system sees no link.
This is the oldest family of search methods, and it is still widely used. Classic search engines relied heavily on it. Many AI search pipelines are described as using it alongside other methods, which a later chapter covers under hybrid retrieval. Outsiders cannot see which method any given product uses for a given query, so treat the details below as the general technique and not as a description of one system.
The working model
A lexical system does most of its work before any query arrives. It builds an inverted index, a lookup table that maps each term to the list of documents or passages that contain it. When a query comes in, the system looks up each query term and combines the lists.
The preparation steps matter because they decide what counts as "the same word":
- Tokenising splits text into units, usually words.
- Lowercasing makes "Shoes" and "shoes" match.
- Stemming or lemmatising reduces word forms to a common root, so "running" and "runs" can match "run". Stemming is a crude chop. Lemmatising uses a dictionary.
- Stop-word removal drops very common words such as "the" and "for". Many modern systems keep them, because they matter in phrases.
Notice what is missing. Nothing in this pipeline knows that "sneakers" and "trainers" can mean the same thing as "shoes".
How matches are scored: TF-IDF and BM25
Finding every passage that contains a query term is easy. Ranking them is the harder part. The classic idea has two parts.
- Term frequency (TF): a passage that uses a query term more often is more likely to be about it.
- Inverse document frequency (IDF): a term that appears in few documents is more informative than one that appears in most. "Overpronation" tells you more than "best".
BM25 is the best-known scoring function built on these ideas. It is a published, well-documented formula and a common baseline in search tools. It adds two refinements:
- Saturation. Repeating a term helps less and less. The tenth mention adds far less than the second.
- Length normalisation. A long passage naturally contains more words, so BM25 adjusts for length. A short passage that is densely on topic is not penalised against a long one.
The sketch below shows the core idea in a simplified form. It uses the standard BM25 formula with common default parameters, applied to a tiny collection.
import math
from collections import Counter
def bm25_scores(query, passages, k1=1.5, b=0.75):
"""Score each passage against a query with a simple BM25."""
tokenised = [p.lower().split() for p in passages]
n = len(tokenised)
avg_len = sum(len(t) for t in tokenised) / n
doc_freq = Counter()
for tokens in tokenised:
for term in set(tokens):
doc_freq[term] += 1
scores = []
for tokens in tokenised:
counts = Counter(tokens)
score = 0.0
for term in query.lower().split():
if term not in counts:
continue
idf = math.log(1 + (n - doc_freq[term] + 0.5) / (doc_freq[term] + 0.5))
tf = counts[term]
norm = tf + k1 * (1 - b + b * len(tokens) / avg_len)
score += idf * tf * (k1 + 1) / norm
scores.append(round(score, 3))
return scores
passages = [
"Stability shoes add support for overpronation.",
"Our best running shoes are comfortable and light.",
"Shoes shoes shoes shoes shoes shoes.",
]
print(bm25_scores("stability shoes overpronation", passages))Run it and compare the third passage with the first. The third repeats "shoes" six times but never mentions the rarer, more informative terms. It scores well below the first passage, because saturation limits the gain from repetition and IDF weights "shoes" lightly.
What lexical retrieval rewards in content
These points follow from how the method works. They are properties of the technique, not confirmed facts about any AI product.
- Exact terms count. If people search for "motion control shoes", a passage that uses that phrase can match. A passage that only says "shoes that limit foot rolling" may not, at least in a lexical pass.
- Rare, specific terms carry weight. Product names, model numbers, standards, error codes, ingredient names and technical terms are strong lexical signals, because few documents contain them.
- Repeating a keyword yields little. Saturation means stuffing a term gains almost nothing. It can also make the text worse for people and for other retrieval methods.
- Vocabulary variants matter. Cover the terms your audience actually uses, including common synonyms and abbreviations, in natural wording.
- Short, focused passages can score well. Length normalisation favours a tight passage over a rambling one with the same terms.
Where lexical retrieval is strong and weak
| Situation | Lexical retrieval | Why |
|---|---|---|
| Query is a model number or error code | Strong | Exact rare tokens match directly |
| Query uses a brand or product name | Strong | Names are rare and distinctive |
| Query is a loose, conversational question | Weak | Few exact words overlap with good answers |
| Document uses different words for the same idea | Weak | No notion of synonyms without extra help |
| Query needs a specific phrase | Moderate | Depends on whether the system indexes word order |
| Typos in the query | Weak | A misspelled term matches nothing unless corrected |
Fan-out makes lexical matching more useful
Fan-out changes how well lexical retrieval works. A long conversational prompt is a poor lexical query. Sub-queries are often shorter and more specific, such as "stability vs motion control shoes overpronation" or "running shoes flat feet under 100 dollars". Short keyword-like queries are what lexical methods handle best. So the sub-queries a system writes may be partly shaped to suit keyword matching, although this is an inference. It is not something outsiders can confirm for a particular product.
Common errors
- Assuming lexical means outdated. Lexical retrieval is often kept alongside newer methods because it is precise on rare terms and cheap to run. Do not dismiss it.
- Assuming it is only keyword stuffing. BM25 penalises repetition. Coverage of distinct, relevant terms beats repetition of one.
- Assuming a match means a citation. A passage found by lexical retrieval is only a candidate. It still has to survive merging, reranking and answer writing, which later chapters cover.
- Assuming one system's behaviour applies to all. Tokenisation, stemming, scoring and index design vary between systems and are mostly not disclosed.
- Ignoring the page's visible text. Retrieval matches the words a system can extract. Text that exists only inside images or loads in ways a crawler may not process may not reach the index. Which crawlers handle which content differs by system.
Practical takeaways for planning content
- List the exact terms, names and identifiers a searcher would use for your topic, and check that your page uses them in plain, natural sentences.
- Include the variant wordings your audience uses, such as abbreviations and common alternatives, where they are accurate.
- Put specific, rare details (models, standards, measurements) in the passage that answers the related question, not only in a table elsewhere on the page.
- Keep passages focused, so the key terms appear close together and are not diluted by unrelated text.
- Do not repeat a keyword for its own sake. The gain is small and the cost in readability is real.
The next chapter looks at semantic retrieval, which handles the synonym and paraphrase gaps that lexical matching leaves open.
Exercise
A page about running shoes repeats the phrase "best running shoes" 40 times but never mentions "overpronation" or "stability". A competitor's page mentions both terms once each, in clear sentences. For a sub-query "stability shoes overpronation", which page would a BM25-style lexical scorer likely rank higher, and which two BM25 ideas explain it?
Show answer
The competitor's page would likely rank higher. Saturation means the 40 repetitions add little after the first few mentions. Inverse document frequency gives more weight to rare, informative terms like "overpronation" and "stability" than to common ones like "best". The first page also does not contain the query terms at all, so it earns no score for them.
Exercise
Name two kinds of query where lexical retrieval is usually strong and one where it is usually weak. Give a reason for each.
Show answer
Strong: a model number or error code (rare exact tokens match directly), and a brand or product name (distinctive and rare, so IDF weights it heavily). Weak: a loose conversational question or a query where the document uses synonyms, because few exact words overlap and lexical matching has no sense of meaning.