SeeingML
Modern AI & LLMs Guide 6 of 7 · tap to switch
✦ 3D Interactive Visual Guide 14 min · 4 hands-on labs · Interactive 3D WebGL

Vector Databases & HNSW

Fly inside a 3D multi-layer HNSW skip graph to see how vector databases search millions of embeddings in milliseconds, compare IVF vs. HNSW, and shrink RAM 32x with Product Quantization.

What is a vector database? Imagine running a digital library of 10 million articles. A visitor asks: “How do space telescopes detect water on alien moons?” Regular keyword search struggles when the best article is titled “Europa Subsurface Saltwater Ocean” and never even repeats the word “telescopes”.

An AI embedding model (from Tokenization & Word Embeddings) solves this by turning every article into coordinates on a map of meaning, so similar ideas sit right next to each other. A vector database stores that map and builds smart shortcuts (called Approximate Nearest Neighbor indexes, like HNSW) so you can find the closest matching articles in milliseconds instead of checking every single document one by one.

Start with Step 1 below and click Next Step. We will build a 3D vector database one floor at a time, watching each step animate live before unlocking the full Free 3D Sandbox.

Interactive 3D Walkthrough: Inside a Vector Database

Loading 3D Meaning Map...
Step 1 of 7 · Start Simple

First, forget 3D layers: meet the Meaning Map

A vector database starts by placing every article onto a map of meaning. Articles about similar ideas sit close together (Space, Oceans, Medicine, Culinary, History, AI). The glowing golden diamond is your question landing right next to Space articles.
Active Question
“How do space telescopes detect water on alien moons?”
What to notice: Hover any colored sphere to read its article title, then hit Next Step to see how a computer finds the closest matches.

How the HNSW algorithm skips millions of vectors

Now that you have watched the 3 floors rise and seen the glowing orb hop across them, let’s put official names to what just happened. That 3-story shortcut map is called HNSW (Hierarchical Navigable Small World), introduced by Malkov and Yashunin (2018), built on the same distance math you saw in Cosine Similarity and K-Nearest Neighbors:

  • Floor 2 (Express Flights): Only a tiny fraction of articles gets promoted to the top floor. Long-range bridges cross the entire meaning map in 1 or 2 hops, jumping from Culinary & Coffee straight over to Space & Astrophysics in milliseconds.
  • Floor 1 (Regional Highways): When no Floor 2 hub gets closer to your question, the search takes the glowing cyan vertical elevator straight down to the exact same article on Floor 1, where medium-range links narrow in on the target region.
  • Floor 0 (Local Streets + Beam Search): Every article lives on the ground floor. Instead of stopping at the first local dead end, HNSW keeps a live shortlist of backup candidates called efSearch (search thoroughness) until it is confident it found the true closest neighbors.

Three knobs govern almost every real-world HNSW deployment (all unlocked in the Free 3D Sandbox tab above):

  1. efSearch (Search thoroughness at query time): Your live speed-vs-accuracy dial! Raising efSearch checks more nearby ground-floor streets and prevents missed matches; lowering it speeds up every query immediately.
  2. M (Links per article): Higher M (typically 16 to 32 in production) builds more highway bridges for higher accuracy, at the cost of extra RAM per article (~2M edges on Floor 0).
  3. efConstruction (Map-building effort): Controls how carefully HNSW picks diverse bridges once when adding articles to the library. Higher values (100 to 200) build a cleaner map with zero extra RAM cost at query time.
✓ Tip

Try breaking HNSW yourself: jump to Step 6 (Local Search) above and click “Try tricky query at efSearch=1”. Because the ground floor stops checking the instant it hits a local pocket, accuracy drops! Drag Search Thoroughness (efSearch) back up to 12 and watch the search bridge across and hit 100% accuracy.


HNSW vs. IVF: tuning recall, latency, and scale

Every fast vector index makes one core trade-off: speed (how few articles you check) vs. accuracy (how many of the true top 5 matches you find, called Recall@5).

