What Is a Vector Database and How Does It Work?
A vector database stores numeric vectors and retrieves records whose vectors are closest to a query vector under a chosen similarity or distance metric. In retrieval-augmented generation, it uses a question's embedding to find candidate text chunks that can be supplied to a language model as context.

An embedding is a fixed-length array of numbers produced by a model. Its coordinates are learned features rather than named fields such as topic or language. The database stores the array and searches it, but the embedding model determines what closeness means. If the model places two unrelated chunks close together, exact search will faithfully return that poor match.
- Index documents: Split documents into chunks. Convert each chunk into an embedding using the model's document encoding format. Store its vector with a stable ID and any metadata needed for filtering or citation.
- Encode the query: Convert the user's question into a vector using the same model, following its query encoding format. Some retrieval models require different prefixes for queries and documents but still map both into the same vector space.
- Search and fetch: Rank vectors by similarity, return the best
kIDs and scores, and fetch their corresponding text. A retrieval application can re-rank these chunks before passing them to the generator.
| Chunk ID | Text snippet | Illustrative embedding prefix | Metadata |
|---|---|---|---|
| 1 | Introduction to machine learning and its applications | [0.12, -0.34, ...] | section=intro |
| 2 | Types of machine learning: supervised, unsupervised and more | [0.45, 0.11, ...] | section=types |
| 3 | Supervised learning trains on examples with known labels | [-0.22, 0.33, ...] | section=supervised |
For the question “Which approach needs labelled training examples?”, chunk 3 is a plausible result even though it never uses the phrase “training examples” in that order. The table shows only vector prefixes, so you cannot compute the ranking from it. In a retrieval-augmented generation (RAG) system, the index finds candidates. The surrounding application still decides which chunks to trust, how to cite them and whether the evidence is sufficient to answer.
How Does Vector Similarity Search Work? A Worked Example
Let q be a query vector and x be a stored vector, both of dimension d. A search index compares them using one of the following scores. The sort direction matters when you log results or implement a threshold.
| Score | Formula | Best result | What affects it? |
|---|---|---|---|
| Inner product | q · x = Σᵢ qᵢxᵢ | Highest | Direction and vector magnitude |
| Cosine similarity | (q · x) / (||q||₂ ||x||₂) | Highest | Angle between nonzero vectors |
| Squared Euclidean distance | ||q − x||₂² = Σᵢ (qᵢ − xᵢ)² | Lowest | Coordinate differences |
Calculate the top two results by hand
Use q = [1, 0] and three candidate vectors: A = [0.8, 0.6], B = [2, 2] and C = [0.6, -0.8]. The query, A and C have norm 1. B has norm √8. Because the second query coordinate is zero, the inner product is just the first coordinate of each candidate.
| Candidate | Inner product | Cosine similarity | Squared Euclidean distance |
|---|---|---|---|
| A | 0.8 | 0.8 | 0.2² + 0.6² = 0.40 |
| B | 2.0 | 2 / √8 ≈ 0.707 | 1² + 2² = 5.00 |
| C | 0.6 | 0.6 | 0.4² + 0.8² = 0.80 |
For k = 2, inner product returns B then A. Cosine returns A then B. Squared Euclidean distance returns A then C. B's score illustrates why choosing inner product without normalising can change the answer: its large magnitude raises its dot product even though A is better aligned with the query.
If you divide every nonzero vector by its own norm, cosine similarity becomes inner product. For unit vectors, ||q − x||₂² = 2 − 2(q · x), so squared Euclidean distance gives the same ranking too, aside from numerical effects or ties. Start with the metric recommended for your embedding model. If you want cosine search through an inner-product index, normalise both stored vectors and queries and handle zero vectors explicitly. A cosine score of 0.8 is a geometric measurement, not an 80 percent probability that a chunk is relevant.
What Is the Difference Between Exact and Approximate Nearest Neighbour Search?
A flat index scores the query against every stored vector. For N vectors of dimension d, the scoring work scales as O(Nd) per query. The engine can use a top-k selection routine instead of fully sorting all scores. With inner product, a batch of queries can be scored as a matrix multiplication, so exact search can be a practical choice for a small collection or a filter that leaves few candidates.
Approximate nearest neighbour search, or ANN, reduces work by inspecting only some vectors, comparing compressed representations, or combining both. An ANN search can return a plausible result while missing a closer vector elsewhere in the index. The main question is how much recall it gives up at your latency and memory budget.
To measure this trade-off, search the same corpus and queries with both a flat index and the ANN index. If the exact top four IDs are [12, 8, 31, 5] and the ANN returns [12, 31, 9, 5], then Recall@4 = 3/4 = 0.75 for that query. ID 8 was missed. This metric counts overlap, so it gives no extra credit for returning ID 12 first. Keep the metric, filters and corpus snapshot identical in both runs. When a filter leaves fewer than k eligible results, use the size of the exact result set as the denominator and track empty queries separately.
Raw vector storage is another baseline. One million 768-dimensional vectors in float32 occupy 1,000,000 × 768 × 4 = 3,072,000,000 bytes, about 3.07 GB in decimal units. That excludes graph links, IDs, payloads, replicas and temporary working memory. An index that fits on disk can still exceed the machine's memory budget when it is loaded and queried.
How Does HNSW Search Find Nearest Neighbours?
Hierarchical Navigable Small World (HNSW) organises vectors into layers of proximity graphs. Every vector has a node in the base layer. Successively higher layers contain smaller subsets of the nodes. Graph construction connects each inserted node to selected nearby nodes and limits the number of retained edges. The upper layers help the search move across the graph before spending more work near a promising region.
- Start at an entry node in the highest layer. Compare its neighbours with the query and move to a closer node when one is available.
- When greedy progress stops, descend a layer from the current node. Repeat until reaching the base layer.
- At the base layer, maintain a bounded set of promising candidates. Expand promising nodes by scoring their unvisited neighbours, then return the best
kresults found.
Three settings control much of the cost. M controls graph connectivity; increasing it generally adds edges, increasing memory use and build work. efConstruction controls how broadly insertions explore the graph before selecting edges. efSearch controls the breadth of query-time exploration, so it can usually be changed without rebuilding the graph. Set a query breadth at least as large as k when the implementation expects that relationship, then measure how additional breadth affects recall and latency.
Search only discovers nodes through links it follows. If construction leaves poor routes into a neighbourhood, a narrow search can miss its closest vectors. Raising efSearch may help, while changing graph connectivity generally requires a rebuild. Filters add another complication: a node that is ineligible as a result may still be useful for navigating towards eligible neighbours. Engines differ in how they handle that, so measure filtered recall separately from unrestricted recall.
How Does IVF Search Find Nearest Neighbours?
An Inverted File index (IVF) partitions vectors into lists. First, it fits a coarse quantiser, typically by clustering a representative sample into nlist centroids. Then it assigns each corpus vector to a centroid and adds the vector's ID and representation to that centroid's list. At query time it chooses the nprobe most promising centroids and searches their lists.

