Slides · Embeddings and vector search

Vector databases

Vector databases

How a store finds the nearest vectors fast, what “approximate” gives up, and how to choose and measure one.

By the end you can explain the ANN trade-off, compare HNSW and IVF, tune and measure recall, choose a store, and design for filters and updates.

Concept

40,000 articles, one second

  • A help centre needs the three closest articles to a question in under a second.
  • Option one: compare the question with every article.
  • Option two: group the articles and look only in the nearest groups.
  • Option three: keep a shortcut list that is usually right.
  • Interviewers probe the word “approximate”: what is traded away, which knob buys it back, how do you check.

Concept

Mental model: a floor plan for a library

  • Exact search walks every shelf with the query in hand.
  • An ANN index is a floor plan: walk to the right area, check the shelves around it.
  • You may miss the single best book, but you finish in a fraction of the time.
  • You pay for the map with memory and build time.

Worked example

Why exact search stops scaling

Illustrative corpus: 10 million vectors of 1,536 dimensions.

StepCalculation
Multiply-adds for one query10,000,000×1,536=15.3610{,}000{,}000 \times 1{,}536 = 15.36 billion
At 1,000 queries per second15.36 billion×1,000=15.3615.36\ \text{billion} \times 1{,}000 = 15.36 trillion per second
  • One query is feasible in an offline job. It is too heavy for a request with a latency budget of tens of milliseconds.
  • Work grows with vectors times dimensions, so doubling the corpus doubles the cost of every query.
  • Exact search stays exact. Only its cost grows.

Diagram

Brute force versus ANN

Diagram: Brute force compares the query with every stored vector and is exact but slow.

Query vector

Brute force: compare with all vectors

ANN index: jump to the right neighbourhood

Exact top-k: slow, no index to build

Almost the same top-k: fast, costs memory and build time

Diagram summary: Brute force compares the query with every stored vector and is exact but slow. An ANN index goes straight to the right neighbourhood, so it is fast but may miss a true neighbour, and it costs memory and build time.

Concept

Brute force still has two jobs

  • Small corpora: a few thousand to tens of thousands of vectors is often fast enough with no index. Measure on your own hardware.
  • Ground truth: flat indexes are the only ones the Faiss guidelines say guarantee exact results, so they define the “true” neighbours.
  • Every recall number later in this deck is measured against this exact answer.

Source1 Guidelines to choose an index (Faiss wiki)

Worked example

Recall@k: what “approximate” costs

Recall@kk is the share of the true top-kk neighbours that the ANN search actually returned.

StepValue
Exact top 10 (ground truth)10 vectors
ANN top 10 contains how many of those9
Recall@109/10=0.99 / 10 = 0.9
  • It measures how close ANN is to exact search. It does not measure whether the results are useful to the user.
  • Every ANN index has settings that trade recall against latency and memory. You choose a point on that curve.

Worked example

Diminishing returns on one knob

These numbers are illustrative, not measurements of any real index.

ef_searchRecall@10Time per queryGain from previous row
100.821 ms
400.953 ms+0.13 recall for +2 ms
1000.987 ms+0.03 recall for +4 ms
4000.99526 ms+0.015 recall for +19 ms
  • Each step buys less recall for more time.
  • Once your recall target is met, extra effort is wasted latency.

Diagram

HNSW: a layered graph

Diagram: An HNSW search enters at the sparse top layer, hops toward the query, then drops to a denser layer and repeats.

hop greedily toward the query

drop a layer and repeat

Query vector

Top layer: few nodes, long hops

Middle layer: more nodes

Bottom layer: all vectors, short hops

Candidate top-k

Diagram summary: An HNSW search enters at the sparse top layer, hops toward the query, then drops to a denser layer and repeats. At the bottom layer it has reached the neighbourhood of the query and returns its best candidates.
  • Malkov and Yashunin describe a multi-layer set of proximity graphs where upper layers are searched first.
  • Analogy: motorway, then main road, then street map.

Source2 Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs

Concept

HNSW knobs