If HNSW is a 3-floor highway network, its main rival IVF (Inverted File Index) works like sorting a giant library into labeled topic rooms (Voronoi zones, built with K-Means Clustering). When a question arrives, IVF checks which room signs look closest, opens only the nearest nprobe rooms, and scans every article inside them.

  • Why pick IVF? It stores no highway links, so it builds faster and uses less memory than HNSW.
  • What is the catch? If your question lands right near the fence between two rooms and nprobe = 1, great matches sitting inches across the wall stay hidden until you open more rooms.

Walk through the 3 guided buttons in Lab 2 below (and click any dot on the chart) to see how HNSW and IVF compare from 100K up to 100M articles, and notice the big memory surprise waiting at Step 3!

Interactive Lab 2: Speed vs. Accuracy & Why Scale Breaks Brute Force
Walk through:
Skip 80%+ of articles and still find the top 5: Click any dot on the chart below. Notice how HNSW (magenta) hugs the green top-left sweet spot: it checks a tiny fraction of articles while still hitting 95% to 100% accuracy.
Live 240-Article Test (Click Any Dot to Inspect)
BEST ZONE (FAST + ACCURATE)60%70%80%90%100%060120180240Articles Checked per Query (Farther Left = Faster)Top-5 AccuracyIVF nprobe=1: 34.3 articles checked, 100% accuracyIVF nprobe=2: 49.7 articles checked, 100% accuracyIVF nprobe=3: 60.8 articles checked, 100% accuracyIVF nprobe=4: 71.3 articles checked, 100% accuracyIVF nprobe=6: 108 articles checked, 100% accuracyIVF nprobe=8: 131.7 articles checked, 100% accuracyHNSW efSearch=1: 23.3 articles checked, 97% accuracyHNSW efSearch=2: 25.3 articles checked, 100% accuracyHNSW efSearch=4: 28.5 articles checked, 100% accuracyHNSW efSearch=8: 33.2 articles checked, 100% accuracyHNSW efSearch=14: 40 articles checked, 100% accuracyHNSW efSearch=24: 54 articles checked, 100% accuracyHNSW efSearch=38: 63 articles checked, 100% accuracyFlat (all 240)
Selected: HNSW (efSearch=4)100% accuracy · 28.5/240 checked
Skipped 88% of the library (8.4x less work than brute force) while finding 5 of 5 true winners on average.
HNSW (3-floor highway) IVF (topic zones) Brute-Force Flat
Real-World Scale (1 million Articles · Standard AI Embeddings)
Brute-Force Flat(Checks every single article)
1.0M checks
Query wait120 ms
RAM needed6.14 GB
IVF Zones (open 16)(Scans nearest topic rooms only)
17.0K checks
Query wait2.0 ms
RAM needed6.27 GB
HNSW 3-Floor Map(M=16 links, width=64)
1.1K checks
Query wait0.14 ms
RAM needed6.30 GB
Compressed IVF-PQ (Preview)(Shrunk with next section trick)
17.0K checks
Query wait0.51 ms
RAM needed56 MB
Bottom line at 1M articles: HNSW does 884x less work than Brute Force, cutting wait time from 120 ms down to 0.14 ms. The catch: keeping full vectors plus highway links in RAM still costs 6.30 GB. Next, see how compression shrinks that bill 64x!
Index FamilyQuery SpeedTop-5 AccuracyMemory (RAM) CostBest Everyday Fit
Flat (Brute Force)Slow past ~100K articles100% exact1.0x (raw vectors only)Small libraries (<100K) or exact benchmarks
IVF-Flat (Topic Zones)Fast (pick nprobe rooms)High (90% to 98%)~1.02x (room centers only)Fast index builds and moderate RAM budgets
IVF-PQ (Compressed)Very fast (swatch lookups)Good (reranks to 95%+)0.03x to 0.08x (16x to 64x smaller)10M to 1B articles on tight memory budgets
HNSW (3-Floor Map)Sub-millisecond O(log N)Very high (96% to 99.5%)~1.2x to 1.6x (highway links)Default pick for live RAG and semantic search
DiskANN (SSD Graph)Low-ms NVMe disk readsHigh (95% to 98%)~0.15x to 0.25x (tiny RAM index)100M+ scale without giant RAM clusters

