AI Engineering
Embeddings and Vector Search
An embedding turns text into a point, and search becomes "find the nearest points". This page builds that from the ground up on twelve sections of a bank's help articles: similarity maths, a toy embedding, BM25, hybrid search, chunking, an IVF index, filtering and recall. Every Python block was run for this page (Python 3.9, numpy 1.26, no other packages) and its output is pasted from that run. The embedding is a toy made of hashed character trigrams, not a model. The real-model call and the pgvector SQL were not run and say so.
Text as vectors
Part 1 of 5 · points, distances and a toy embedding
What an embedding is
An embedding model maps a piece of text to a fixed-length list of floats. Documents are embedded once at write time, the question at query time, with the same model.
| Term | Meaning |
|---|---|
| Dimensions | Length of the vector. Typical models: a few hundred to a few thousand (approximate, check the model card) |
| Dense vector | Almost every position is non-zero. What embedding models produce |
| k-NN | The k nearest neighbours of the query vector |
Scope: this page stops at "nearest chunks". Turning them into an answer (prompt assembly, reranking, citations) is in RAG.
Near means similar
The model is trained so that texts with similar meaning land close together. Search is then geometry: score every chunk against the question, keep the highest.
- The score is only comparable inside one model. 0.89 from one model and 0.89 from another mean different things.
- There is no universal "relevant" threshold. Pick one per model from labelled queries (Measuring recall).
Cosine, dot product, Euclidean
Text as vectors · run for this page
Three ways to score two vectors. They disagree when lengths differ and agree once every vector is scaled to length 1.
| Metric | Measures | Before normalising, nearest to a is | Use when |
|---|---|---|---|
| Cosine | Angle only | b (1.000) | Default for text |
| Dot product | Angle and length | b (50 beats 24, helped by its length) | Vectors are unit length, or length is meant to count |
| Euclidean (L2) | Straight-line distance, lower is nearer | c (1.414 beats 5.000) | The model card says so |
Trap: the index metric must match the query operator. A cosine index queried with an L2 operator is not used, or returns a different order.
The help articles
Text as vectors · run for this page
Four articles, three sections each. Every later block imports this file, so the blocks are project files: save them in one folder and run each with python3 name.py.
A toy embedding
Text as vectors · run for this page
This is a toy: each word is cut into three-letter pieces and each piece adds 1 to a hashed slot of a 256-float vector. It knows spelling, not meaning, but it is a real fixed-length dense vector and everything downstream works the same.
MATRIX @ embed(query)is the whole search: 12 dot products, sort, take k. This is exact k-NN.- The misspelt query still finds the right section, because most trigrams survive a typo.
What a real model changes
Text as vectors · not run for this page
Swap embed() for a trained model and nothing else on this page changes. Not run for this page (needs a package install and a model download); sentence-transformers is one open-source library, hosted embedding APIs have the same shape: texts in, vectors out.
| Toy on this page | Trained model | |
|---|---|---|
| "abroad" vs "another country" | Unrelated: no shared letters | Close: same meaning |
| "otp" vs "one time code" | Unrelated | Usually close; in-house jargon can still miss |
| Typos, plurals | Handled by trigrams | Mostly handled by subword tokens |
| Exact codes such as E4012 | Partly, by spelling | Weak: rare ids have no learned meaning |
Check the model card: some models want a different prefix or input type for queries and for documents. Getting it wrong lowers recall without any error.
Keyword, vector, hybrid
Part 2 of 5 · two ways to rank, and how to merge them
Keyword search: BM25
Keyword, vector, hybrid · run for this page
BM25 scores a document by the query words it contains: more for rare words, less for repeats, less for long documents. It is what a search engine's text query runs by default.
e4012appears in one section, so it carries the most weight.theis everywhere and counts for almost nothing.- The misspelt query shares no whole word with any section: zero results.
k1caps the gain from repeated words;bsets how much long documents are penalised.
Where each wins and loses
Keyword, vector, hybrid · run for this page
Ten questions, each with the one section that answers it. The numbers are the rank of that section; a dash means it was not returned. The script is in the next chapter.
| Query | Winner | Why |
|---|---|---|
| what is error E4012 | Both | Rare exact token. With a trained model this is keyword's home ground |
| how do I change my PIN | Keyword | pin is rare and exact; the vector is diluted by the filler words |
| how much can I send in one day | Keyword | IDF ignores filler; the toy vector has no notion of filler |
| tranfser limt | Vector | No whole word matches, most trigrams do |
| refunds | Vector | Plural: no stemming in this BM25. Real engines add a stemmer |
| unknown payment on my statement | Vector | Keyword is pulled to other sections that say "payment" |
| charges for using card abroad, otp not received, money did not arrive | Neither | Synonyms. Spelling cannot link "abroad" to "another country". This is the gap a trained model closes (not run here) |
| Keyword (BM25) | Vector (trained model) | |
|---|---|---|
| Strong at | Ids, error codes, names, rare terms | Paraphrase, synonyms, long natural questions |
| Weak at | Different wording for the same thing | Exact tokens, negation, numbers |
| Needs | An inverted index | A model, a vector index, re-embedding on model change |
Hybrid with reciprocal rank fusion
Keyword, vector, hybrid · run for this page
BM25 scores and cosine scores are on different scales, so do not add them. RRF uses only the ranks: each list gives a document 1 / (60 + rank), and the sums are sorted.
- Hybrid is never worse than the weaker list here and takes the win from whichever list has it, at the cost of one rank on two queries.
- A reranker over the fused top 20 to 50 is the usual next step: see RAG.
Chunking
Part 3 of 5 · what one vector should cover
Fixed size, overlap, by structure
Chunking · run for this page
One vector for a whole article blurs every topic in it, so articles are cut into chunks and each chunk gets a vector. Where you cut decides what can be found.
| Way | Good | Bad |
|---|---|---|
| Fixed size | Trivial, even sizes | Cuts mid-sentence: "rejected with" / "error E4012" ended up in two chunks |
| Fixed with overlap | Repairs most cuts | More chunks to store, near-duplicate results |
| By structure (headings, paragraphs) | Each chunk is one topic, heading included | Uneven sizes; needs a fallback split for very long sections |
Default: split on the document's own structure, cap the size, fall back to fixed windows with 10 to 20% overlap. Real pipelines count tokens, not words.
The size trade-off
Chunking · run for this page
The last three lines of the output above are the trade-off. The 8-word chunk matches best (0.72) and cannot answer "how do I fix it". The 94-word chunk holds the fix, scores lowest (0.54) and is about twelve times as long.
- Parent retrieval: embed small chunks, store the parent section id, return the parent.
- Keep metadata on every chunk: article id, heading path, position, updated-at. Filters, citations and deletes all need it.
- Pick the size by measuring recall@k on your own questions, not by rule of thumb.
Indexes: exact and approximate
Part 4 of 5 · scanning less, at the cost of recall
Exact k-NN
Score the query against every vector and keep the top k. Always correct, and the cost grows linearly with the number of vectors and dimensions.
| Use exact when | Use approximate (ANN) when |
|---|---|
| Up to roughly a hundred thousand vectors (approximate; measure) | Millions of vectors |
| A filter already cuts the set small (one customer, one product) | Queries span the whole set |
| Building ground truth to measure an ANN index | Latency budget is a few milliseconds |
Interview point: ANN does not change the ranking function. It skips candidates, so its only error is a missed neighbour. That error is measured as recall against exact search.
IVF: search a few clusters
Build: cluster the vectors with k-means and store each vector in the list of its nearest centroid. Query: find the nearest few centroids and scan only their lists.
More lists (nlist, set at build) means shorter scans and more neighbours split across borders. More probes (nprobe, set per query) means better recall and a slower query.
Centroids are learned from the data present at build time. After the data shifts a lot, rebuild.
HNSW: walk a graph
Indexes · explained, not implemented here
Every vector is a node linked to a few near neighbours. Upper layers hold a few nodes with long links, the bottom layer holds all. A query starts at the top and keeps stepping to whichever neighbour is closer.
| IVF | HNSW | |
|---|---|---|
| Build | Fast; needs data first to train centroids | Slow; can start empty and grow |
| Memory | Small overhead | Vectors plus links per node |
| Recall at a given speed | Good | Usually better |
| Build knobs | nlist | m (links per node), ef_construction |
| Query knob | nprobe | ef_search (candidates kept) |
| Deletes | Remove from a list | Marked dead, cleaned up later; heavy churn hurts |
Recall against latency
Indexes · run for this page
Brute force against a hand-made IVF index in numpy, on 200,000 synthetic vectors grouped around 500 topics. Timings are from one laptop run and will differ on yours; the shape will not.
- Scanning 6% of the vectors (nprobe 16) keeps 89% of the true neighbours at a tenth of the time. The last few points of recall cost the most.
- The curve depends on the data. With the noise factor at 0.7 instead of 1.2 the same script gave recall 0.99 at nprobe 1; at 2.0 it gave 0.11. Measure on your own vectors.
Metadata filters: pre and post
Indexes · run for this page
"Nearest chunks where product is loans" combines a vector search with a normal filter. The order of the two decides whether you get k results.
| Filter keeps | Do |
|---|---|
| Most rows | Post-filter with a little over-fetch |
| Few rows | Pre-filter, then exact search on what is left |
| Always the same key (tenant, language) | Partition: one index per value |
| Unknown | An engine with filter-aware graph search, or iterative scan (check the docs of yours) |
Security: "which customer may see this chunk" is a filter the server applies, never something left to the prompt.
Storage and operations
Part 5 of 5 · where vectors live and how they stay correct
Storage options
Start with the database you already run. Move only when a measured limit forces it.
| Option | Pick it when | Watch for |
|---|---|---|
| In-memory library (numpy, FAISS, hnswlib) | Small or read-only set, one process, batch jobs, tests | No persistence, no filters, each replica holds a full copy |
| pgvector in PostgreSQL | Data already in Postgres; you want joins, transactions and SQL filters with the vectors | Index build memory, vacuum on heavy churn, one node's RAM |
| OpenSearch or Elasticsearch k-NN | You already run it for text search and want BM25 and vectors in one query | Cluster to operate, eventual visibility after refresh |
| Dedicated vector database | Hundreds of millions of vectors, many tenants, filter-heavy ANN | One more system to sync with the source of truth |
Rule: the vector store is a derived index. The articles live in the primary database, and the index must be rebuildable from them.
pgvector: table, index, query
Storage and operations · not run for this page
Not run for this page (no database was started). Syntax follows the pgvector README; check it for your version.
- The index is used only for
ORDER BY distance LIMIT k, ascending, with the operator the index was built for. - The
WHEREis applied after the index scan, so a selective filter can return fewer than 5 rows: the post-filter problem. Fixes: a partial index per product, partitioning, or iterative index scans in newer versions (check the docs). - Hybrid: add a
tsvectorcolumn with a GIN index, run both queries, fuse with RRF in SQL or in the app. Postgres text ranking is not BM25.
Dimensions and storage cost
Storage and operations · run for this page
Raw size is chunks × dimensions × bytes per number. An ANN index wants this in RAM.
- The graph-link line is a rough lower bound (4-byte ids, bottom layer only).
- Fewer dimensions: some models let you request or truncate to a shorter vector. Re-normalise after truncating and re-measure recall.
- Quantisation: search on int8 or binary codes, then re-score the top few hundred with the full floats.
- Embedding cost is paid per token at write time and again on every re-embed. Prices change: check the docs.
Re-embedding on model change
Vectors from two models, or two versions of one model, live in different spaces and cannot be compared. Changing the model means embedding everything again into a second index.
- Store the model name and version on every row and in the index name.
- A hosted model can be retired by its provider. Keep the source text so a rebuild is always possible.
Updates and deletes
An edited article produces a new set of chunks. Chunks that no longer exist must be removed, or the assistant keeps quoting the old text.
- Drive it from change events on the articles table (outbox or CDC), not from a nightly full rebuild alone.
- Make the job idempotent: deterministic chunk ids such as
article_id:position:hash. - Deletion requests (a customer's data) must reach the vector store and its backups too.
Measuring recall@k
Storage and operations · run for this page
Two different things are both called recall. Measure them separately.
| Kind | Question | Ground truth |
|---|---|---|
| Index recall | Did ANN return what exact search would? | Exact k-NN on the same vectors (shown above) |
| Retrieval recall | Is the chunk that answers the question in the top k? | Questions labelled by people |
- Ten questions is a demonstration, not a benchmark. Use a few hundred real ones, including questions with no answer in the corpus.
- Answer quality on top of retrieval is a separate measurement: see LLM Evaluation.
Common failures
| Symptom | Cause | Fix |
|---|---|---|
| Results look random after a deploy | Query embedded with a different model than the index | Model name on the index; refuse a mismatch |
| Error codes and account ids are never found | Vector search only | Hybrid, or route id-shaped queries to keyword |
| Fewer than k results | Post-filter after ANN | Pre-filter, partition or over-fetch |
| Assistant quotes a withdrawn policy | Old chunks never deleted | Delete by article id on every change |
| Answer misses the second half of a rule | Chunk boundary cut it | Structure split, overlap, return the parent |
| Something is always returned, even for nonsense | k-NN always has k nearest | A minimum score tuned on labelled data; allow "no answer" |
| Recall dropped slowly over months | IVF centroids stale, or HNSW full of dead nodes | Scheduled rebuild; track index recall |
| One customer sees another's text | Tenant filter missing or applied in the prompt | Server-side filter or one index per tenant |
Cheat sheet
| I need to | Do this |
|---|---|
| Choose a metric | Normalise, use dot product, unless the model card says otherwise |
| Find ids, codes, names | BM25 |
| Serve both | RRF over the two lists, then a reranker |
| Cut documents | By structure, capped size, small overlap, metadata on each chunk |
| Search under 100k vectors | Exact; no index to tune |
| Search millions | HNSW by default, IVF when memory or build time is tight |
| Trade recall for speed | ef_search or nprobe, against measured recall |
| Filter by tenant or product | Pre-filter or partition |
| Pick a store | The database you already run, until a measured limit |
| Size the memory | chunks × dims × 4 bytes, plus the index |
| Change the model | Second index, backfill, compare, switch |
| Know it works | recall@k on labelled questions, in CI |
Interview questions
| Question | Short answer |
|---|---|
| Cosine or dot product? | The same ranking on unit vectors; dot is cheaper. They differ only when length varies, and then follow the model card. |
| Why not vector search alone? | It is weak on exact tokens: ids, error codes, rare names. Keyword search is weak on paraphrase. Hybrid covers both. |
| Why RRF and not a weighted sum of scores? | The two scores have different scales and distributions. Ranks need no calibration. |
| How do you pick a chunk size? | Small enough to be one topic, large enough to answer. Then measure recall@k on labelled questions and adjust. |
| HNSW or IVF? | HNSW: better recall for the speed, more memory, slow build. IVF: cheap and fast to build, needs training data and rebuilds as data drifts. |
| What does ANN get wrong? | It can miss true neighbours; it never mis-scores. Quantify with recall against exact search. |
| A filtered search returns 2 of 10 results. Why? | The filter ran after the ANN top k. Pre-filter, partition by the key, or over-fetch. |
| You are upgrading the embedding model. Plan? | New index beside the old, dual write, backfill, compare recall, switch reads, keep the old one for rollback. |
| How much memory for 10 million 1024-dim vectors? | 10M × 1024 × 4 bytes is about 41 GB of float32, before index overhead. Quantise or shard. |
| How do you know retrieval got worse? | A fixed labelled set, recall@k and MRR tracked per release, plus the share of queries below the score threshold in production. |
Next: RAG puts retrieval in front of a model. Back to AI Engineering.