KnobWhat it controlsWhen it is set
MLinks kept per nodeBuild time; changing it means rebuilding
ef_constructionSearch width while buildingBuild time; slower builds when raised
ef_searchCandidates tracked per queryQuery time; can change per query
  • Higher values raise recall at the cost of memory, build time or latency.
  • pgvector defaults: m = 16, ef_construction = 64, hnsw.ef_search = 40.
  • HNSW has no training step in pgvector: the index can be created on an empty table.

Source3 pgvector: open-source vector similarity search for Postgres

Worked example

What the HNSW graph costs

The Faiss guidelines give HNSW memory as (d×4+M×2×4)(d \times 4 + M \times 2 \times 4) bytes per vector, where dd is the dimension and MM the links per vector.

StepCalculation
Vector itself (d=1,536d = 1{,}536, float32)1,536×4=6,1441{,}536 \times 4 = 6{,}144 bytes
Graph links (M=16M = 16)16×2×4=12816 \times 2 \times 4 = 128 bytes
Per vector6,272 bytes
1 million vectors6.272 GB
  • At M=16M = 16 the links add about 2 percent over the raw vectors (128/6,144128 / 6{,}144), and the vectors themselves dominate.
  • Raising M raises the graph share. This is the Faiss formula; other products store the graph differently.

Source1 Guidelines to choose an index (Faiss wiki)

Diagram

IVF: clusters and probes

Diagram: An IVF query is compared with the cluster centres first, then only the nearest few clusters are scanned.

true neighbour in an unprobed cluster

Query vector

Compare with all cluster centres: only nlist of them

Pick the nprobe nearest clusters

Scan only the vectors inside those clusters

Candidate top-k

Missed

Diagram summary: An IVF query is compared with the cluster centres first, then only the nearest few clusters are scanned. A true neighbour that sits in a cluster that was not probed is missed, which is where IVF loses recall.
  • Analogy: postal districts. Search the districts nearest the address, not the whole country.
  • IVF learns its cluster centres from a sample, so the table should hold representative data before you build the index.

Sources4 Faster search (Faiss wiki)3 pgvector: open-source vector similarity search for Postgres

Concept

IVF knobs

KnobWhat it controlsNotes
nlist (pgvector: lists)Number of clustersFixed at build; changing it means rebuilding
nprobe (pgvector: probes)Clusters scanned per querySearch time grows roughly linearly with it
  • Probing all clusters (nprobe=nlist\mathrm{nprobe} = \mathrm{nlist}) matches brute force, but slower.
  • Defaults: Faiss and pgvector both start at nprobe 1.
  • pgvector’s starting points: lists=rows/1,000\mathrm{lists} = \mathrm{rows} / 1{,}000 up to 1 million rows, probes\mathrm{probes} near lists\sqrt{\mathrm{lists}}. Treat them as places to start measuring.

Sources4 Faster search (Faiss wiki)3 pgvector: open-source vector similarity search for Postgres

Worked example

IVF cost, by hand

Illustrative: 1,000,000 vectors, nlist=1,000\mathrm{nlist} = 1{,}000 clusters, assumed equal-sized (1,000 vectors each). Distance computations per query are centres plus scanned vectors.

nprobeCalculationDistancesShare of brute force
11,000+1×1,0001{,}000 + 1 \times 1{,}0002,0000.2%
101,000+10×1,0001{,}000 + 10 \times 1{,}00011,0001.1%
321,000+32×1,0001{,}000 + 32 \times 1{,}00033,0003.3%
  • 1,000\sqrt{1{,}000} is about 32, the pgvector starting point for probes.
  • Real clusters are uneven, so measure rather than trust this arithmetic.
  • Raising nlist to 4,000 at nprobe 10 gives 4,000+10×250=6,5004{,}000 + 10 \times 250 = 6{,}500 distances: faster, but each query now looks at only 0.25% of the data (10 of 4,000 clusters), so recall usually falls.

Sources4 Faster search (Faiss wiki)3 pgvector: open-source vector similarity search for Postgres

Compare

HNSW versus IVF