Product quantization (PQ): shrinking embeddings 32x

Notice the painful surprise from Step 3 of Lab 2 above: even though HNSW searches 10 million articles in ~1 millisecond, just storing 10 million standard embeddings in RAM takes 61.4 GB (10,000,000 × 1,536 decimal numbers × 4 bytes) before adding a single highway link!

Product Quantization (PQ) solves that memory bill with a clever paint-swatch trick:

  1. Slice each long list of numbers into short chunks: Cut a 1,536-number vector into m short slices (for example, 96 slices of 16 numbers each).
  2. Build a 256-pattern Swatch Book for each slice: Group common slice patterns into 256 reusable prototypes. Because 0 to 255 fits in one single byte, you can replace 16 full decimal numbers (64 bytes) with a 1-byte Swatch ID (like #12)!
  3. Store tiny byte codes in RAM: A full 6,144-byte article shrinks down to just 96 bytes (64x smaller!), dropping 10 million articles from 61.4 GB down to ~1 GB.
  4. Fix tiny rounding slips with 4x Reranking: Swatch rounding can slightly nudge the top-5 order. So the database grabs the top 20 compressed candidates from RAM in microseconds, loads just those 20 full originals from disk, and re-sorts them cleanly back to 100% accuracy.

Click Step 1 -> Step 2 -> Step 3 below to watch 61.44 GB shrink to ~1 GB, see real compression drift appear, and then watch 4x Reranking fix it live!

Interactive Lab 3: Shrinking 61 GB to 1 GB with Product Quantization
10M RAM: 61.44 GBAccuracy: 100%
Full precision eats 61.44 GB of RAM for 10M articles: Every standard AI embedding stores 1,536 decimal numbers (4 bytes each = 6,144 bytes). Multiply by 10 million articles and you need an expensive 64+ GB RAM server before adding a single search highway.
How One Article Vector Shrinks (6,144 Bytes → 96 Bytes)
Original Full Vector (6,144 Bytes)
Slice 116 nums4B each
Slice 216 nums4B each
Slice 316 nums4B each
Slice 416 nums4B each
Uncompressed
Click Step 2 to Compress Into Swatch IDs
[#12#13#11#02... (96 bytes total)]
Query time: add 96 quick swatch-table lookups instead of multiplying 1,536 decimals.
Memory (RAM) Needed for 10 Million Articles
Original Full Numbers (Float32)61.44 GB
Light Rounding (SQ8 · 4x smaller)15.36 GB
Product Quantization (m=96 bytes)1.04 GB
Shrinking 61.44 GB down to 1.04 GB lets 10 million embeddings fit inside a single modest server instead of an expensive memory cluster.
Live Top-5 Search Accuracy Test
Mode: Full exact vectors (61.44 GB RAM)100% match
#1Espresso 9-Bar Crema Emulsion PhysicsTrue Top-5
#2Coffee Bean Roasting Maillard CaramelizationTrue Top-5
#3First Crack Pyrolysis in Coffee DrumsTrue Top-5
#4Cold Brew Low-Acid Chlorogenic DiffusionTrue Top-5
#5Burr Grinder Bimodal Particle SizeTrue Top-5
Showing exact top 5 for "Coffee Caramelization". Click Step 2 above to compress every article into tiny swatch IDs and see what happens.
💡 Insight

Gentler & extreme cousins (SQ8 and Binary Quantization): Want simpler compression with almost zero accuracy drop? Scalar Quantization (SQ8) rounds each decimal into an 8-bit integer (4x less RAM, ~99% accuracy). Want extreme speed? Binary Quantization (BQ) keeps only whether each number is positive or negative (1 bit per number = 32x smaller), then reranks the top candidates from disk!


Production vector search: filtering traps and choosing a stack

In real RAG & AI Agents, users rarely search your entire database blindly. They ask things like “Find our refund policy, but only verified 2026 articles.”

Mixing a regular WHERE filter with a vector search map hides a classic trap:

  • Search first, filter after (Post-filtering): Runs HNSW to grab the 5 closest articles overall, then throws away any that fail your filter. When only 7% of articles pass, all 5 get thrown away and the user sees 0 results!
  • Filter first, scan all passing (Pre-filtering): Finds every matching article first and scans them one by one. Fast when only 7% match, but slow again when 60% match!
  • Check filters while hopping (Filter-Aware HNSW): Modern engines like Qdrant, Weaviate, Milvus, and pgvector 0.8+ check your filter directly during the graph walk, skipping disqualified dots until 5 valid winners are found.

Watch all three strategies play out on the 48-article visual map below, then click the project scenario on the right to see whether pgvector, Qdrant, FAISS, or DiskANN fits best!

Interactive Lab 4: Why Search Filters Break (and Which Tool to Pick)
Part A: Watch How Each Strategy Handles a Filter on 240 Articles
Grabs the 5 closest articles first, then throws away non-matches: Watch the 5 nearest tiles on the left of the visual map below. Red "X" tiles were discarded because they failed your filter, leaving you with almost nothing when the filter is strict!
18/240 pass (8%)
Closest 48 Articles (Left = Closest Match to Your Question)WHERE verified = true AND year = 2026
✓Returned winner×Grabbed then discarded (4)Passes filterFails filter
Returned: 1 / 5 articlesChecks: 35 · Accuracy: 20%
#1Lunar South Pole Shadowed Water Ice: Field Notes2026 · verified
Part B: Which Vector Tool Should You Pick?
Click the situation closest to your project:
pgvector (PostgreSQL)SQL Extension
Under the hood: HNSW + IVFFlat inside Postgres
Why it fits: Startups and teams already running Postgres who want vector search next to normal user tables with zero extra databases to manage.
Watch out for: Keep your HNSW index fitting comfortably in Postgres memory, and enable pgvector 0.8+ iterative scans so strict WHERE filters do not drop results.
Quick cheat sheet: under 100K articles, plain brute force takes <2 ms. From 100K to 50M, HNSW (+ compression) wins. Past 100M, move to DiskANN or sharded IVF-PQ.
See HNSW Layer Math, Search Complexity & Product Quantization ADC EquationsOptional Math

1. HNSW Exponential Layer Assignment (Malkov & Yashunin, 2018): When inserting vector xx, its maximum layer ll is drawn from an exponentially decaying distribution scaled by mL=1/ln⁡(M)m_L = 1 / \ln(M):

l=⌊−ln⁡ ⁣(uniform⁡(0,1))⋅mL⌋,mL=1ln⁡Ml = \left\lfloor -\ln\!\big(\operatorname{uniform}(0, 1)\big) \cdot m_L \right\rfloor, \qquad m_L = \frac{1}{\ln M}

This produces O(log⁡N)\mathcal{O}(\log N) layers with geometrically shrinking node counts, mirroring a probabilistic Skip List so upper-layer greedy descent traverses the space in O(log⁡N)\mathcal{O}(\log N) hops.

2. Diversity-Preserving Neighbor Selection (Heuristic): Rather than linking only to the MM nearest nodes (which traps graphs inside isolated clusters), HNSW adds candidate ee to node qq‘s neighborhood only when ee is closer to qq than to any already-selected neighbor r∈Rr \in R:

d(q,e)<min⁡r∈Rd(e,r)d(q, e) < \min_{r \in R} d(e, r)

3. Product Quantization & Asymmetric Distance Computation (Jégou et al., 2011): Splitting x∈RDx \in \mathbb{R}^D into mm disjoint subvectors x=[x(1),…,x(m)]x = [x^{(1)}, \dots, x^{(m)}] quantized to codebook centroids cj(i)∈RD/mc_{j}^{(i)} \in \mathbb{R}^{D/m} yields squared Euclidean distance approximation via mm scalar table lookups:

d^(q,x)2=∑i=1m∥q(i)−ccodei(x)(i)∥22\hat{d}(q, x)^2 = \sum_{i=1}^{m} \left\| q^{(i)} - c_{\text{code}_i(x)}^{(i)} \right\|_2^2

For unit-normalized vectors (∥q∥2=∥x∥2=1\|q\|_2 = \|x\|_2 = 1), squared L2 distance relates monotonically to cosine similarity via ∥q−x∥22=2(1−cos⁡(q,x))\|q - x\|_2^2 = 2\big(1 - \cos(q, x)\big).

See Production Code: FAISS, Qdrant & PostgreSQL pgvectorOptional Code

1. FAISS (Python research & GPU indexing: HNSW + IVF-PQ):

faiss_hnsw_and_ivfpq.py
python
import faiss
import numpy as np

dim = 1536
xb = np.random.randn(100_000, dim).astype("float32")
faiss.normalize_L2(xb)  # Unit-normalize so Inner Product == Cosine Similarity

# Option A: HNSW (fast sub-ms queries, higher RAM)
hnsw = faiss.IndexHNSWFlat(dim, 16, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 128
hnsw.add(xb)
hnsw.hnsw.efSearch = 64  # Live recall-vs-latency throttle

# Option B: IVF-PQ (compressed 64x smaller RAM for 10M+ vectors)
nlist, m_subspaces, bits = 256, 96, 8
quantizer = faiss.IndexFlatIP(dim)
ivfpq = faiss.IndexIVFPQ(quantizer, dim, nlist, m_subspaces, bits, faiss.METRIC_INNER_PRODUCT)
ivfpq.train(xb)
ivfpq.add(xb)
ivfpq.nprobe = 16

query = xb[:1]
scores, ids = hnsw.search(query, k=5)

2. Qdrant (Dedicated Vector DB with Filtered HNSW + Scalar Quantization):

qdrant_filtered_hnsw.py
python
from qdrant_client import QdrantClient, models

client = QdrantClient(url="http://localhost:6333")

client.create_collection(
  collection_name="knowledge_docs",
  vectors_config=models.VectorParams(size=1536, distance=models.Distance.COSINE),
  hnsw_config=models.HnswConfigDiff(m=16, ef_construct=128),
  quantization_config=models.ScalarQuantization(
      scalar=models.ScalarQuantizationConfig(type=models.ScalarType.INT8, always_ram=True)
  ),
)

# Filter-aware HNSW + oversampling + automatic exact rescoring
hits = client.query_points(
  collection_name="knowledge_docs",
  query=query_vector,
  query_filter=models.Filter(
      must=[
          models.FieldCondition(key="verified", match=models.MatchValue(value=True)),
          models.FieldCondition(key="year", range=models.Range(gte=2025)),
      ]
  ),
  search_params=models.SearchParams(
      hnsw_ef=64,
      quantization=models.QuantizationSearchParams(rescore=True, oversampling=3.0),
  ),
  limit=5,
)

3. PostgreSQL pgvector (HNSW Index + Iterative Filtered Scan):

pgvector_hnsw.sql
sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE documents (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
verified BOOLEAN NOT NULL DEFAULT false,
year INT NOT NULL,
embedding vector(1536)
);

-- Build an HNSW cosine index with M = 16, ef_construction = 128
CREATE INDEX documents_embedding_hnsw
ON documents USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 128);

-- Tune ef_search and enable iterative scans (pgvector 0.8+) for strict WHERE filters
SET hnsw.ef_search = 64;
SET hnsw.iterative_scan = relaxed_order;

SELECT id, title, 1 - (embedding <=> $1::vector) AS cosine_similarity
FROM documents
WHERE verified = true AND year >= 2025
ORDER BY embedding <=> $1::vector
LIMIT 5;

Next up in Path 05: Modern AI & LLMs: plug your vector database straight into an LLM prompt alongside keyword search and tool-calling loops in RAG & AI Agents!

✓ Self-Check

Quick Intuition Check

Four quick real-world scenarios to lock in what you just saw. No grades, just intuition.

1

Why does HNSW stack sparse upper floors (Floor 2 and Floor 1) above the ground-floor meaning map (Floor 0)?

Pick an option first, or peek anytime
2

Your HNSW search is super fast (1.2 ms), but top-5 accuracy slipped to 84% on tricky questions. Which dial can you turn up right now WITHOUT rebuilding the map?

Pick an option first, or peek anytime
3

You shrank 10 million embeddings from 61 GB down to ~1 GB using Product Quantization swatch IDs, and accuracy dipped from 100% to 80%. How do production apps recover ~100% accuracy while keeping the RAM savings?

Pick an option first, or peek anytime
4

Searching for the 5 closest articles first and applying a strict filter afterward (post-filtering for 'verified 2026 articles') reliably returns 5 good results.

Pick an option first, or peek anytime
Quick Reference

Common Questions

What is a vector database in AI?
A vector database is a specialized data store built to index and search high-dimensional numerical embeddings (such as 1,536-dimensional text or image vectors) by semantic similarity rather than exact keyword or SQL equality. It pairs Approximate Nearest Neighbor (ANN) indexes like HNSW or IVF with metadata filtering, persistence, and horizontal scaling for RAG and semantic search.
How do vector databases work under the hood?
First, an embedding model converts each document, image, or product into a dense vector of numbers. Instead of scanning every stored vector on every query (which scales linearly as O(N)), the database builds a smart search structure such as a multi-layer HNSW proximity graph or IVF Voronoi clusters so queries evaluate only a tiny fraction of vectors while returning near-exact top-K matches.
What is the HNSW algorithm and why is it so fast?
HNSW (Hierarchical Navigable Small World, Malkov and Yashunin 2018) is a multi-layer proximity graph modeled like a 3D skip list. Sparse upper layers carry long-range express links across the whole vector space, while the dense bottom layer (Layer 0) connects local semantic neighbors. A query starts at the top, hops rapidly across clusters, drops vertically to finer layers, and runs a local beam search controlled by efSearch in roughly O(log N) distance checks.
HNSW vs. IVF: which vector index should I choose?
Choose HNSW when you want the fastest sub-millisecond query latency and highest Recall@K (95% to 99%+) and have enough RAM to hold the graph edges alongside your vectors. Choose IVF (especially IVF-PQ) when memory budget is tight, index build times must stay fast on massive datasets, or you can tolerate slightly higher query latency by tuning nprobe.
What is product quantization (PQ) in vector search?
Product Quantization compresses high-dimensional float32 vectors by 16x to 64x by splitting each vector into m independent subvectors and replacing each subvector with a single 1-byte ID pointing to its nearest learned K-Means centroid. At query time, Asymmetric Distance Computation (ADC) approximates distances using fast lookup-table additions, and oversampling plus exact float32 reranking recovers near-100% Recall@K.
Is FAISS a vector database, and how does it compare to Qdrant or pgvector?
No: FAISS (Facebook AI Similarity Search) is a high-performance C++/Python indexing library for in-memory and GPU nearest-neighbor search, not a full database. It lacks built-in CRUD persistence, crash recovery, replication, and rich metadata filtering out of the box. Dedicated vector databases (Qdrant, Milvus, Weaviate) or Postgres extensions (pgvector) wrap ANN algorithms like HNSW with storage durability, hybrid filtering, and production APIs.

Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference

https://seeingml.com/learn/vector-databases/ Open GitHub issue Suggest an edit
Cite this guide in a paper, thesis, or course (BibTeX & APA)
BibTeX
@misc{irshad2026vectordatabases,
  author       = {Irshad, Muhammad Aashir},
  title        = {Vector Databases & HNSW: Interactive Visual Guide},
  howpublished = {SeeingML},
  year         = {2026},
  month        = {dec},
  url          = {https://seeingml.com/learn/vector-databases/},
  note         = {Interactive visual guide}
}
APA

Irshad, M. A. (2026). Vector Databases & HNSW: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/vector-databases/