Embeddings and vector search

What embeddings are, similarity metrics, approximate nearest-neighbour indexes, and the limits of dense retrieval.

L4 · Applied AI engineer≈ 5 min read
Key points · the two-minute version
  1. An embedding is a vector of meaning. Cosine similarity finds nearest neighbours.
  2. Bi-encoders embed documents ahead of time, which is fast but less precise than reading query and document together.
  3. ANN indexes: HNSW (high recall, more memory) vs IVFFlat (fast builds, needs data first).
  4. Dense retrieval misses exact codes, rare terms, negation and numbers.
  5. Store the embedding model name with every vector. Changing the model means re-embedding everything.
You should be able to
  • Explain embeddings and cosine similarity
  • Describe how HNSW and IVF indexes trade recall for speed
  • Know what dense retrieval misses

Why this matters

Vector search is the first stage of most RAG systems. Understanding it explains both why it finds paraphrases that keyword search misses, and why it misses exact identifiers that keyword search finds trivially.

Core ideas

  • Embedding: a fixed-length vector (hundreds to thousands of numbers) produced by an embedding model, such that texts with similar meaning have nearby vectors.
  • Similarity: cosine similarity (angle between vectors) is the usual measure; dot product and L2 distance are alternatives. Use what the embedding model was trained for.
  • Bi-encoder: query and documents are embedded separately, so documents can be embedded once ahead of time. Fast; less precise than models that read query and document together.
  • Approximate nearest neighbour (ANN): exact search compares the query with every vector; ANN indexes trade a little recall for huge speed-ups.
  • HNSW: a layered graph; excellent recall and speed; more memory; slower to build.
  • IVF (IVFFlat): clusters vectors and searches the nearest clusters; faster builds; needs data before building; tune lists and probes.
  • Same model for queries and documents. Changing the embedding model means re-embedding everything.

Where dense retrieval fails

  • Exact identifiers: product codes, drug names, diagnosis and billing codes, record numbers, error codes.
  • Rare words and new jargon the embedding model hasn't seen.
  • Negation and numbers ("not covered", "over 65").
  • Very long chunks, whose meaning gets averaged into mush.

That's why production systems add lexical search and re-ranking (8.3).

How to do it

vectors = await embedder.embed([c.text for c in chunks])      # batch, not one call per chunk
rows = [(c.id, c.text, v, EMBED_MODEL) for c, v in zip(chunks, vectors)]  # store the model name

Record the embedding model with every vector, so a model change can be detected and migrated with a dual index (Q9).

Interview follow-ups

  • "Cosine, dot product or L2?" Use what the embedding model was trained for; with normalised vectors cosine and dot product rank identically.
  • "How many dimensions?" More dimensions can capture more, but cost storage and speed; some models support truncation (Matryoshka). Choose by eval, not by size.
  • "How do you search in several languages?" A multilingual embedding model, language-aware lexical analysers, and an eval set per language.

Check yourself

Why can dense retrieval miss a query for "ICD-10 E11.9"?

Embeddings capture meaning, not exact strings; rare codes don't have reliable semantic representations, so similar-looking codes or general diabetes text may rank higher. Lexical search matches the exact token.

HNSW or IVFFlat?

HNSW for better recall and query speed when memory and build time allow; IVFFlat for faster builds and lower memory, tuned with lists/probes, built after data exists.

Build it

Embed 200 short documents, search with cosine similarity by brute force, then add an HNSW index and compare results and timing.

What comes next

8.2 Ingestion and chunking.

Build it to remember

Two hands-on projects that exercise this lesson. Pick one, build it end to end, and keep it in your portfolio.

Project 1

Semantic search over your notes

Embed your Markdown notes, search with cosine similarity, and compare brute force with an HNSW index on speed and recall.

  • Python
  • sentence-transformers
  • pgvector
  • FastAPI

Practises Embeddings and ANN trade-offs.

Project 2

Embedding model shoot-out

Score recall@5 on 40 labelled queries for two embedding models and include queries with exact codes to show where dense fails.

  • Python
  • two embedding APIs
  • pandas

Practises Measuring retrieval quality.

Can you answer every check-yourself question out loud without opening the answer?