Lesson 4.3 · 3 of 10 · 4 min read · Reviewed 24 Nov 2026
Keyword search vs semantic search
By the end, you can
- Compare keyword search and semantic search.
- Know when to combine them.
Side by side
| Keyword (for example BM25) | Semantic (embeddings) | |
|---|---|---|
| Matches | Words and their frequency | Meaning |
| Paraphrases | Weak | Strong |
| Exact ids, codes, names | Strong | Weak |
| Needs a model | No | Yes, an embedding model |
| Explaining a match | Easy: shared words | Harder: “the vectors were close” |
| New jargon | Works if the word appears | Depends on the model knowing it |
Examples
| Query | Better method |
|---|---|
| “ERR-4012” | Keyword |
| “my screen goes black when I close the lid” | Semantic |
| “invoice INV-20931 from Okafor Ltd” | Keyword (ids, names) plus semantic |
| “how do I take time off” when docs say “annual leave” | Semantic |
Combining them
Hybrid search runs both and merges the rankings, often with reciprocal rank fusion (23.2). It’s the usual default for RAGRetrieval-augmented generation (RAG): Retrieving relevant documents at request time and adding them to the prompt so the answer is grounded in them. systems because real queries mix exact terms with natural language.
Key points
- Keyword search matches words: great for exact terms, ids and names.
- Semantic search matches meaning: great for paraphrases and natural questions.
- Most production systems combine both (hybrid search).
Race keyword search against semantic search
See which queries keyword search wins, which semantic search wins, and how a hybrid merge gets both.
You will have: A script that runs four queries through keyword, semantic and hybrid (reciprocal rank fusion) search and prints the top hit of each.
Steps
- Run the starter: keyword search works, semantic search returns nothing yet.
- Fill in semantic(): rank documents by cosine of toy embeddings.
- Fill in rrf(): merge the two rankings with score 1 / (60 + rank).
- Compare the top hits: the error code query should favour keyword, the paraphrase should favour semantic.
- Check that hybrid gets the right top hit for all four queries.
Done when
- Keyword finds ERR-4012; semantic finds the 'device fails to start' article for 'laptop won't power on'.
- Hybrid's top hit is correct for all 4 queries.
- Output prints 'hybrid correct: 4/4'.
Open in the Playground No API key needed.
Starter code (Python)
import math
# Toy embedding: 5 named dimensions. Real models learn hundreds you can't name.
DIMS = ["account", "billing", "shipping", "device", "pets"]
WORDS = {
"password": [1, 0, 0, 0, 0], "login": [1, 0, 0, 0, 0], "locked": [0.8, 0, 0, 0, 0], "code": [0.6, 0, 0, 0.2, 0],
"charged": [0, 1, 0, 0, 0], "invoice": [0, 1, 0, 0, 0], "refund": [0, 0.8, 0.3, 0, 0], "twice": [0, 0.4, 0, 0, 0],
"parcel": [0, 0, 1, 0, 0], "delivery": [0, 0, 1, 0, 0], "late": [0, 0, 0.6, 0, 0], "courier": [0, 0, 0.9, 0, 0],
"laptop": [0, 0, 0, 1, 0], "screen": [0, 0, 0, 0.9, 0], "battery": [0, 0, 0, 0.9, 0], "power": [0, 0, 0, 0.7, 0],
"cat": [0, 0, 0, 0, 1], "kitten": [0, 0, 0, 0, 1], "nap": [0, 0, 0, 0, 0.6], "sleeps": [0, 0, 0, 0, 0.6],
}
DOCS = {
"kb-1": "ERR-4012 means the card was declined",
"kb-2": "device fails to start: hold the power button",
"kb-3": "reset your password from the login page",
"kb-4": "track a late parcel with the courier",
}
QUERIES = {"ERR-4012": "kb-1", "laptop won't power on": "kb-2", "locked out, forgot login code": "kb-3", "delivery is late": "kb-4"}
def words(t):
return set(t.lower().replace(":", " ").replace(",", " ").split())
def keyword(q):
return sorted(DOCS, key=lambda d: (-len(words(q) & words(DOCS[d])), d))
def embed(t):
v = [0.0] * len(DIMS)
for w in words(t):
for i, x in enumerate(WORDS.get(w, [0] * len(DIMS))):
v[i] += x
return v
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
la, lb = math.sqrt(sum(x * x for x in a)), math.sqrt(sum(x * x for x in b))
return dot / (la * lb) if la and lb else 0.0
def semantic(q):
return [] # TODO: sort DOCS ids by cosine(embed(q), embed(text)), highest first, ties by id
def rrf(*rankings, k=60):
return [] # TODO: score each doc id with sum of 1 / (k + rank), rank starting at 1; return ids best first
for q, want in QUERIES.items():
print(q, "| keyword:", keyword(q)[:1], "| semantic:", semantic(q)[:1], "| hybrid:", rrf(keyword(q), semantic(q))[:1])
Show a solution
import math
# Toy embedding: 5 named dimensions. Real models learn hundreds you can't name.
DIMS = ["account", "billing", "shipping", "device", "pets"]
WORDS = {
"password": [1, 0, 0, 0, 0], "login": [1, 0, 0, 0, 0], "locked": [0.8, 0, 0, 0, 0], "code": [0.6, 0, 0, 0.2, 0],
"charged": [0, 1, 0, 0, 0], "invoice": [0, 1, 0, 0, 0], "refund": [0, 0.8, 0.3, 0, 0], "twice": [0, 0.4, 0, 0, 0],
"parcel": [0, 0, 1, 0, 0], "delivery": [0, 0, 1, 0, 0], "late": [0, 0, 0.6, 0, 0], "courier": [0, 0, 0.9, 0, 0],
"laptop": [0, 0, 0, 1, 0], "screen": [0, 0, 0, 0.9, 0], "battery": [0, 0, 0, 0.9, 0], "power": [0, 0, 0, 0.7, 0],
"cat": [0, 0, 0, 0, 1], "kitten": [0, 0, 0, 0, 1], "nap": [0, 0, 0, 0, 0.6], "sleeps": [0, 0, 0, 0, 0.6],
}
DOCS = {
"kb-1": "ERR-4012 means the card was declined",
"kb-2": "device fails to start: hold the power button",
"kb-3": "reset your password from the login page",
"kb-4": "track a late parcel with the courier",
}
QUERIES = {"ERR-4012": "kb-1", "laptop won't power on": "kb-2", "locked out, forgot login code": "kb-3", "delivery is late": "kb-4"}
def words(t):
return set(t.lower().replace(":", " ").replace(",", " ").split())
def keyword(q):
return sorted(DOCS, key=lambda d: (-len(words(q) & words(DOCS[d])), d))
def embed(t):
v = [0.0] * len(DIMS)
for w in words(t):
for i, x in enumerate(WORDS.get(w, [0] * len(DIMS))):
v[i] += x
return v
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
la, lb = math.sqrt(sum(x * x for x in a)), math.sqrt(sum(x * x for x in b))
return dot / (la * lb) if la and lb else 0.0
def semantic(q):
qv = embed(q)
return sorted(DOCS, key=lambda d: (-cosine(qv, embed(DOCS[d])), d))
def rrf(*rankings, k=60):
score = {}
for ranking in rankings:
for rank, d in enumerate(ranking, start=1):
score[d] = score.get(d, 0) + 1 / (k + rank)
return sorted(score, key=lambda d: (-score[d], d))
right = 0
for q, want in QUERIES.items():
kw, se, hy = keyword(q)[0], semantic(q)[0], rrf(keyword(q), semantic(q))[0]
right += hy == want
print(f"{q:32} keyword={kw} semantic={se} hybrid={hy} want={want}")
print(f"hybrid correct: {right}/{len(QUERIES)}")