How Vector Databases Work
Vector databases find similar items by comparing embeddings. How HNSW and IVF indexes work, the recall trade-off, filtering, and how to choose one.
A vector database stores data as embeddings, which are lists of numbers that capture meaning, and answers one main question: which stored items are closest to this one? Instead of matching exact words, it measures distance between vectors, so a search for "laptop won't charge" can find a document titled "battery not detected." To do that quickly across millions of items, vector databases use approximate nearest neighbor indexes such as HNSW, which trade a small amount of accuracy for very large speed gains.
From data to vectors
Everything starts with an embedding model. You feed it a piece of text (or an image, or audio), and it returns a fixed-length vector. The model is trained so that items with similar meaning produce vectors that sit close together.
That idea was proven out for search by Dense Passage Retrieval (DPR) in 2020. Its authors showed that learned dense vectors alone could beat the classic BM25 keyword method by 9 to 19 percentage points on top-20 passage retrieval accuracy across several open-domain question-answering datasets [10]. That result helped make embeddings the default for semantic search and for retrieval-augmented generation.
A vector database doesn't create meaning; the embedding model does. The database's job is to store those vectors, search them fast, and keep them alongside the metadata and filters an application needs.
Measuring "close"
Three distance measures cover most use cases:
Measure | What it compares | Typical note |
|---|---|---|
Euclidean (L2) | Straight-line distance between two points | Smaller is closer |
Inner (dot) product | How much two vectors point the same way, scaled by length | Larger is closer |
Cosine | The angle between vectors, ignoring length | Equivalent to inner product on normalized vectors |
Use whichever your embedding model was trained for; its documentation usually says. In pgvector, for example, these appear as SQL operators: <-> for L2 distance, <#> for negative inner product, and <=> for cosine distance [6]. Faiss notes that its inner-product index also handles cosine similarity if you normalize vectors first [5].
Why exact search doesn't scale
The simplest approach is to compare the query with every stored vector and keep the best matches. That's called flat or brute-force search, and it's exact. Faiss offers it as IndexFlatL2 and IndexFlatIP [5], and pgvector uses exact search by default, with perfect recall, until you add an index [6].
The problem is cost. Every query touches every vector, so the work grows linearly with the collection. Weaviate's documentation says its flat index suits small collections but "does not scale well to large collections" for exactly this reason [8].
The fix is approximate nearest neighbor (ANN) search: build an index that lets you examine only a small, promising fraction of the vectors. You give up a guarantee of finding the true nearest neighbors in exchange for speed. The fraction of true neighbors an ANN search actually returns is called recall, and almost every tuning knob in a vector database moves you along a speed-versus-recall curve.
How HNSW works
Hierarchical Navigable Small World (HNSW) graphs, described by Yury Malkov and Dmitry Yashunin in a paper first posted in 2016 [1], are a widely implemented ANN index: pgvector, Weaviate and Faiss all offer it [6][8][5].
Think of it as a multi-level road map:
- Every vector is a node in a graph, linked to a handful of its near neighbors.
- There are several layers. The bottom layer contains every node. Each higher layer contains a random, shrinking subset. The paper assigns each element's top layer randomly, with an exponentially decaying probability, so upper layers are sparse [1].
- Search starts at the top. The query lands at an entry point on the sparsest layer and greedily hops to whichever neighbor is closer to the query. When it can't get closer, it drops down a layer and repeats with more detail.
- The bottom layer finishes the job, exploring a candidate list around the query to return the k best matches.
Upper layers act like highways that cover long distances in a few hops; lower layers are local streets. The authors report that this structure gives logarithmic scaling of search complexity [1].
The knobs
The hnswlib reference implementation documents three main parameters [2]:
- M: how many links each new node gets. Higher M improves recall, especially for high-dimensional data, but costs memory, which hnswlib puts at roughly M Γ 8 to 10 bytes per stored element for the links alone. It suggests 12 to 48 for most uses.
- ef_construction: how widely the builder searches when inserting a node. Higher values build a better graph, more slowly.
- ef (or ef_search): how many candidates a query keeps in play. Higher values raise recall and slow queries. It must be at least k.
pgvector exposes the same ideas as m (default 16), ef_construction (default 64) and the query setting hnsw.ef_search (default 40) [6].
HNSW has practical quirks. Faiss notes that its HNSW index doesn't support removing vectors [5]. Weaviate notes that HNSW lives in memory, so memory grows with the number of vectors [8].
How IVF works
The other classic family is the inverted file index (IVF). It works more like sorting mail into bins:
- Train by clustering a sample of vectors into
nlistgroups, each with a center point (centroid). - Assign every vector to its nearest centroid's list.
- Search by finding the few centroids closest to the query, then scanning only those lists. The number of lists scanned is
nprobe, set at query time [5].
More probes means higher recall and slower queries. Faiss's wiki suggests sizing nlist around a constant times the square root of the number of vectors [5]. pgvector's IVFFlat offers lists and ivfflat.probes, recommends starting with rows/1000 lists for up to a million rows, and advises creating the index after the table has data, because the clusters are learned from it [6].
pgvector's README summarizes the trade-off: HNSW has a better speed-recall balance but builds more slowly and uses more memory; IVFFlat builds faster and uses less memory but has lower query performance [6].
Compression: fitting more vectors in memory
A 1,024-dimension vector stored as 32-bit floats takes 4 KB. Faiss documents flat storage as 4 Γ d bytes per vector [5]. At hundreds of millions of vectors, memory becomes the bottleneck. Quantization shrinks vectors at some cost to accuracy:
- Product quantization (PQ) splits each vector into sub-vectors and replaces each with a short code. Faiss's
IndexIVFPQcombines it with IVF, storing roughly M Γ nbits / 8 + 8 bytes per vector [5]. - Scalar quantization stores each number in fewer bits, such as 8-bit integers or 16-bit floats [5].
- Half-precision and binary types do similar work at the database level. pgvector offers
halfvecandbittypes alongsidevector[6].
Systems often store compressed vectors for the fast first pass, then rescore the best candidates against full-precision vectors. Weaviate describes this rescoring step for one of its compressed index types [8].
GPUs are another lever. A 2017 paper on GPU similarity search by Jeff Johnson, Matthijs Douze and HervΓ© JΓ©gou, who are also among the Faiss library's authors [3], reported building a k-nearest-neighbor graph linking 1 billion vectors in under 12 hours on four GPUs [4].
Index types compared
Index | How it narrows the search | Exact? | Training step | Main trade-off |
|---|---|---|---|---|
Flat | Doesn't; scans everything | Yes | No | Simple and exact, slow at scale |
HNSW | Navigates a layered neighbor graph | No | No | Strong speed-recall, more memory, slower builds |
IVF | Scans only the nearest clusters | No | Yes (clustering) | Less memory, recall depends on probes |
IVF + PQ | Nearest clusters, compressed codes | No | Yes | Much smaller, lower accuracy without rescoring |
Sources: Faiss wiki [5], pgvector [6], Weaviate [8].
What makes it a database
A library like Faiss gives you indexes. A vector database wraps them with the things applications need:
- Metadata and filtering. Real queries say "similar to this, but only from the 2026 policy set, and only documents this user can see." Pinecone stores metadata as flat JSON and supports operators such as
$eq,$inand$gt[7]. - Partitioning and multitenancy. Pinecone partitions records into namespaces, often one per customer [7]. pgvector suggests partial indexes or partitioning for filters with few distinct values, and list partitioning or separate tables for tenant isolation [6]. Weaviate suggests its flat index for small per-tenant collections [8].
- Hybrid search. Many systems combine vector search with keyword search. Weaviate runs vector and BM25F searches and fuses the two result sets, weighted by an
alphaparameter [9]. Pinecone's documentation describes combining a keyword or sparse signal with a dense one at query time [7]. - Durability and operations. Writes, updates, backups, replication. This is where a vector extension to a database you already run, such as Postgres, has an advantage: pgvector stores vectors next to your other data with ACID transactions, point-in-time recovery and joins [6].
The filtering trap
Filtering and ANN indexes don't always mix cleanly. pgvector's documentation is candid about it: with approximate indexes, filters are applied after the index scan, so a selective filter can return fewer rows than you asked for [6]. Since version 0.8.0, pgvector offers iterative index scans that keep searching until enough rows pass the filter [6]. Filtering strategies differ between databases, so whichever you use, test filtered queries specifically, because that's where recall quietly drops.
Write access is the other operational point to watch, particularly as AI agents gain tools that can modify data stores. The risk is illustrated by a separate incident we covered, in which an AI coding agent deleted a database. Scope credentials for retrieval to read-only where you can.
Dedicated vector database or extension?
If you⦠| Consider | Why |
|---|---|---|
Already run Postgres and have up to a moderate number of vectors | pgvector | One system, SQL joins, transactions, existing backups [6] |
Need managed scaling, namespaces and hybrid search without running infrastructure | A managed vector service such as Pinecone | Operations handled by the provider [7] |
Want an open-source database with built-in hybrid search and several index types | A system such as Weaviate | Flat, HNSW and dynamic indexes; BM25 fusion [8][9] |
Need full control inside your own service, or research-grade tuning | A library such as Faiss | Many index types and GPU support; you build the database around it [3][5] |
This table reflects the documented feature sets as of November 2026, not performance testing. Benchmark with your own data, filters and recall target before committing.
How to choose and tune
- Fix your embedding model first. Dimension, distance measure and quality all flow from it, and changing it later means re-embedding everything.
- Set a recall target. Build a small ground-truth set using exact search, then measure what fraction of true neighbors your ANN settings return.
- Tune at query time first.
ef_searchorprobescan be changed per query without rebuilding [2][6]. - Test with your real filters and tenants. Filtered recall is the most common surprise.
- Plan memory. Vector count Γ dimension Γ bytes per number, plus graph links for HNSW. Decide early whether you need quantization.
Outlook
Vector search has moved from a specialized system into a feature that general-purpose databases ship. As of November 2026, pgvector's README lists version 0.8.7 [6], and Pinecone's documentation describes schema-based "document" indexes that combine dense vectors, sparse vectors and full-text fields in one place, alongside its earlier vector-only indexes [7]. Expect the dividing lines between "vector database," "search engine" and "regular database" to keep blurring, with the real differences showing up in filtering, scale and operations.
Frequently asked questions
What is an embedding?
An embedding is a list of numbers that an AI model produces to represent a piece of content. Models are trained so that similar content produces nearby vectors. A vector database stores and searches those lists; it doesn't create them.
Is a vector database required for RAG?
No. RAG needs a retrieval step, and that can be a vector database, a vector extension such as pgvector, a library such as Faiss, or keyword search. Very small collections can even skip retrieval and go straight into a long prompt. See our RAG explainer.
Why are results "approximate"?
ANN indexes like HNSW and IVF only examine part of the collection to stay fast, so they can occasionally miss a true nearest neighbor. You control how often through parameters like ef_search or nprobe, trading speed for recall [2][5].
What's the difference between HNSW and IVF?
HNSW navigates a layered graph of neighbors and generally gives a better speed-recall balance, at the cost of memory and build time. IVF clusters vectors and searches only the nearest clusters, which uses less memory but usually needs more tuning for the same recall [6].
How many dimensions can I store?
It depends on the system. As of November 2026, pgvector's vector type stores up to 16,000 dimensions but can index up to 2,000; its halfvec type can index up to 4,000 [6]. Check your chosen database's limits against your embedding model.
Sources
- Malkov, Y. A. and Yashunin, D. A. "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs." arXiv:1603.09320. https://arxiv.org/abs/1603.09320
- hnswlib. "HNSW algorithm parameters." https://github.com/nmslib/hnswlib/blob/master/ALGO_PARAMS.md
- Douze, M. et al. "The Faiss library." arXiv:2401.08281. https://arxiv.org/abs/2401.08281
- Johnson, J., Douze, M. and JΓ©gou, H. "Billion-scale similarity search with GPUs." arXiv:1702.08734. https://arxiv.org/abs/1702.08734
- Faiss wiki. "Faiss indexes." https://github.com/facebookresearch/faiss/wiki/Faiss-indexes
- pgvector. README. https://github.com/pgvector/pgvector
- Pinecone. "Indexing overview." https://docs.pinecone.io/guides/index-data/indexing-overview
- Weaviate. "Vector indexing." https://docs.weaviate.io/weaviate/concepts/vector-index
- Weaviate. "Hybrid search." https://docs.weaviate.io/weaviate/search/hybrid
- Karpukhin, V. et al. "Dense Passage Retrieval for Open-Domain Question Answering." EMNLP 2020. arXiv:2004.04906. https://arxiv.org/abs/2004.04906