AI-Powered Search Systems
Keyword matching finds words. Semantic retrieval finds meaning â and knows when the two disagree.
RetrievalPrerequisites
- !TF-IDF and BM25 relevance scoring
- !Vector similarity and cosine distance
- !How embeddings map text into a shared space
What You'll Learn
- 1Explain the failure cases that separate lexical from semantic matching
- 2Chunk and embed a corpus so retrieval quality survives contact with real documents
- 3Blend sparse and dense scores with a tunable weighting
- 4Evaluate retrieval with ranking metrics instead of vibes
Where exact matching stops being enough
Search that scores documents by term overlap works remarkably well until the query and the document use different words for the same idea. Someone searching for "how do I reset my password" gets nothing from a help article titled "credential recovery", even though the article is exactly right. No amount of stemming fixes a vocabulary mismatch, because the problem is synonymy, not morphology.
The mirror failure is just as common. A query for "apple price target" should not rank a recipe for apple pie first, yet a bag-of-words scorer sees a rare, distinctive term and happily obliges. Polysemy punishes lexical systems in the opposite direction from synonymy, and the two problems are two faces of the same limitation: words are treated as symbols rather than meanings.
Neural retrieval addresses both by mapping queries and documents into the same vector space, where a password-reset request and a credential-recovery article land close together regardless of shared tokens. The cost is that dense models are worse at the things lexical matching handles for free â exact identifiers, product codes, error strings and rare proper nouns. That tension is why production systems increasingly run both and combine the results.
The pipeline, stage by stage
An AI search system is a chain, and each stage has a quality budget the next stage cannot recover from. Documents are split into chunks that are self-contained enough to answer a question on their own. Each chunk is embedded into a fixed-length vector by a sentence encoder. Those vectors go into an index built for approximate nearest neighbor lookup, because exact scan over millions of vectors is far too slow for an interactive box.
At query time the incoming text is embedded with the same model, the index returns the closest candidates in milliseconds, and a re-ranker rescores the top few dozen with a heavier cross-encoder before anything is shown. Recall is decided early and precision late: if the right chunk never entered the candidate set, no re-ranker can invent it.
Chunking deserves more attention than it usually gets. Fixed 512-token windows cut tables in half and separate a heading from the paragraph it introduces, producing fragments that embed poorly and retrieve worse. Overlapping chunks by ten to twenty percent, splitting on structural boundaries first and falling back to token counts, and attaching the section title to every chunk's text consistently all improve retrieval measurably without touching the model.
Building a semantic index
The indexing code is short, which misleads people into thinking the problem is solved. The interesting decisions are which model to encode with, whether metadata filters apply before or after the vector search, and what distance metric the index uses.
import chromadb
from sentence_transformers import SentenceTransformer
class SemanticIndex:
"""Small but complete dense retrieval index."""
def __init__(self, model_name="all-MiniLM-L6-v2"):
self.encoder = SentenceTransformer(model_name)
client = chromadb.EphemeralClient()
self.store = client.get_or_create_collection(
name="docs",
metadata={"hnsw:space": "cosine"},
)
def index(self, chunks):
embeddings = self.encoder.encode(
[c["text"] for c in chunks], show_progress_bar=False
).tolist()
self.store.add(
ids=[c["id"] for c in chunks],
documents=[c["text"] for c in chunks],
embeddings=embeddings,
metadatas=[c.get("meta", {}) for c in chunks],
)
def search(self, query, k=8, where=None):
vec = self.encoder.encode([query]).tolist()
hits = self.store.query(
query_embeddings=vec,
n_results=k,
where=where,
include=["documents", "metadatas", "distances"],
)
return [
{"text": doc, "score": 1 - dist, "meta": meta}
for doc, dist, meta in zip(
hits["documents"][0], hits["distances"][0], hits["metadatas"][0]
)
]
Cosine distance is the right default for normalized embeddings, but confirm your encoder's recommended metric â some models are trained with dot product or Manhattan distance, and mismatching it silently scrambles the ranking.
Sparse, dense, and blending them
Sparse retrieval scores by term statistics; dense retrieval scores by geometric proximity. Their blind spots are complementary, so a weighted combination recovers precision that neither achieves alone. Normalize both score vectors first, otherwise whichever produces larger raw numbers dominates the blend regardless of its actual quality.
import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
class HybridRetriever:
def __init__(self, alpha=0.5, model_name="all-MiniLM-L6-v2"):
self.alpha = alpha # weight on dense score
self.encoder = SentenceTransformer(model_name)
self.bm25 = None
self.dense = None
self.texts = []
def fit(self, texts):
self.texts = texts
self.bm25 = BM25Okapi([t.lower().split() for t in texts])
self.dense = self.encoder.encode(texts, normalize_embeddings=True)
def search(self, query, k=10):
sparse = self.bm25.get_scores(query.lower().split())
qvec = self.encoder.encode([query], normalize_embeddings=True)[0]
dense = self.dense @ qvec
s_norm = sparse / (sparse.max() + 1e-9)
d_norm = (dense - dense.min()) / (dense.max() - dense.min() + 1e-9)
fused = self.alpha * d_norm + (1 - self.alpha) * s_norm
top = np.argsort(fused)[::-1][:k]
return [{"text": self.texts[i], "score": float(fused[i])} for i in top]
Set alpha by validation rather than intuition. On identifier-heavy corpora the sparse term should dominate; on conversational, paraphrase-heavy queries the dense term usually should. Weighted score fusion is the simplest of the available strategies â reciprocal rank fusion is more robust when the two scorers produce incomparable score distributions, and it needs no normalization at all.
Re-ranking is the cheapest precision win
Retrieval optimizes recall under a latency ceiling, so it must be cheap and therefore approximate. Re-ranking flips the trade: take the fifty or so candidates a fast retriever produced, then score each query-document pair jointly with a cross-encoder that reads them together rather than encoding them independently. Cross-encoders see exactly how the query and passage interact, which makes them dramatically more accurate â and far too slow to run over an entire corpus.
from sentence_transformers import CrossEncoder
class TwoStageSearch:
def __init__(self, retriever, top_n=50, top_k=8):
self.retriever = retriever
self.reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L-6-v2")
self.top_n = top_n
self.top_k = top_k
def search(self, query):
candidates = self.retriever.search(query, k=self.top_n)
pairs = [(query, c["text"]) for c in candidates]
scores = self.reranker.predict(pairs)
ranked = sorted(
zip(candidates, scores), key=lambda x: x[1], reverse=True
)
return [
{"text": c["text"], "score": float(s)}
for c, s in ranked[: self.top_k]
]
The latency arithmetic is what makes this attractive. Encoding fifty short passages with a small cross-encoder costs a few milliseconds on a GPU, while the recall gained â typically the largest single jump available in the whole pipeline â is the difference between a search that surfaces the right answer in the top three and one that buries it at position twenty.
Choosing pieces for your corpus
Different corpora reward different configurations. The table below maps common situations to the choices that tend to work, before any tuning.
| Corpus characteristic | Primary retriever | Chunking | Re-rank |
|---|---|---|---|
| Product SKUs and codes | Sparse or hybrid, low alpha | Short, keep identifiers intact | Yes |
| Support FAQs and chat logs | Dense | Medium, overlap 15% | Yes |
| Long legal or policy docs | Hybrid | Structural sections with titles | Yes, with metadata |
| Code documentation | Hybrid plus path filters | Per function or heading | Optional |
| Multilingual queries | Multilingual dense model | Medium | Yes |
Index choice matters less than people expect at the ten-million-vector scale, and more at the billion scale. Below a few million vectors, brute force with a good encoder often beats a poorly tuned approximate index; beyond it, product quantization and hierarchical navigable small world graphs become necessary to keep memory and latency under control.
Measuring whether search got better
You cannot improve what you have not measured, and search quality is unusually easy to fake with anecdotes. Build a labeled set of query-document pairs â even two hundred hand-judged queries transform decision-making â and track ranking metrics on every change.
import numpy as np
def ndcg_at_k(relevance, k=10):
"""Normalized discounted cumulative gain for one ranked list."""
gains = [rel / np.log2(i + 2) for i, rel in enumerate(relevance[:k])]
ideal = sorted(relevance, reverse=True)[:k]
ideal_gains = [rel / np.log2(i + 2) for i, rel in enumerate(ideal)]
idcg = sum(ideal_gains)
return sum(gains) / idcg if idcg > 0 else 0.0
def hit_rate_at_k(ranked, relevant, k=10):
return 1.0 if any(r in relevant for r in ranked[:k]) else 0.0
def evaluate(queries, retriever, k=10):
scores = []
for q in queries:
ranked = [h["text"] for h in retriever.search(q["query"], k=k)]
scores.append(ndcg_at_k([1.0 if r in q["relevant"] else 0.0 for r in ranked], k))
return float(np.mean(scores))
Report multiple metrics together. Precision at five tells you what users see, recall at fifty tells you whether the candidate pool was viable at all, and normalized discounted cumulative gain captures ordering quality. When a change raises one while lowering another, you have found a real trade-off rather than a noise-driven win â and that is the point at which the labeled set has earned its keep.
đĄLog what users click
Impression and click logs become relabeled training data for the re-ranker. Queries that return ten results and get zero clicks are free labels telling you the current ranking is wrong.
Common Mistakes
Indexing fixed-size chunks that split tables and headings from their content
Fix: Split on structural boundaries first, overlap adjacent chunks, and prepend the section title to each chunk's embedding text.
Fusing raw BM25 and cosine scores without normalization
Fix: Normalize both score vectors or use reciprocal rank fusion, otherwise the numerically larger scorer always wins.
Judging a new retrieval setup on three hand-picked queries
Fix: Keep a frozen labeled set of a few hundred queries and compare ranking metrics across every change.
Best Practices
- Run hybrid retrieval by default and tune the blend weight on validation data
- Add a cross-encoder re-ranker before anything reaches the user â it is the biggest cheap win
- Store metadata at index time so filters can run before vector search
- Track precision, recall and NDCG together rather than a single headline number
- Refresh embeddings whenever the underlying documents change materially
Key Takeaways
- Lexical and dense retrieval fail in opposite ways, which is why hybrid systems dominate
- Chunking quality caps recall no matter how good the encoder is
- Normalize before score fusion or let reciprocal rank fusion avoid the problem entirely
- Two-stage search puts cheap recall first and expensive precision second
- Frozen labeled sets turn search tuning from opinion into measurement