Suppose one million vectors are split into 1,000 equally sized lists. Probing 10 lists would score roughly 10,000 stored vectors, plus the work of choosing the lists. Real lists are uneven, so the number of candidates can vary between queries at the same nprobe. The nearest vector can also sit just across a partition boundary in an unprobed list. Raising nprobe reduces this risk at the cost of scanning more candidates.
| Index | What gets scored? | Main tuning or resource cost |
|---|---|---|
| Flat | Every stored vector | Scan time grows with corpus size and dimension |
| HNSW with full vectors | Vectors reached through graph traversal | Graph memory, build effort and query breadth |
| IVF-Flat | Full vectors in the probed lists | Centroid training and number of lists probed |
| IVF-PQ | Compressed vector codes in the probed lists | Code size, quantisation error and number of lists probed |
In IVF-Flat, the score for each visited vector is exact under the chosen metric, up to floating-point effects. At nprobe = nlist, it can recover the flat ranking, assuming no scan cap or filter difference. In IVF-PQ, product quantisation splits vectors into subvectors and encodes each using a learned codebook. Many IVF-PQ implementations encode the residual from the coarse centroid. Searching all lists still leaves quantisation error. If you retain the original vectors, you can re-score the returned candidates precisely, but re-scoring cannot recover an ID missing from the candidate set.
How Do You Build and Measure a Vector Index with FAISS?
FAISS is a similarity search library, not a complete database service. The following example uses the Python packages faiss-cpu and numpy. It compares an exact flat index with IVF-Flat and HNSW on unit-normalised synthetic vectors. Synthetic data makes the experiment repeatable in setup, but its measured recall does not predict performance on your document embeddings.
import faiss
import numpy as np
rng = np.random.default_rng(42)
d, n, nq, k = 64, 6000, 100, 10
nlist = 32
# FAISS expects contiguous float32 matrices: one vector per row.
xb = rng.standard_normal((n, d), dtype=np.float32)
xq = rng.standard_normal((nq, d), dtype=np.float32)
faiss.normalize_L2(xb)
faiss.normalize_L2(xq)
# Normalised inner product gives cosine similarity.
flat = faiss.IndexFlatIP(d)
flat.add(xb)
exact_scores, exact_ids = flat.search(xq, k)
def mean_recall_at_k(found_ids, reference_ids):
recalls = []
for found, reference in zip(found_ids, reference_ids):
expected = set(reference.tolist()) - {-1}
retrieved = set(found.tolist()) - {-1}
if expected:
recalls.append(len(retrieved & expected) / len(expected))
return float(np.mean(recalls))
# The coarse quantiser routes vectors and queries to IVF lists.
quantiser = faiss.IndexFlatIP(d)
ivf = faiss.IndexIVFFlat(
quantiser, d, nlist, faiss.METRIC_INNER_PRODUCT
)
ivf.train(xb) # Learn centroids before inserting vectors.
ivf.add(xb)
for nprobe in (1, 4, 16, nlist):
ivf.nprobe = nprobe
_, ids = ivf.search(xq, k)
recall = mean_recall_at_k(ids, exact_ids)
print(f"IVF nprobe={nprobe:2d} Recall@{k}={recall:.3f}")
# HNSW-Flat builds a graph over full vectors without centroid training.
hnsw = faiss.IndexHNSWFlat(d, 16, faiss.METRIC_INNER_PRODUCT)
hnsw.hnsw.efConstruction = 80
hnsw.add(xb)
for ef in (16, 32, 64, 128):
hnsw.hnsw.efSearch = ef
_, ids = hnsw.search(xq, k)
recall = mean_recall_at_k(ids, exact_ids)
print(f"HNSW efSearch={ef:3d} Recall@{k}={recall:.3f}")
print("Exact IDs for query 0:", exact_ids[0])
print("Cosine scores for query 0:", exact_scores[0])
Each search returns two arrays with shape (nq, k): scores and IDs. Here the IDs are insertion positions because every index receives the same rows in the same order. In an application, use a stable mapping to document and chunk IDs, or use an index setup that accepts explicit IDs. FAISS can return -1 when it cannot fill a result slot. Discard those IDs before fetching text; in Python, indexing a list with -1 would otherwise fetch its last item.
To turn this example into a benchmark, replace xb with corpus embeddings and xq with held-out questions. Train IVF on a representative sample of corpus vectors. Measure p50 and p95 latency with a fixed thread count and query batch size. A single timed call over all 100 queries measures batch service time, not the latency distribution for 100 independent requests.
Which Vector Database Should You Use for RAG?
Use a library such as FAISS when you want local control over the index and can implement persistence, metadata lookups and updates around it. Pinecone, Weaviate, Chroma and Milvus are vector database products or systems with their own storage and query interfaces. Compare their deployment options, filter semantics, supported index types, update and delete behaviour, and backup and recovery options. An index benchmark alone does not compare those features.
Define the query path before selecting an index. If a learner may see only course material assigned to their account, search must respect that access rule. Where supported, constrain the candidate set by tenant and permissions before or during retrieval, and authorise records before returning them. Retrieving ten global candidates and then discarding unauthorised matches can return fewer than ten even if many eligible chunks exist. Test common filters and rare filters separately because selectivity changes the work the engine must do.
Evaluate two kinds of recall. ANN recall asks whether the index recovers the neighbours that exact search would return. Task recall asks whether retrieval returns evidence needed to answer the question. If neither flat search nor ANN retrieves the correct paragraph, tuning efSearch cannot fix a flat-search miss. Inspect the chunking, embedding and re-ranking pipeline instead. For queries containing exact identifiers such as error codes, compare dense search against lexical search or combine both, since a dense embedding can blur distinctions between near-identical strings.
Finally, record the embedding model version, dimension, metric and normalisation policy with each index build. Matching dimensions do not make vectors from different models comparable. If you switch models, build a new index from re-embedded chunks and evaluate it before redirecting traffic. Pair retrieval tests with evaluation of the generated answers: a good top-k result set still needs to be used accurately by the language model.
Key Takeaways
- A vector database retrieves records by numerical similarity. The embedding model determines which relationships the vectors preserve.
- To perform cosine search with an inner-product index, L2-normalise nonzero vectors on both sides.
- Use flat search as an exact reference before deciding how much recall to trade for lower latency.
- HNSW explores a layered graph, while IVF scans selected centroid lists.
efSearchandnprobecontrol query-time work. - FAISS supplies index implementations. A database system also needs to handle data lifecycle, metadata and operational requirements.
- Measure ANN recall, filtered latency and retrieval quality on real questions before tuning the index for production.
Frequently Asked Questions
Is FAISS a vector database?
FAISS is a library for indexing and searching dense vectors. It includes index training, nearest neighbour search and index serialization. A database service typically adds record storage, metadata filtering, access control and operational features such as backups. You can use FAISS as the search component inside a system that provides those capabilities.
When should I use HNSW instead of IVF?
Try HNSW when you can keep its graph and vectors in memory and want low query latency at high recall. Test IVF when scanning selected partitions fits your workload, especially if you also want to evaluate compressed vector codes. Compare both on your corpus because memory limits, filters and query patterns can change the result.
Does increasing top-k improve RAG answers?
Increasing top-k can recover supporting evidence that a shorter list would omit. It can also increase prompt length and introduce distracting passages. Tune candidate count separately from the number of chunks sent to the generator. Measure whether answer quality improves after re-ranking and removing near-duplicate chunks, rather than assuming a larger context helps.
Can I store embeddings from different models in the same index?
Use separate searchable partitions or indexes unless the models were designed or validated to share the same embedding space. Equal vector dimensions only mean the arrays have the same length. A model upgrade normally requires re-embedding the corpus and switching the query encoder at the same time as the index.
Why do two systems return different scores for the same vectors?
They may use different metrics or score conventions. One can return cosine similarity, another can return one minus cosine similarity as a distance, and a Euclidean index can report squared distance. Check normalisation, score direction and precision before comparing values. A tiny score difference near a tie can also change the returned order.