AspectHNSWIVF
How it searchesHops through a layered graphScans the nearest few clusters
MemoryHigherLower
Build timeSlowerFaster
Needs trainingNo: index can start emptyYes: centres learned from existing data
Speed-recall trade-offBetter per the pgvector READMESlower queries at the same recall
Main recall knobef_searchnprobe
  • Faiss guidance: HNSW is a very fast and accurate choice when RAM is plentiful or the dataset is small.
  • IVF is the lighter choice when memory or build time is tight.

Sources3 pgvector: open-source vector similarity search for Postgres1 Guidelines to choose an index (Faiss wiki)

Worked example

Quantization shrinks the vectors

1 million vectors of 1,536 dimensions:

StoragePer vectorTotal
32-bit floats1,536×4=6,1441{,}536 \times 4 = 6{,}144 bytesabout 6.1 GB
8-bit integers (scalar quantization)1,536×1=1,5361{,}536 \times 1 = 1{,}536 bytesabout 1.5 GB
Product quantization, 64-byte codes (illustrative)64 bytes64 MB
  • Product quantization stores M-byte codes per vector (Faiss guidelines). Compression usually costs some recall.
  • Common pattern: search the compressed vectors, then re-rank a short list with the originals.

Source1 Guidelines to choose an index (Faiss wiki)

Diagram

Compress, then re-rank

Diagram: Compressed vectors are searched first because they are small and quick.

Query

Search compressed vectors

Short list, e.g. top 100

Re-rank with full-precision vectors

Final top-k

Diagram summary: Compressed vectors are searched first because they are small and quick. A short list is then re-scored with the original full-precision vectors, which recovers much of the recall that compression cost.

Process

How to measure recall

  1. Sample a few hundred real queries, from logs or a realistic test set.
  2. Get the exact top-k for each with brute force. This is the ground truth.
  3. Get the ANN top-k with your index and settings.
  4. Compute recall@k as the overlap, and record latency.
  5. Change one knob at a time (ef_search, nprobe) and re-measure.
  6. Pick the cheapest setting that meets your recall target.
  • pgvector’s README says to monitor recall by comparing approximate with exact results, and shows SET LOCAL enable_indexscan = off; to force exact search.
  • Check that retrieval recall is what really limits your product. Embeddings or chunking sometimes matter more.

Source3 pgvector: open-source vector similarity search for Postgres

Worked example

A tiny recall measurement

Illustrative: 5 queries, k=10k = 10. For each, count how many of the exact top 10 the ANN search returned.

QueryOverlap with exact top 10Recall@10
q1101.0
q290.9
q3101.0
q480.8
q590.9
Mean46/5046 / 500.92
  • Look at the worst queries, not only the mean: q4 at 0.8 is where users would notice.
  • Real measurements need hundreds of queries. Five is only to show the arithmetic.

Compare

Three kinds of store

OptionWhat it isGood whenWatch out for
Postgres extension (pgvector)Vector columns and ANN indexes inside the database you already runModest scale, and you want transactions and joins in one systemOne node’s memory and build time, tuning, dimension limits
Library (Faiss)An index you embed in your own service, not a databaseOffline jobs, research, custom servingYou build persistence, updates, filtering and replication
Dedicated vector database (for example Qdrant, Weaviate, Pinecone)A service built around vector indexes, filtering and scalingLarge corpora, high query volume, built-in shardingAnother system to run, pay for and keep in sync
  • Faiss describes itself as a library for similarity search and clustering of dense vectors.
  • Qdrant describes itself as a vector similarity search engine and vector database.

Sources3 pgvector: open-source vector similarity search for Postgres5 Faiss: a library for efficient similarity search and clustering of dense vectors6 Qdrant: vector similarity search engine and vector database

Concept

“Dedicated” does not mean “managed only”

  • Qdrant is Apache 2.0 licensed, can run locally with Docker, and also has a managed Qdrant Cloud.
  • Weaviate calls itself open source and lists Docker, Kubernetes and embedded options plus Weaviate Cloud.
  • Pinecone’s overview describes a search engine for AI agents and applications, and a Bring Your Own Cloud option that deploys in your own cloud account.
  • All checked for this deck on 2026-10-22. Products and plans change, so confirm current options before you decide.

