Sub topic 6
The semantic search pipeline: embed, index, query, rank
Earlier chapters covered what embeddings are, how similarity is measured, and how to generate vectors with a pretrained model. This chapter connects those pieces into one working system. It assumes you can read basic Python and NumPy, know what a dot product and a vector norm are, and have seen SentenceTransformer.encode. It does not cover approximate indexes, chunking, or reranking. Those are later stages that plug into the structure described here.
Two phases: offline and online
A semantic search system has two phases that run at different times.
- Offline (indexing) phase. Runs once, then again whenever documents change. It turns every document into a vector and stores the vectors.
- Online (query) phase. Runs on every search. It turns the query into a vector, compares it to the stored vectors, and returns the best matches.
The split matters because embedding is the expensive step. Encoding a document can take milliseconds to seconds, depending on model and hardware. Comparing a query vector to stored vectors is cheap by comparison. You pay the embedding cost for documents once, ahead of time, and only the single query at search time.
The four stages
The pipeline name lists the stages: embed, index, query, rank.
- Embed. Pass each document through the embedding model to get a fixed-size vector. All vectors from one model have the same dimension (384 for
all-MiniLM-L6-v2). - Index. Store the vectors in a structure you can search, along with a way to map each vector back to its document. At small scale this is a NumPy matrix where row
ibelongs to documenti. - Query. Embed the user's text with the same model and the same settings used for the documents.
- Rank. Score the query vector against every document vector, sort by score, and keep the top
k.
The first two stages are offline. The last two are online.
A complete minimal implementation
The class below packages the four stages. It keeps vectors in a matrix, which is the exact search approach covered in detail in the next chapter.
import numpy as np
from sentence_transformers import SentenceTransformer
class SemanticIndex:
def __init__(self, model_name="all-MiniLM-L6-v2"):
self.model_name = model_name
self.model = SentenceTransformer(model_name)
self.docs = []
self.matrix = None # shape (n_docs, dim), unit-length rows
def add(self, docs):
"""Embed documents and append them to the index."""
new = self.model.encode(docs, normalize_embeddings=True)
self.docs.extend(docs)
if self.matrix is None:
self.matrix = new
else:
self.matrix = np.vstack([self.matrix, new])
def search(self, query, k=3, min_score=None):
"""Return up to k (document, score) pairs, best first."""
if self.matrix is None:
return []
q = self.model.encode(query, normalize_embeddings=True)
scores = self.matrix @ q # cosine similarity for unit vectors
order = np.argsort(-scores)[:k] # slicing handles k > n_docs safely
results = [(self.docs[i], float(scores[i])) for i in order]
if min_score is not None:
results = [r for r in results if r[1] >= min_score]
return results
index = SemanticIndex()
index.add([
"Steps to recover access to your account",
"Our office is open from 9 to 5 on weekdays",
"Change your login credentials in the security settings",
"The cafeteria serves lunch at noon",
])
for text, score in index.search("How do I reset my password?", k=2):
print(f"{score:.3f} {text}")The two account-related documents should rank above the office hours and cafeteria documents. Exact scores depend on the model version, so do not hard-code them in tests. Test the order instead.
Why each design choice matters
Normalize once, at indexing time
With normalize_embeddings=True, every vector has length 1. For unit vectors, the dot product equals cosine similarity, so matrix @ q scores every document in one operation. If you skip normalization and still use a dot product, longer vectors get higher scores for reasons unrelated to meaning. Normalize the documents and the query the same way.
Use the same model for both sides
Vectors from different models live in different spaces. Even two models that both output 384 dimensions assign unrelated meanings to each coordinate. Comparing a query from model B to documents from model A runs without error and returns plausible-looking numbers that are meaningless. This is the most common silent failure in search systems.
The class stores model_name for this reason. When you persist an index, save the name with it and check it on load:
import numpy as np
def save_index(index, path):
np.savez(
path,
matrix=index.matrix,
docs=np.array(index.docs, dtype=object),
model_name=np.array(index.model_name),
)
def load_index(path):
data = np.load(path, allow_pickle=True)
index = SemanticIndex(str(data["model_name"]))
index.matrix = data["matrix"]
index.docs = list(data["docs"])
return indexLoading with allow_pickle=True can execute code from a malicious file. Only load files you created yourself. For anything shared between systems, store the texts as JSON and the vectors as a plain float array.
Keep the row-to-document mapping consistent
The matrix has no labels. Row i is only meaningful because self.docs[i] was added in the same call. Bugs appear when documents are deleted from one list but not the other, or when the two are sorted separately. In real systems, store a stable document ID next to each vector and return IDs from search, then look up the text in your database.
Ranking details and edge cases
Scores are relative, not absolute
A cosine score of 0.55 does not mean "55% relevant." Score ranges depend on the model, the language, and the length of the texts. A score that signals a strong match with one model can signal a weak match with another. The ranking, not the number, is the reliable output.
Top-k always returns k items, even when nothing in the collection is relevant. Searching a cooking corpus for "tax filing deadlines" still returns the three least-bad recipes. Options for handling this:
- Set a minimum score (
min_scoreabove), tuned on queries you have labeled for your own model and data. - Compare the top score to the gap between the first and second results.
- Return fewer results and let a downstream stage, such as reranking, decide.
A fixed threshold is brittle. Pick it from a labeled sample, and recheck it whenever you change models.
Ties and ordering
Equal scores are common with duplicate documents. np.argsort is not guaranteed stable with its default algorithm, so tied documents can come back in different orders. If you need deterministic output, use np.argsort(-scores, kind="stable"), which breaks ties by original row order.
Empty and tiny collections
With zero documents, search returns an empty list because the matrix is None. With fewer than k documents, slicing returns all of them without error. Both cases are worth a unit test.
Batching
model.encode accepts a list and processes it in batches, which is much faster than calling it once per document. Pass the whole list, and adjust batch_size if you run out of memory. For the single query, pass a string, which returns a 1-D vector. If you pass a list of one string you get a 2-D array of shape (1, dim), and matrix @ q then fails with a shape error.
Growing indexes
np.vstack copies the whole matrix on every add, so adding documents one at a time is slow. Collect new documents and add them in batches. For millions of vectors, a matrix in memory stops being practical and you move to a vector library or database.
Cost at a glance
| Stage | When it runs | Cost grows with |
|---|---|---|
| Embed documents | Offline, on change | Number and length of documents |
| Store vectors | Offline | Documents × dimension × 4 bytes (float32) |
| Embed query | Every search | Query length (one short text) |
| Score and rank | Every search | Documents × dimension |
As a memory check, 100,000 documents at 384 dimensions in float32 take about 100,000 × 384 × 4 bytes, roughly 154 MB. The scoring step reads all of that on every query. This is why exact search is fine at this size and why approximate indexes become interesting at tens of millions.
Debugging a poor result
When a query returns bad matches, check the pipeline in order:
- Confirm the query and documents used the same model and the same
normalize_embeddingssetting. - Print the scores of the top 10 results. A flat list of nearly equal scores suggests the query is outside the model's domain.
- Read the top documents. If the right document is not in the collection, or was cut off by a length limit, no ranking change will help.
- Check that row
istill matchesdocs[i]. - Only then consider a different model, better chunking, hybrid search, or reranking.
Most problems are found in steps 1 to 4.
Exercise
You built an index with all-MiniLM-L6-v2. A teammate changes the query code to use a different model that also outputs 384-dimensional vectors, and leaves the index unchanged. No error appears. Why is this a bug, and how would you prevent it?
Show answer
Each model defines its own vector space, so a coordinate in one model has no relationship to the same coordinate in another. The matrix product still runs because the shapes match, but the scores are meaningless and the ranking is effectively noise. To prevent it, store the model name with the saved index, check it when loading and when constructing the query encoder, and rebuild the index whenever the model changes.
Exercise
A search for "tax filing deadlines" over a corpus of cooking recipes returns three results with cosine scores around 0.15 to 0.20. What does this show about top-k search, and what are two ways to handle it?
Show answer
Top-k always returns k items, even when nothing is relevant, so it ranks the least-bad documents instead of reporting that nothing matches. Two ways to handle it: apply a minimum score threshold tuned on labeled queries for your model and data, or pass the results to a later stage such as a reranker that can reject weak candidates.
Exercise
Why does matrix @ q give cosine similarity in the SemanticIndex class, and what would break if you indexed with normalize_embeddings=True but encoded queries without it?
Show answer
Cosine similarity is the dot product divided by the product of the vector lengths. When all vectors have length 1, the division changes nothing, so the dot product alone is the cosine. If the query is not normalized, its length scales every score by the same factor, so the ranking stays the same, but the score values are no longer cosines. Any fixed threshold would then behave inconsistently. Normalizing both sides keeps scores comparable.