Sub topic 1
Why Keyword Search Falls Short: Matching Words Versus Matching Meaning
Keyword search finds documents that contain the words you typed. Semantic search finds documents that mean what you meant. This chapter shows where the first approach breaks, why patching it only goes so far, and what the second approach has to do differently. The rest of the tutorial builds that second approach.
Prerequisites
This chapter assumes you:
- can read and write basic Python (functions, dictionaries, sets, list comprehensions)
- know the idea of keyword search: you type words, and a system returns documents containing them
- have a general idea of what a neural network does (it learns a function from examples)
You do not need any library beyond the Python standard library for this chapter. Vectors and dot products come up in the next chapters.
How keyword search works
Most keyword search engines build an inverted index. This is a map from each term to the set of documents that contain it. At query time, the engine splits the query into terms, looks each one up, and scores documents by how many terms they share with the query.
Production engines add weighting. TF-IDF and BM25 give more credit to rare terms and to repeated terms. They still rest on one operation: checking whether the same token appears on both sides.
The code below is a minimal version of that idea. It runs as written.
import re
from collections import defaultdict
docs = {
"d1": "Steps to recover access to your account",
"d2": "Our office is open from 9 to 5 on weekdays",
"d3": "Change your login credentials in the security settings",
"d4": "Reset the router to factory settings",
}
STOPWORDS = {"a", "an", "the", "to", "do", "i", "how", "is", "on",
"in", "from", "your", "our", "of", "my"}
def tokenize(text):
tokens = re.findall(r"[a-z0-9]+", text.lower())
return [t for t in tokens if t not in STOPWORDS]
index = defaultdict(set)
for doc_id, text in docs.items():
for term in tokenize(text):
index[term].add(doc_id)
def keyword_search(query):
scores = defaultdict(int)
for term in set(tokenize(query)):
for doc_id in index.get(term, ()):
scores[doc_id] += 1
return sorted(scores.items(), key=lambda kv: (-kv[1], kv[0]))
print(keyword_search("How do I reset my password?"))
print(keyword_search("recover account access"))
print(keyword_search("regain entry to my profile"))The output is:
[('d4', 1)]
[('d1', 3)]
[]The second query works because the user happened to use the document's words. The first and third queries show the problem.
Where keyword search fails
A person asking "How do I reset my password?" wants d1 and d3. Both describe changing or recovering login access. Neither contains "reset" or "password". The only hit is d4, a document about a router, because it shares the word "reset". The engine returned a wrong answer and missed both right ones.
This is not a bug in the toy code. BM25 would produce the same ranking, because the token overlap is the same. The failures fall into a few recurring patterns.
Vocabulary mismatch
Different people use different words for the same thing. "Password" and "credentials" are related. "Reset" and "recover access" describe the same action. "Profile" and "account" overlap in what they refer to. Studies of how people name things have long found that two people rarely choose the same word for the same concept, so a query and a relevant document often share no terms. This is called the vocabulary mismatch problem, and it is the main reason to move beyond keywords.
Polysemy
The reverse problem is one word with several meanings (polysemy). "Reset" in the query matched a router document. Other examples:
- "python" the language, the snake, and the comedy group
- "bank" as a financial institution or a river edge
- "cell" in biology, prison, spreadsheets, and phones
Token matching has no way to tell these senses apart. It treats the string as the unit of meaning.
Word forms and morphology
"Recover", "recovering", and "recovery" are different tokens. A query for "recovering accounts" misses a document that says "recover your account." Stemming (cutting words to a crude root) and lemmatization (mapping to a dictionary form) reduce this problem. Both are language-specific rules, and both make mistakes. A stemmer can map "universe" and "university" to the same root.
Paraphrase, order, and negation
Two sentences can share nearly all their words and differ in meaning, or share none and mean the same. "Dog bites man" and "man bites dog" have the same bag of words. "The treatment did not reduce symptoms" and "The treatment reduced symptoms" overlap heavily and say opposite things. Bag-of-words scoring discards the order that carries this information.
Languages and cross-lingual queries
A query in Spanish will not match an English document, even if the document is the perfect answer. Keyword systems need separate analyzers and separate indexes per language, and cross-language retrieval needs a translation step.
The diagram below sorts these failures by cause.
Patching keyword search
Teams have worked around these failures for decades. The common patches are:
- Stemming and lemmatization to merge word forms.
- Synonym lists such as
password = credentials = login, applied at index time or query time. - Query expansion, where the system adds related terms to the query. The terms come from a thesaurus, from query logs, or from the top results of a first pass (pseudo-relevance feedback).
- Spelling correction and fuzzy matching for typos.
Here is a synonym patch applied to the earlier example. It reuses tokenize, index, and keyword_search from above.
SYNONYMS = {
"reset": {"recover", "change"},
"password": {"credentials", "login", "access"},
}
def expand(query):
terms = set(tokenize(query))
for term in list(terms):
terms |= SYNONYMS.get(term, set())
return " ".join(terms)
print(keyword_search(expand("How do I reset my password?")))The output is now [('d1', 2), ('d3', 2), ('d4', 1)]. Both relevant documents are found, and the router document still ranks last. The patch worked for this one query.
The cost shows up as you scale it:
- Someone must write and maintain the list. A new product term or a different domain needs new entries.
- Synonymy depends on context. "Reset" is a synonym of "recover" for accounts and not for routers. A flat list cannot express this.
- Expansion lowers precision. Every added term can match unrelated documents.
- The list never covers the long tail of ways people phrase a request.
Patches reduce vocabulary mismatch for the cases someone anticipated. They do not give the system a general notion of meaning.
What matching meaning requires
To retrieve d1 for "How do I reset my password?", a system needs a representation in which the query and the document are close even though their words differ. It also needs that representation to be learned from data, so nobody has to list synonyms by hand.
Text embeddings do this. A model reads a piece of text and outputs a list of numbers (a vector). The model is trained so that texts with similar meaning get similar vectors. Search then becomes a geometric problem: embed the query, embed the documents, and return the documents whose vectors are nearest to the query's vector. The following chapters cover what these vectors are, how to compare them, and how to build the full pipeline.
Semantic search has its own weaknesses, which later chapters cover in detail: model quality depends on the domain it was trained on, and results are harder to explain than a list of matched words.
Where keyword search still wins
Keyword matching is not obsolete. It is the better tool when the exact string is the meaning:
| Query type | Example | Better fit |
|---|---|---|
| Identifiers and codes | `ERR_CONNECTION_RESET`, `SKU-48213` | Keyword |
| Rare names and jargon | A drug name, a function name | Keyword |
| Exact phrases | A quoted legal clause | Keyword |
| Natural-language questions | "how can I get back into my account" | Semantic |
| Paraphrased or vague intent | "laptop battery dies fast" | Semantic |
| Cross-language queries | A Spanish query over English documents | Semantic |
Keyword search also needs no model, is cheap to run, and is easy to debug: you can point to the matching term. Embedding models can blur exact identifiers, since two similar-looking codes may land near each other in vector space. Real systems often use both, and the hybrid search chapter shows how to merge the two result lists.
Common mistakes when diagnosing search quality
- Judging by one query. A synonym patch that fixes your test query tells you little about the rest. Collect a set of real queries with known relevant documents. The evaluation chapter shows how to score them.
- Blaming ranking when the issue is recall. If no relevant document shares a term with the query, no scoring function can surface it. Check whether the right document is retrieved at all before tuning weights.
- Adding synonyms globally. A synonym that helps one domain can hurt another. Test the effect on queries that used to work.
- Assuming semantic search replaces everything. Check your query logs. If many queries are product codes or exact names, keep keyword matching.
Exercise
A user searches your help center for "cancel subscription". The best article is titled "Ending your plan and stopping future charges" and never uses the word "cancel" or "subscription". Name the failure mode, and explain why adding a synonym entry for this one pair is an incomplete fix.
Show answer
This is vocabulary mismatch: the query and the relevant document share no tokens, so a token-overlap scorer (including BM25) gives the article a score of zero. A synonym entry fixes this pair only. Users could also write "quit my membership", "stop paying", or "close my account", and someone has to anticipate each phrasing and keep the list current. Flat lists also ignore context, and each added term can pull in unrelated documents. A learned representation of meaning handles unlisted phrasings without hand-written rules.
Exercise
Run keyword_search from this chapter on the query "settings". Which documents come back, and why does the query "setting" return nothing? Name one technique that would fix it and one risk of that technique.
Show answer
"settings" returns d3 and d4 with a score of 1 each, because the token settings appears in both. "setting" returns an empty list because the index holds the token settings, and the two strings differ. Stemming or lemmatization would map both to one root. The risk is over-merging: a crude stemmer can conflate words with different meanings, such as "universe" and "university", which adds wrong matches.