Chapter 2
Embeddings and vector search
How a computer can tell that "what did he do with maps?" and "geospatial vector tiling pipeline" are about the same thing, even though they share no words.
The problem with words
Classic search matches words. Ask "what did he do with maps?" and a keyword engine looks for "maps". But your DeepVolt page says "geospatial", "vector tiles", "Mapbox GL", "heatmap". The meaning matches; the words barely do. People phrase questions their own way, so we need search by meaning.
Meaning as a direction
An embedding model turns any text into a fixed-length list of numbers, a vector. Ours outputs 384 numbers per text. During training, the model is pushed to place texts with related meaning so that their vectors point in similar directions. You can't picture 384 dimensions, but two work the same way:
The similarity measure is the cosine of the angle between two vectors:
cos θ = (a · b) / (‖a‖ ‖b‖) where a · b = a₁b₁ + a₂b₂ + … + a₃₈₄b₃₈₄
1 means same direction (same meaning), 0 means unrelated, and negative values are rare in practice. One trick
makes it cheap: divide every vector by its length once (normalize it to length 1). Then
‖a‖ = ‖b‖ = 1 and cosine is just the dot product. That's what _normalise does:
Contrastive training. Show the model millions of pairs that belong together (a question and the passage that answers it, a title and its article) alongside unrelated texts. Adjust the weights so matching pairs' vectors move closer and mismatched ones move apart. Repeat for a very long time. Meaning-as-geometry is what's left over. No one programs "maps ≈ geospatial"; it emerges from the data.
Our model: bge-small-en-v1.5
We use BAAI/bge-small-en-v1.5: 33 million parameters, 384 dimensions, ~65 MB on disk, English. It's small enough to embed our whole corpus on a laptop CPU in a second or two, and good enough to rank well on public retrieval benchmarks (MTEB). Two details matter:
- Queries get a prefix. BGE was trained with "Represent this sentence for searching relevant passages: " in front of questions (but not documents). Questions and passages look very different (short vs. long, asking vs. telling), and the prefix tells the model which side of the pair it's embedding.
- Same model both sides, always. Vectors from two different models live in unrelated spaces; comparing them is meaningless. That's why the index cache key includes the model name (below).
The usual way to run an embedding model is sentence-transformers, which pulls in PyTorch (~2 GB).
fastembed runs the same models exported to
ONNX, a portable format for neural networks, on ONNX Runtime, a lean inference engine
(~50 MB). Same vectors, a fraction of the install size and memory. Ideal for a small server.
Swapping to an API-hosted embedding model (e.g. Gemini's gemini-embedding-001) is one
.env change, thanks to the same Protocol trick as the LLM:
EMBEDDINGS_PROVIDER=openai EMBEDDINGS_BASE_URL=https://generativelanguage.googleapis.com/v1beta/openai/ EMBEDDINGS_MODEL=gemini-embedding-001 EMBEDDINGS_API_KEY=...
Then run the eval (chapter 4) and see whether it's actually better. Bigger isn't automatically better on your data.
The "vector database" is a numpy matrix
All chunk vectors are stacked into one matrix: 47 rows (chunks) × 384 columns. Searching means embedding the
question, multiplying the matrix by that vector (47 dot products, i.e. 47 cosine similarities), and sorting. Here's
the first step of search:
That's ~18,000 multiply-adds: microseconds. Embedding is the expensive part, so it's cached on disk, keyed by a hash of the model name plus every chunk's text. Change a word on your site and the key changes, triggering a re-embed:
When would you need a real vector database?
Comparing against every row (brute force) scales linearly. At a million chunks it's a million dot products per query, still fine on a GPU but slow on a CPU. Vector databases use approximate nearest neighbour indexes, most commonly HNSW, a layered graph you "walk" toward the query, checking a few hundred vectors instead of all of them, at the price of occasionally missing the true best match. Since you know Postgres, the natural upgrade is pgvector:
CREATE EXTENSION vector; CREATE TABLE chunks (id text PRIMARY KEY, text text, embedding vector(384)); CREATE INDEX ON chunks USING hnsw (embedding vector_cosine_ops); -- the same search as `self.vectors @ query`, top 5: SELECT id, text, 1 - (embedding <=> $1) AS cosine FROM chunks ORDER BY embedding <=> $1 LIMIT 5;
Rule of thumb: under ~100k vectors, numpy (or no index at all) is simpler and exact. Your portfolio has 47.
Where embeddings fail
On the eval set (chapter 4), semantic search alone puts the right page first 80% of the time. Its typical misses:
- Exact identifiers. "CP-SAT", "OR-Tools", "R²", "EVMirror": rare tokens a small model has little sense of. Keyword search nails them.
- Vocabulary gaps. "Where did he study?" initially found nothing: the education text said "National Engineering Degree… Higher Institute of Computer Science" and never "study". The fix was in the data: the exporter now writes "studied at university". Often the cheapest retrieval fix is rewording the content.
That's why the next chapter combines both kinds of search.
You switch EMBEDDINGS_MODEL from bge-small to a different model but keep the cached vectors from the old one. What happens?
The worst bugs are silent. A dimension mismatch would crash; two 384-dimensional models wouldn't. The index would just return nonsense. Tying the cache to the model name prevents it.
Why can we compute similarity as a plain dot product (self.vectors @ query) instead of the full cosine formula?
cos θ = a·b / (‖a‖‖b‖). Normalize once at indexing time and every search saves the division.
Go further
- articleJay Alammar: The Illustrated Word2vec The visual origin story of embeddings.
- docsSentence-Transformers docs The reference for training and using text embeddings.
- modelbge-small-en-v1.5 model card Including the query instruction.
- benchmarkMTEB leaderboard Compare embedding models by task.
- articlePinecone: HNSW explained How vector databases search fast.
- toolpgvector Vector search inside Postgres.