Sources6 Qdrant: vector similarity search engine and vector database7 Weaviate Database | Weaviate Documentation8 Pinecone Database

Worked example

A limit that can decide the choice

pgvector can index its vector type up to 2,000 dimensions and halfvec up to 4,000.

Embedding dimensionsIndex options
1,536vector (limit 2,000) or halfvec (limit 4,000)
3,072halfvec only: over the 2,000 limit, under 4,000
  • A 3,072-dimension embedding needs half-precision storage or a shorter vector.
  • Read the current docs for limits like this before you commit.

Source3 pgvector: open-source vector similarity search for Postgres

Diagram

Start from what you run

Diagram: Start from what you already run.

yes

no

yes

no

yes

no

Already running Postgres, modest vector count?

pgvector: measure first

Offline job or research, no live service?

Faiss library

Dedicated vector database

Measured limit hit: latency, memory, filtering, ops?

Stay where you are

Diagram summary: Start from what you already run. Postgres with pgvector is the default for modest scale, Faiss fits offline or embedded use, and a dedicated database is for scale or needs you have measured, not guessed.
  • This is judgment, not a measured law: move when a measured limit forces you.

Diagram

Metadata filters can starve the result list

Diagram: With a filter applied after the approximate search, only the matching share of the candidate list survives.

ANN returns 40 candidates

Filter keeps the 10% that match

About 4 results, fewer than k = 10

Diagram summary: With a filter applied after the approximate search, only the matching share of the candidate list survives. Ten percent of 40 candidates leaves about 4 rows, fewer than the 10 requested.
  • pgvector’s README uses exactly this example: a condition matching 10% of rows with hnsw.ef_search at 40 gives about 4 matching rows on average.
  • Remedies: iterative index scans (pgvector 0.8.0 and later), a larger candidate list, partitioning by the filter field, or an engine that filters during the graph search.
  • Permission filters are a security boundary. A missed filter is a data leak, not a ranking quirk. Test filtered queries for recall too.

Source3 pgvector: open-source vector similarity search for Postgres

Worked example

Keeping the index fresh

Use deterministic chunk IDs, such as document ID plus chunk number.

EventChunk IDs beforeAfter re-embedding
Document refund-policy has 5 chunksrefund-policy#0 to #4
Document edited, now 4 chunks#0 to #3 are overwritten
Chunk that no longer existsrefund-policy#4Delete it
  • Random IDs would leave the old chunks in the index, still matching queries.
  • Some indexes need periodic rebuilds or compaction after many deletes.

Check yourself

Check: probing more clusters

IVF over 1,000,000 vectors with nlist=2,000\mathrm{nlist} = 2{,}000 (assume 500 vectors per cluster). You compare nprobe=20\mathrm{nprobe} = 20 with nprobe=40\mathrm{nprobe} = 40. By how much does the scan work change, and what is the trade?

Answer

Vectors scanned go from 20×500=10,00020 \times 500 = 10{,}000 to 40×500=20,00040 \times 500 = 20{,}000, so the scan work doubles. Adding the 2,000 centre comparisons, total distances go from 12,000 to 22,000, so latency rises by less than double. You pay in latency for the higher recall you hope to gain. Re-measure recall against brute force to confirm the gain is worth it.

Check yourself

Check: does the graph fit?

A server can give the index 5 GB. You plan an HNSW index over 2,000,000 vectors of 768 dimensions (float32) with M=16M = 16, using the Faiss memory formula. Does it fit? Name two ways to get under budget, and say whether switching to IVF alone would do it.

Answer

Per vector: 768×4+16×2×4=3,072+128=3,200768 \times 4 + 16 \times 2 \times 4 = 3{,}072 + 128 = 3{,}200 bytes. For 2,000,000 vectors that is 6.4 GB, which is over the 5 GB budget, so it does not fit. The raw vectors alone are 2,000,000×3,0722{,}000{,}000 \times 3{,}072 bytes =6.144= 6.144 GB, so the graph (0.256 GB) is not the problem. Two ways under budget: shorten the vectors (at 384 dimensions the formula gives 1,664 bytes, 3.328 GB), or store compressed codes (quantization, for example IVF with product quantization). Plain IVF with full vectors stores the same 6.144 GB, so switching to it alone does not fit. Re-measure recall after any change.

