Lesson 5 of 8 · Using Embeddings
Semantic Search
Build semantic search: embed documents and queries, rank by cosine similarity and return the best matches. How it beats keyword search, plus hybrid search.
- 5 min read
- Intermediate
- Reviewed
- The steps of semantic search: index, embed the query, compare, rank
- How semantic search differs from keyword search, and where each wins
- Why search needs a minimum score
- How hybrid search and vector databases fit in
Search by meaning
It has two phases:
- Indexing (once, ahead of time): embed every document and store each vector with its text.
- Searching (for every query): embed the query with the same model, compute its similarity to every stored vector, sort, and return the top results.
Semantic search in a few lines
The program below uses the tiny see-inside model from the previous lessons (a word list standing in for a real embedding model).
import math
# A tiny, hand-made "embedding model". Each dimension is a topic.
# A real model learns thousands of dimensions from data; ours uses a word list
# so you can see exactly where the numbers come from.
TOPICS = ["travel", "food", "money", "tech", "health", "weather"]
LEXICON = {
"flight": {"travel": 1}, "flights": {"travel": 1}, "airline": {"travel": 1},
"plane": {"travel": 1}, "airport": {"travel": 1}, "trip": {"travel": 1},
"holiday": {"travel": 1}, "hotel": {"travel": 1, "money": 0.3},
"train": {"travel": 1}, "tickets": {"travel": 0.8, "money": 0.5},
"recipe": {"food": 1}, "cook": {"food": 1}, "dinner": {"food": 1},
"pasta": {"food": 1}, "rice": {"food": 1}, "curry": {"food": 1},
"vegetarian": {"food": 1, "health": 0.3}, "restaurant": {"food": 1, "travel": 0.3},
"cheap": {"money": 1}, "budget": {"money": 1}, "low-cost": {"money": 1},
"price": {"money": 1}, "save": {"money": 1}, "salary": {"money": 1},
"bank": {"money": 1}, "loan": {"money": 1}, "expensive": {"money": 1},
"laptop": {"tech": 1}, "phone": {"tech": 1}, "app": {"tech": 1},
"battery": {"tech": 1}, "wifi": {"tech": 1}, "password": {"tech": 1},
"python": {"tech": 1}, "doctor": {"health": 1}, "sleep": {"health": 1},
"exercise": {"health": 1}, "fever": {"health": 1}, "headache": {"health": 1},
"diet": {"health": 1, "food": 0.5}, "rain": {"weather": 1},
"sunny": {"weather": 1}, "forecast": {"weather": 1}, "storm": {"weather": 1},
"umbrella": {"weather": 1}, "snow": {"weather": 1, "travel": 0.2},
}
def embed(text):
vector = [0.0] * len(TOPICS)
for word in text.lower().replace(",", " ").replace(".", " ").replace("?", " ").split():
for topic, weight in LEXICON.get(word, {}).items():
vector[TOPICS.index(topic)] += weight
length = math.sqrt(sum(v * v for v in vector))
if length == 0:
return vector
return [v / length for v in vector] # unit length, so dot product = cosine
def cosine(a, b):
return sum(x * y for x, y in zip(a, b))
documents = [
"Low-cost airline tickets to Goa and Kerala",
"Budget hotel deals for your next holiday",
"An easy vegetarian curry recipe for dinner",
"How to make your laptop battery last longer",
"Storm and rain forecast for the weekend",
"When to see a doctor about a headache",
]
# Index: embed every document once, and keep the text with its vector
index = []
for text in documents:
index.append((embed(text), text))
def search(query, k=3):
q = embed(query)
scored = []
for vector, text in index:
scored.append((cosine(q, vector), text))
scored.sort(reverse=True) # highest similarity first
return scored[:k]
for query in ["cheap flights", "what should I cook tonight?"]:
print("Query:", query)
for score, text in search(query):
print(f" {score:.2f} {text}")"cheap flights" finds "Low-cost airline tickets" first, with no words in common. "what should I cook tonight?" finds the curry recipe, though neither "cook" nor "tonight" appears in it. That is what keyword search can't do.
Notice the last results: scores of 0.00, unrelated documents. Search ranks everything, so something always comes back, even when nothing is relevant.
A minimum score
Always decide what counts as "good enough". Below a threshold, show "no good match" instead of a weak result, or (in RAG) give the LLM nothing rather than something misleading. Set the threshold by looking at scores for queries with known answers, using your real model.
Keyword search still matters
| Query | Keyword search | Semantic search |
|---|---|---|
| "cheap flights" vs "low-cost airline tickets" | Misses it: no shared words | Finds it |
| "error code E-4021" | Finds the exact code | May return any article about errors |
| A product SKU, a name, a rare term | Precise | Can blur rare exact terms |
| "how do I get my money back" | Misses "refund policy" | Finds it |
Many production systems use hybrid search for exactly this reason.
Making it fast
Our code compares the query with every document. That is fine for thousands; for millions it is too slow. Vector databases and search libraries build special indexes that find the nearest vectors approximately but very quickly, by checking only a small part of the collection.
The Vector Databases course covers these in depth.
Common mistakes
Search always returns something, even when nothing is relevant. Add a minimum score so weak matches are dropped.
results = [
(0.91, "Refund policy for damaged items"),
(0.62, "How to return an order"),
(0.35, "Delivery times in winter"),
(0.05, "Our company history"),
]
threshold = 0.5
# Print only the results with a score of at least threshold, like:
# 0.91 Refund policy for damaged items
# If none pass, print: No good match found
Which query is keyword search likely to handle better than pure semantic search?
Summary
- Semantic search embeds documents once, embeds each query, and ranks documents by similarity.
- It finds matches by meaning, even without shared words.
- Search always returns something: use a minimum score.
- Keyword search wins on exact codes and names; hybrid search combines both.
- At scale, approximate nearest neighbour indexes and reranking make search fast and accurate.
Next: grouping and labelling text with embeddings.
Finished reading? Tick it off to track your progress.