Modern AI & LLMs Guide 6 of 7 · tap to switch
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.
First, forget 3D layers: meet the Meaning Map
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):
efSearch(Search thoroughness at query time): Your live speed-vs-accuracy dial! RaisingefSearchchecks more nearby ground-floor streets and prevents missed matches; lowering it speeds up every query immediately.M(Links per article): HigherM(typically16to32in production) builds more highway bridges for higher accuracy, at the cost of extra RAM per article (~2Medges on Floor 0).efConstruction(Map-building effort): Controls how carefully HNSW picks diverse bridges once when adding articles to the library. Higher values (100to200) build a cleaner map with zero extra RAM cost at query time.
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!
| Index Family | Query Speed | Top-5 Accuracy | Memory (RAM) Cost | Best Everyday Fit |
|---|---|---|---|---|
| Flat (Brute Force) | Slow past ~100K articles | 100% exact | 1.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 reads | High (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:
- Slice each long list of numbers into short chunks: Cut a 1,536-number vector into
mshort slices (for example,96slices of 16 numbers each). - Build a 256-pattern Swatch Book for each slice: Group common slice patterns into
256reusable prototypes. Because0to255fits in one single byte, you can replace 16 full decimal numbers (64 bytes) with a 1-byte Swatch ID (like#12)! - Store tiny byte codes in RAM: A full
6,144-bytearticle shrinks down to just96 bytes(64x smaller!), dropping 10 million articles from 61.4 GB down to ~1 GB. - 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!
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!
WHERE verified = true AND year = 2026See HNSW Layer Math, Search Complexity & Product Quantization ADC EquationsOptional Math
1. HNSW Exponential Layer Assignment (Malkov & Yashunin, 2018): When inserting vector , its maximum layer is drawn from an exponentially decaying distribution scaled by :
This produces layers with geometrically shrinking node counts, mirroring a probabilistic Skip List so upper-layer greedy descent traverses the space in hops.
2. Diversity-Preserving Neighbor Selection (Heuristic): Rather than linking only to the nearest nodes (which traps graphs inside isolated clusters), HNSW adds candidate to node ‘s neighborhood only when is closer to than to any already-selected neighbor :
3. Product Quantization & Asymmetric Distance Computation (Jégou et al., 2011): Splitting into disjoint subvectors quantized to codebook centroids yields squared Euclidean distance approximation via scalar table lookups:
For unit-normalized vectors (), squared L2 distance relates monotonically to cosine similarity via .
See Production Code: FAISS, Qdrant & PostgreSQL pgvectorOptional Code
1. FAISS (Python research & GPU indexing: HNSW + IVF-PQ):
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):
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):
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!
Quick Intuition Check
Four quick real-world scenarios to lock in what you just saw. No grades, just intuition.
Why does HNSW stack sparse upper floors (Floor 2 and Floor 1) above the ground-floor meaning map (Floor 0)?
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?
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?
Searching for the 5 closest articles first and applying a strict filter afterward (post-filtering for 'verified 2026 articles') reliably returns 5 good results.
Common Questions
What is a vector database in AI?
How do vector databases work under the hood?
What is the HNSW algorithm and why is it so fast?
HNSW vs. IVF: which vector index should I choose?
What is product quantization (PQ) in vector search?
Is FAISS a vector database, and how does it compare to Qdrant or pgvector?
Related Visual Guides
Tokenization & Word Embeddings
How LLMs turn raw text into subword token IDs and map meaning into geometry where King - Man + Woman lands right on Queen.
Euclidean Distance & Cosine Similarity
How recommenders, search engines, and AI embeddings measure closeness, and why high dimensions distort everyday geometry.
K-Nearest Neighbors (KNN Algorithm)
Predict a new example simply by asking its K closest neighbors to vote, and see why choosing K and scaling features make or break the result.
RAG & AI Agents
Give LLMs an open-book library with Retrieval-Augmented Generation (RAG) and real-world hands with ReAct tool-calling AI Agents.
Written & illustrated by Muhammad Aashir Irshad · Updated December 2026 · Free open-access reference
Cite this guide in a paper, thesis, or course (BibTeX & APA)
@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}
} Irshad, M. A. (2026). Vector Databases & HNSW: Interactive Visual Guide. SeeingML. https://seeingml.com/learn/vector-databases/