Sub topic 6
The semantic search pipeline: embed, index, query, rank
This chapter assumes you know basic Python, what a dot product and a vector length are, and that a pretrained model can turn text into a fixed-size vector. You have already seen how to generate embeddings and how cosine similarity works. Here you put those pieces together into a working search.
The four stages
Every semantic search system has the same shape, whether it holds four documents or four hundred million. Work happens at two different times.
- Offline (once, or when documents change): embed each document and store the vectors. The stored collection is the index.
- Online (for every query): embed the query with the same model, score it against the stored vectors, and return the best matches.
Splitting the work this way matters for cost. Embedding documents is the slow part, so you do it once. A query needs only one embedding call and one comparison pass.
A complete example
The code below runs all four stages on four short documents. The index here is just a matrix with one row per document.
import numpy as np
from sentence_transformers import SentenceTransformer
model = SentenceTransformer("all-MiniLM-L6-v2")
docs = [
"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",
]
# Offline: embed and index.
doc_emb = model.encode(docs, normalize_embeddings=True)
def search(query, k=2):
# Online: embed the query, score, rank.
q = model.encode(query, normalize_embeddings=True)
scores = doc_emb @ q # cosine similarity, since vectors are unit length
top = np.argsort(-scores)[:k] # indices of the k highest scores
return [(docs[i], float(scores[i])) for i in top]
for text, score in search("How do I reset my password?"):
print(f"{score:.3f} {text}")The query shares no words with the two account-related documents, yet they should rank first. The scores are cosine similarities, so higher means closer in meaning.
What each line does
encode(docs, ...)returns an array of shape(4, 384): one 384-dimension vector per document.normalize_embeddings=Truescales every vector to length 1. For unit vectors, the dot product equals cosine similarity.doc_emb @ qmultiplies a(4, 384)matrix by a(384,)vector. The result has one score per document.np.argsort(-scores)sorts indices from highest score to lowest. Negating the scores turns an ascending sort into a descending one.[:k]keeps the first k indices.
The function returns the text and its score together, so you can see how confident the ranking is.
Common errors
- Using a different model for the query. Vectors from two models live in different spaces, and comparing them gives meaningless scores. Query and documents must use the same model.
- Forgetting to normalize on one side. If documents are normalized and the query is not, the ranking is still correct for a single query. Scores from different queries are then not comparable. Normalize both.
- Re-embedding documents on every query. Keep
doc_embin memory or on disk. Rebuild it only when documents change. - Losing the mapping from row to document. Row
iof the matrix must correspond todocs[i]. If you add, delete, or reorder documents, rebuild the matrix and the list together.
Where this design runs out
Scoring against every row is exact, and it is fast for thousands of documents. As the collection grows into millions, the full pass per query becomes too slow. Later chapters cover chunking long documents and approximate indexes that trade a little accuracy for speed. The four stages stay the same.
Exercise
In the pipeline above, which steps run once per document set and which run once per query? What goes wrong if the query is embedded with a different model than the documents?
Show answer
Embedding the documents and building the index run once, offline, and again only when the documents change. Embedding the query, scoring, and ranking run for every query. A different query model produces vectors in a different space from the document vectors, so the dot products have no meaning and the ranking is essentially arbitrary.