What is vector search and how does HNSW work?
Vector search finds the stored vectors closest to a query vector under a similarity measure such as cosine similarity, dot product, or Euclidean (L2) distance. The vectors are usually embeddings, so "closest" means "most similar in meaning". Exact search compares the query with every stored vector, which is too slow for millions of items, so practical systems use approximate nearest neighbour (ANN) indexes such as HNSW, IVF, and product quantization.
Vector search is the retrieval step in retrieval-augmented generation (RAG): a question is embedded, the nearest document chunks are fetched, and an LLM answers from them. The same operation powers semantic search, recommendation, image search, deduplication, and anomaly detection. Libraries such as FAISS and hnswlib, and vector databases built on them, return the top results from hundreds of millions of vectors in milliseconds by searching only a tiny fraction of the data.
Key ideas
- Vector search returns the k stored vectors most similar to a query, usually embeddings compared by cosine, dot product, or L2 distance.
- Exact search costs one distance per stored vector, so its cost grows linearly with the size of the collection.
- On normalized vectors, cosine similarity, dot product, and L2 distance produce the same ranking.
- Approximate indexes trade a small loss in recall@k for search that is tens to thousands of times faster.
- HNSW builds a layered proximity graph and searches it greedily from a sparse top layer down to a dense bottom layer, with ef controlling the beam width.
- IVF limits the search to a few k-means clusters, and product quantization compresses each vector to a few bytes so billions of vectors fit in memory.
Short takes on this topic
Common questions
What is a vector database?
A vector database stores embeddings alongside their source records and serves nearest-neighbour queries through an ANN index, usually HNSW or IVF. It adds the features of a database around the index: inserts and deletes, metadata filters, persistence, replication, and access control. Many relational and search engines, such as PostgreSQL with pgvector and Elasticsearch, now offer vector indexes too.
Is HNSW better than IVF?
HNSW usually gives higher recall at a given latency and needs no training step, but it keeps the full vectors and graph links in memory. IVF needs a k-means training pass and is often combined with product quantization, which makes it far more memory-efficient at billion scale. The right choice depends on collection size, memory budget, and how often the data changes.
How do you choose ef and M for HNSW?
M sets how many links each node keeps, so a larger M raises recall and memory use together. efConstruction controls build quality, and ef at query time controls the recall and latency trade-off. A common approach is to fix M and efConstruction, then raise ef until recall@k on a held-out set of queries with exact answers reaches the target.
Can you filter vector search results by metadata?
Yes, but filtering interacts with the index. Post-filtering searches first and then drops non-matching results, which can return fewer than k items when the filter is strict. Pre-filtering or filter-aware graph traversal restricts the search to matching items, and most vector databases implement one of these strategies.
Related explainers
- Embeddings — Turning words and categories into vectors
- Norms & Distance Metrics — L1, L2, cosine similarity — measuring closeness in vector spaces
- K-Nearest Neighbors — Classification by proximity and distance metrics
- K-Means Clustering — Unsupervised grouping by centroid distance
- Retrieval-Augmented Generation — Ground language model outputs in retrieved documents to reduce hallucination
- Quantization — Shrinking model weights to 8 and 4 bits
References
- Malkov & Yashunin (2016), "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs"
- Jégou, Douze & Schmid (2011), "Product Quantization for Nearest Neighbor Search"
- Johnson, Douze & Jégou (2017), "Billion-scale similarity search with GPUs"
- Douze et al. (2024), "The Faiss library"
Last updated