Learnings

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

Text as vectors

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.

Left side runs once per document change. Right side runs on every question.
TermMeaning
DimensionsLength of the vector. Typical models: a few hundred to a few thousand (approximate, check the model card)
Dense vectorAlmost every position is non-zero. What embedding models produce
k-NNThe 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

Text as vectors

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.

Cosine similarity of one question to three titles. The numbers are printed by the toy embedding in A toy embedding.
  • 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.

MetricMeasuresBefore normalising, nearest to a isUse when
CosineAngle onlyb (1.000)Default for text
Dot productAngle and lengthb (50 beats 24, helped by its length)Vectors are unit length, or length is meant to count
Euclidean (L2)Straight-line distance, lower is nearerc (1.414 beats 5.000)The model card says so
On unit vectors, dot equals cosine and squared L2 equals 2 minus 2 times cosine, so all three rank the same. Dot is the cheapest to compute.

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 pageTrained model
"abroad" vs "another country"Unrelated: no shared lettersClose: same meaning
"otp" vs "one time code"UnrelatedUsually close; in-house jargon can still miss
Typos, pluralsHandled by trigramsMostly handled by subword tokens
Exact codes such as E4012Partly, by spellingWeak: 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 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.

  • e4012 appears in one section, so it carries the most weight. the is everywhere and counts for almost nothing.
  • The misspelt query shares no whole word with any section: zero results.
  • k1 caps the gain from repeated words; b sets 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.

QueryWinnerWhy
what is error E4012BothRare exact token. With a trained model this is keyword's home ground
how do I change my PINKeywordpin is rare and exact; the vector is diluted by the filler words
how much can I send in one dayKeywordIDF ignores filler; the toy vector has no notion of filler
tranfser limtVectorNo whole word matches, most trigrams do
refundsVectorPlural: no stemming in this BM25. Real engines add a stemmer
unknown payment on my statementVectorKeyword is pulled to other sections that say "payment"
charges for using card abroad, otp not received, money did not arriveNeitherSynonyms. Spelling cannot link "abroad" to "another country". This is the gap a trained model closes (not run here)
Keyword (BM25)Vector (trained model)
Strong atIds, error codes, names, rare termsParaphrase, synonyms, long natural questions
Weak atDifferent wording for the same thingExact tokens, negation, numbers
NeedsAn inverted indexA 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.

A document ranked well by both lists beats a document ranked first by only one.
  • 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.

Overlap repeats the end of one chunk at the start of the next, so a sentence cut by one boundary is whole in the neighbour.
WayGoodBad
Fixed sizeTrivial, even sizesCuts mid-sentence: "rejected with" / "error E4012" ended up in two chunks
Fixed with overlapRepairs most cutsMore chunks to store, near-duplicate results
By structure (headings, paragraphs)Each chunk is one topic, heading includedUneven 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.

Match on something small, hand the model something larger.
  • 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

Indexes

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 whenUse 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 indexLatency 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

Indexes

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.

nlist = 256 lists, nprobe = 2 probed. A true neighbour sitting in a skipped list is lost.

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.

Like a skip list in many dimensions: coarse moves first, fine moves last.
IVFHNSW
BuildFast; needs data first to train centroidsSlow; can start empty and grow
MemorySmall overheadVectors plus links per node
Recall at a given speedGoodUsually better
Build knobsnlistm (links per node), ef_construction
Query knobnprobeef_search (candidates kept)
DeletesRemove from a listMarked 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.

Post-filter: search first. A selective filter throws away most of the 10.
Pre-filter: filter first. Always k results, but the ANN index may not help on the reduced set.
Filter keepsDo
Most rowsPost-filter with a little over-fetch
Few rowsPre-filter, then exact search on what is left
Always the same key (tenant, language)Partition: one index per value
UnknownAn 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

Storage and operations

Start with the database you already run. Move only when a measured limit forces it.

OptionPick it whenWatch for
In-memory library (numpy, FAISS, hnswlib)Small or read-only set, one process, batch jobs, testsNo persistence, no filters, each replica holds a full copy
pgvector in PostgreSQLData already in Postgres; you want joins, transactions and SQL filters with the vectorsIndex build memory, vacuum on heavy churn, one node's RAM
OpenSearch or Elasticsearch k-NNYou already run it for text search and want BM25 and vectors in one queryCluster to operate, eventual visibility after refresh
Dedicated vector databaseHundreds of millions of vectors, many tenants, filter-heavy ANNOne 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 WHERE is 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 tsvector column 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

Storage and operations

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.

The same blue-green shape as a schema migration. The query must be embedded with the model of the index it is sent to.
  • 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

Storage and operations

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.

Hashing the chunk text skips the model call for the parts that did not change.
  • 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.

KindQuestionGround truth
Index recallDid ANN return what exact search would?Exact k-NN on the same vectors (shown above)
Retrieval recallIs the chunk that answers the question in the top k?Questions labelled by people
Run it on every change to the chunker, the model, the index settings or the fusion.
  • 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

Storage and operations

SymptomCauseFix
Results look random after a deployQuery embedded with a different model than the indexModel name on the index; refuse a mismatch
Error codes and account ids are never foundVector search onlyHybrid, or route id-shaped queries to keyword
Fewer than k resultsPost-filter after ANNPre-filter, partition or over-fetch
Assistant quotes a withdrawn policyOld chunks never deletedDelete by article id on every change
Answer misses the second half of a ruleChunk boundary cut itStructure split, overlap, return the parent
Something is always returned, even for nonsensek-NN always has k nearestA minimum score tuned on labelled data; allow "no answer"
Recall dropped slowly over monthsIVF centroids stale, or HNSW full of dead nodesScheduled rebuild; track index recall
One customer sees another's textTenant filter missing or applied in the promptServer-side filter or one index per tenant

Cheat sheet

Storage and operations

I need toDo this
Choose a metricNormalise, use dot product, unless the model card says otherwise
Find ids, codes, namesBM25
Serve bothRRF over the two lists, then a reranker
Cut documentsBy structure, capped size, small overlap, metadata on each chunk
Search under 100k vectorsExact; no index to tune
Search millionsHNSW by default, IVF when memory or build time is tight
Trade recall for speedef_search or nprobe, against measured recall
Filter by tenant or productPre-filter or partition
Pick a storeThe database you already run, until a measured limit
Size the memorychunks × dims × 4 bytes, plus the index
Change the modelSecond index, backfill, compare, switch
Know it worksrecall@k on labelled questions, in CI

Interview questions

Storage and operations

QuestionShort 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.