Check yourself

Check: the starved filter

Your HNSW query filters after the index search, and the filter matches 5% of rows. You need 10 results. Roughly what ef_search gives 10 matching rows on average, and why is that not a full fix?

Answer

Matching rows =ef_search×0.05= \mathrm{ef\_search} \times 0.05, so 10=ef_search×0.0510 = \mathrm{ef\_search} \times 0.05 gives ef_search=200\mathrm{ef\_search} = 200. It is only an average, so some queries still return fewer than 10. A larger candidate list also raises latency for every query, and a rarer filter (1%) would need 1,000. That is why iterative scans or partitioning by the filter field are worth testing. Re-test filtered queries for recall either way.

Check yourself

Check: 3,072 dimensions in Postgres

A team on Postgres wants to index 800,000 embeddings of 3,072 dimensions with pgvector. What blocks a plain vector index, and what are two ways round it?

Answer

The vector type can be indexed up to 2,000 dimensions, and 3,072 is over that. Either store the vectors as halfvec, which can be indexed up to 4,000 dimensions, or use a shorter embedding if the model supports a dimensions setting. Test the retrieval quality after either change.

Summary

Recap

  • Exact search costs vectors x dimensions per query; ANN trades a little recall for much lower latency.
  • HNSW: layered graph, no training, more memory. Knobs: M, ef_construction, ef_search.
  • IVF: clusters probed per query, less memory, needs training. Knobs: nlist, nprobe.
  • Measure recall@k against brute force on real queries, one knob at a time.
  • Start with what you run, often pgvector, and move when a measured limit forces it.
  • Design filters and updates explicitly: post-filtering can return too few results, and deterministic chunk IDs prevent stale copies.

References

References & Sources (1 of 2)

  1. Guidelines to choose an index (Faiss wiki) (opens in a new tab)

    Meta Research (Faiss project)2026Documentation

    Used for Flat indexes are the only ones that guarantee exact results, HNSW memory is (d * 4 + M * 2 * 4) bytes per vector, and a product quantizer stores M-byte codes.

  2. Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs (opens in a new tab)

    Yu. A. Malkov, D. A. Yashunin2020IEEE Transactions on Pattern Analysis and Machine IntelligencePaper

    Used for HNSW is a graph-based approximate nearest-neighbour method that builds a multi-layer set of proximity graphs and searches from the upper layers down.

  3. pgvector: open-source vector similarity search for Postgres (opens in a new tab)

    pgvector2026Repository

    Used for pgvector defaults (m 16, ef_construction 64, hnsw.ef_search 40, ivfflat probes 1), lists and probes starting points, IVFFlat versus HNSW trade-off, 10%-filter example giving 4 rows, iterative scans from 0.8.0, the 2,000 and 4,000 dimension limits, and checking recall against exact search.

  4. Faiss: a library for efficient similarity search and clustering of dense vectors (opens in a new tab)

    Meta Research (Faiss project)2026Repository

    Used for Faiss describes itself as a library for efficient similarity search and clustering of dense vectors.

References

References & Sources (2 of 2)

  1. Qdrant: vector similarity search engine and vector database (opens in a new tab)

    Qdrant2026Repository

    Used for Qdrant is a vector database licensed under Apache 2.0, runs locally with Docker, and has a managed Qdrant Cloud.

  2. Weaviate Database | Weaviate Documentation (opens in a new tab)

    Weaviate2026Documentation

    Used for Weaviate calls itself an open-source vector database with Docker, Kubernetes, embedded and Weaviate Cloud options.

  3. Pinecone Database (opens in a new tab)

    Pinecone2026Documentation

    Used for Pinecone describes itself as a search engine for AI agents and applications, with a Bring Your Own Cloud deployment option.