Sub topic 11
Embeddings and Semantic Search
This chapter assumes you can read Python, work with lists and dictionaries, and call an HTTP API. You should also know what a prompt is and how a model turns text into text. No linear algebra beyond "a vector is a list of numbers" is needed.
What an embedding is
An embedding is a list of numbers (a vector) that represents a piece of text. An embedding model reads a string and returns a vector of fixed length, often a few hundred to a few thousand numbers. The model is trained so that texts with similar meaning get vectors that point in similar directions.
This differs from keyword search. A keyword search for "refund" misses a document that says "get my money back". Embeddings place those two phrases close together, so a search over vectors can find the document anyway. This is called semantic search.
An embedding model is not a chat model. It does not generate text. It takes text in and returns numbers. You usually call it through a separate API endpoint, and it is cheaper and faster than a text-generation call.
Measuring closeness
To compare two vectors you need a similarity measure. The most common is cosine similarity, which measures the angle between two vectors and ignores their length.
- A value near 1 means the vectors point the same way (similar meaning).
- A value near 0 means they are unrelated.
- A negative value means they point in opposite directions. This is rare for text embeddings.
Many embedding APIs return vectors already scaled to length 1. For those, cosine similarity equals the plain dot product, which is faster to compute. Check your provider's documentation before relying on this.
The following code ranks documents against a query. The vectors here have two numbers so you can run it and see the result. Real vectors are much longer.
import math
def cosine(a, b):
dot = sum(x * y for x, y in zip(a, b))
norm_a = math.sqrt(sum(x * x for x in a))
norm_b = math.sqrt(sum(y * y for y in b))
return dot / (norm_a * norm_b)
def top_k(query_vec, docs, k=2):
# docs is a list of (text, vector) pairs
ranked = sorted(docs, key=lambda d: cosine(query_vec, d[1]), reverse=True)
return [text for text, _ in ranked[:k]]
docs = [("refund policy", [1.0, 0.0]), ("shipping times", [0.0, 1.0]), ("refund steps", [0.9, 0.1])]
print(top_k([1.0, 0.0], docs))It prints ['refund policy', 'refund steps']. The query vector points along the first axis, so the two refund documents score highest.
The search pipeline
A semantic search system has two phases. The indexing phase runs once per document, or again when a document changes. The query phase runs on every search.
The key rule: the query and the documents must be embedded with the same model. Vectors from different models live in different spaces, and comparing them gives meaningless scores. Even two versions of one model are usually incompatible.
Chunking
Embedding a whole 40-page document into one vector blurs everything it says into a single average. A query about one detail will match poorly. Instead, split documents into chunks and embed each chunk.
Choices that matter:
- Chunk size. A few hundred tokens is a common starting point. Small chunks match precisely but lose surrounding context. Large chunks keep context but dilute the signal.
- Overlap. Repeating 10 to 20 percent of the previous chunk at the start of the next one prevents a sentence from being cut in half at the boundary.
- Boundaries. Split on headings, paragraphs, or sentences where possible, not at a fixed character count.
- Metadata. Store the source file, title, and position with each chunk. You need these to show citations and to filter results.
Every embedding model has a maximum input length. Text beyond it is either rejected or silently truncated, depending on the API. Count tokens before you send.
Storing and searching vectors
For a few thousand chunks, a Python list and the top_k function above are enough. A linear scan over 10,000 vectors takes milliseconds.
At larger scale, a linear scan gets slow. Vector databases and libraries use approximate nearest neighbor (ANN) indexes. These structures find vectors that are very likely, but not guaranteed, to be among the closest. You trade a small loss of recall for a large gain in speed. Options include a vector extension for a database you already run, a dedicated vector database, or a library you embed in your application.
| Scale | Reasonable approach |
|---|---|
| Under about 50,000 chunks | In-memory arrays and exact search |
| Hundreds of thousands | A vector extension in your existing database, or an ANN library |
| Millions or more | A dedicated vector database with sharding and filtering |
These thresholds are rough. Measure on your own data and hardware.
Common errors
- Mixing models. Indexing with one model and querying with another. Store the model name alongside the index and refuse to query if it differs.
- Forgetting to re-embed. You edit a document but leave the old vector in the index. Searches then return stale matches.
- Treating the score as a probability. A cosine score of 0.8 does not mean "80 percent relevant". Score ranges differ between models. Pick thresholds by testing on your own queries.
- Always returning results. Top-k returns k items even when nothing relevant exists. Apply a minimum score, or let the application say "no good match found".
- Questions versus statements. A short question and a long answer passage are phrased very differently, which can lower their similarity. Some models expect a different prefix or input type for queries and documents. Read the model's documentation.
- Exact terms. Embeddings can miss product codes, error numbers, or rare names, because these carry little general meaning. Pure semantic search will often miss an exact match that a keyword search would catch.
Hybrid search
Because of that last error, many production systems combine both approaches. They run a keyword search (such as BM25, a classic term-frequency ranking) and a vector search, then merge the two ranked lists. A simple merge method is reciprocal rank fusion, where each document scores the sum of 1 / (60 + rank) across the lists.
def reciprocal_rank_fusion(rankings, k=60):
scores = {}
for ranking in rankings:
for position, doc in enumerate(ranking, start=1):
scores[doc] = scores.get(doc, 0.0) + 1.0 / (k + position)
return sorted(scores, key=scores.get, reverse=True)
keyword = ["error E4012 guide", "refund policy", "shipping times"]
semantic = ["refund steps", "refund policy", "error E4012 guide"]
print(reciprocal_rank_fusion([keyword, semantic]))Documents that appear high in both lists rise to the top. A reranker model can then reorder the top 20 or so results more carefully, at extra cost and latency.
Uses beyond search
The same vectors support other features:
- Deduplication. Find near-identical tickets or articles by looking for very high similarity.
- Clustering. Group feedback into themes without defining the categories first.
- Recommendations. Suggest items whose vectors are close to ones a user liked.
- Classification. Compare a text to labeled examples and pick the nearest. This works as a cheap alternative to prompting when you have many labeled examples.
Embeddings also supply the retrieval step in retrieval-augmented generation, covered in the next chapters. There, the top chunks are pasted into a prompt so the model can answer from your documents.
Evaluating search quality
Build a small test set before you tune anything. Write 20 to 50 realistic queries, and for each one list the chunks that should be found. Then measure:
- Recall at k: the fraction of queries where a correct chunk appears in the top k results.
- Mean reciprocal rank: the average of 1 / rank of the first correct result.
Change one thing at a time (chunk size, model, overlap, hybrid search) and rerun the test set. Without it, you are guessing.
Exercise
Your search returns "shipping times" as a top result for the query "how do I get my money back", even though no document is relevant to that query. What two changes would you make, and why?
Show answer
First, apply a minimum similarity score so the system returns "no good match" instead of padding results up to k. Choose the threshold by testing queries that have no answer. Second, check that the knowledge base actually contains refund content, then add a test case for this query to your evaluation set so the failure is tracked. Raising k or changing the similarity measure would not fix the cause, which is that top-k always returns k items.
Exercise
You change your embedding model to a newer version and only re-embed new documents. Searches become erratic. Why, and how do you fix it?
Show answer
Vectors from different models (or versions) are in different spaces, so comparing a new query vector to old document vectors gives meaningless scores. Re-embed every document with the new model and rebuild the index. To prevent a repeat, store the model name with the index and check it at query time.