Vector Databases & Similarity Search

Generative & Agentic AI · Retrieval-Augmented Generation · Advanced · 22 min

Understand how a vector database finds the closest embeddings among millions in milliseconds, pick a distance metric and index, and choose the right AWS vector store.

Millions of glowing dots float in a dark room. You drop a new dot (the question) and a guide hops from dot to dot, always stepping to the neighbour that is closer to yours, until no step gets you closer.

The idea in everyday words

Finding the closest coffee shop by measuring the distance to every coffee shop on Earth would work, but it would take all day. Instead you take the highway to the right city, then main roads to the right neighbourhood, then walk the last few streets. A vector index does the same: big jumps first, small steps at the end.

Why a special database at all?

An embedding is a list of numbers that captures meaning (see the Embeddings lesson). Similar meaning means the vectors point in similar directions.

To answer "which stored chunks are most like this question?" the obvious way is exact kNN (k nearest neighbours): measure the distance from the question to every stored vector, then keep the k smallest.

Tiny example with real sizes:

Stored vectors Dimensions Multiply-adds per query
10,000 1,024 about 10 million (fast)
50,000,000 1,024 about 51 billion (far too slow)

The key idea: exact search costs O(n × d) per query, so at scale we accept "almost the best" in exchange for huge speed. That is ANN (approximate nearest neighbour) search.

We measure how good ANN is with recall@k: of the true top-k, what fraction did the index return? Recall 0.95 means 19 of the true top 20 were found. A vector database is a store that keeps these ANN indexes, updates them as you add data, and lets you filter by metadata.

Distance metrics: cosine, dot product, L2

A metric decides what "close" means.

Metric Formula idea Bigger or smaller is closer? Notes
Cosine similarity angle between vectors bigger (max 1) ignores length, the default for text
Dot product sum of a[i] × b[i] bigger rewards long vectors too
Euclidean (L2) straight-line distance smaller like a ruler in space

Small example: q = [1, 0], a = [1, 0], b = [10, 0]. Cosine says a and b are equally close (same direction). Dot product says b wins (10 vs 1). L2 says a wins (distance 0 vs 9).

The key idea: if vectors are normalised (length 1), all three give the same ranking. Many embedding models (for example Amazon Titan Text Embeddings V2 with normalisation on) output unit vectors, so the choice matters less. Rule: use the metric the embedding model was trained for, and configure the index with that same metric.

A handy trick: for ranking you can skip the square root in L2. Squared distance keeps the same order and is cheaper.

Indexes: HNSW and IVF

HNSW (Hierarchical Navigable Small World) is the most popular ANN index.

  • Every vector is a node in a graph, linked to its nearby vectors.
  • There are several layers. The top layer has only a few nodes with long links (the highways). Each lower layer has more nodes. The bottom layer has every node (the side streets).
  • Search is greedy: start at an entry node on the top layer, hop to whichever neighbour is closer to the query, and when no neighbour is closer, drop one layer and continue.
  • Real HNSW keeps a short list of the best candidates (size efSearch) instead of a single current node. A bigger list means higher recall but slower queries.
  • M = links per node (more links, better recall, more memory). efConstruction = effort spent while building.

Cost: roughly O(log n) hops per query, but the graph lives in memory, so HNSW is fast and memory hungry.

IVF (Inverted File index) clusters the vectors first (k-means into, say, 1,000 groups). A query is compared with the group centres, then only the closest nprobe groups are scanned. Fewer groups scanned = faster but lower recall.

PQ (Product Quantization) compresses vectors into short codes to save memory, at some cost to accuracy. Flat means no index at all: exact search, perfect recall, fine for small sets.

The key idea: every ANN index trades recall for speed and memory, and exposes a knob (efSearch, nprobe) to choose where you sit.

Metadata filtering

Real queries say "similar to this, but only documents from the HR department, written after 2024, that this user is allowed to see".

Each vector is stored with metadata (key/value pairs like dept: "hr", year: 2025, tenant: "acme").

  • Post-filtering: find the top 10 by similarity, then drop the ones that fail the filter. Simple, but you may end up with 2 results, or 0.
  • Pre-filtering / filtered search: restrict the search to matching vectors while walking the index. Better results when the filter is strict. The Amazon OpenSearch k-NN plugin (efficient filtering, depending on the engine) and Qdrant support this.
  • pgvector is a post-filter by default. With an HNSW or IVFFlat index, Postgres pulls about hnsw.ef_search (default 40) candidates from the index, and only then applies your WHERE clause. If only 1% of rows match, a "top 10" query can come back with 0 to 2 rows. Fixes: iterative index scans (pgvector 0.8 and later keep scanning until enough rows pass), a partial index per hot filter value, or partitioning the table by tenant. Check the pgvector README for the current options.

The key idea: filters are a correctness and security feature, not just relevance. For multi-tenant apps, always filter by tenant or user so one customer can never retrieve another customer's chunks.

Go deeper (engineer level)

HNSW knobs and what they cost. M is the number of links per node. Doubling it raises recall on hard queries but roughly doubles the graph's memory and slows inserts. efConstruction is the candidate list size while building: higher gives a better graph and a slower build, with no query-time cost. efSearch is the beam width at query time and must be at least k. Recall rises steeply at first, then flattens, while latency keeps growing, so tune it on a recall@k vs p99 latency curve, not by feel.

Memory maths. 10 million vectors × 1,024 dims × 4 bytes is about 41 GB of raw floats before any graph links. That is why engines offer scalar quantization (int8), binary quantization and product quantization, often with a re-score step on full-precision vectors for the final top k, and disk-based indexes for huge collections.

Filtered search failure modes.

  • Post-filtering under-fills results when the filter is selective (the pgvector case above).
  • Filtering while walking the graph can strand the search: if few nodes match, the allowed nodes may not be connected, recall collapses and latency spikes. Good engines detect a very selective filter and switch to exact search over the matching subset.
  • Per-tenant partitions or indexes avoid both problems, at the price of many small indexes to manage.

Updates and drift. HNSW deletes are usually tombstones, so heavy churn slowly degrades the graph until you rebuild or compact (in Postgres, VACUUM and REINDEX matter). Vectors from two different embedding models are not comparable: switching models means re-embedding everything into a new index, ideally built side by side and swapped behind an alias. Re-measure recall whenever data size or distribution changes, because the efSearch that gave 0.95 at 1 million vectors may not at 50 million.

Step by step

  1. Store:

    Six points A to F live in a 2D space (real embeddings have about 1,024 dimensions, the idea is the same). Each is linked to a few neighbours.

  2. Query arrives:

    The question is embedded to Q = (7, 3). We want the closest stored point.

  3. Start at the entry:

    Greedy search starts at A. Squared distance from A to Q is (0-7)² + (0-3)² = 58.

  4. Hop:

    A's only neighbour B has distance 25 + 4 = 29 < 58, so we move to B.

  5. Hop again:

    B's neighbours: A = 58, C = 18, D = 4. D is best and closer than B, so move to D. Then D's neighbour F has distance 2, so move to F.

  6. Stop:

    F's neighbours are D = 4 and E = 4. Neither beats 2, so the search stops at F. It checked about 9 distances instead of scanning everything.

  7. Filter and return:

    If F failed the metadata filter (wrong tenant), a filtered search would skip it and return the next best allowed point.

Code example

import math

# Tiny "embeddings" (real ones have 256 to 3,072 numbers)
docs = {
    "refund policy":  [0.9, 0.1, 0.0],
    "return an item": [0.8, 0.3, 0.1],
    "shipping times": [0.1, 0.9, 0.2],
    "gift cards":     [0.2, 0.1, 0.9],
}
query = [0.85, 0.2, 0.05]

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def cosine(a, b):
    return dot(a, b) / (math.sqrt(dot(a, a)) * math.sqrt(dot(b, b)))

def l2(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

print("Exact kNN: score EVERY vector (fine for 4, slow for 40 million)")
for name in sorted(docs, key=lambda n: -cosine(query, docs[n])):
    print(f"  {name:15s} cosine={cosine(query, docs[name]):.3f}  L2={l2(query, docs[name]):.3f}")

# Metadata filter: only search what this user may see
meta = {"refund policy": "public", "return an item": "public", "shipping times": "public", "gift cards": "internal"}
allowed = [n for n in docs if meta[n] == "public"]
print("Filtered top-1:", max(allowed, key=lambda n: cosine(query, docs[n])))

# Greedy graph search: the core move inside HNSW
points = {"A": (0, 0), "B": (2, 1), "C": (4, 0), "D": (5, 3), "E": (7, 1), "F": (8, 4)}
graph = {"A": ["B"], "B": ["A", "C", "D"], "C": ["B", "E"], "D": ["B", "F"], "E": ["C", "F"], "F": ["D", "E"]}
q = (7, 3)

def d2(n):
    return (points[n][0] - q[0]) ** 2 + (points[n][1] - q[1]) ** 2

cur, checks = "A", 1
while True:
    best = min(graph[cur], key=d2)
    checks += len(graph[cur])
    print(f"  at {cur} (dist2={d2(cur)}), best neighbour {best} (dist2={d2(best)})")
    if d2(best) >= d2(cur):
        break
    cur = best
print("Greedy search stopped at", cur, "after", checks, "distance checks")

Complexity

  • Time: Exact kNN: O(n × d) to score every vector plus O(n log n) to sort (O(n log k) with a heap). HNSW: roughly O(log n) hops, each checking about M neighbours of d dimensions.
  • Space: Exact: O(n × d) for the vectors. HNSW adds O(n × M) links and usually lives in memory; IVF and PQ trade accuracy for less memory.

Interview tips

  • Explain exact kNN vs ANN in one breath: exact is O(n × d) per query with perfect recall; ANN (HNSW, IVF) is sub-linear and trades a little recall for speed.

  • Be ready to sketch HNSW: layered graph, greedy descent from a sparse top layer, efSearch and M as the recall knobs, high memory use.

  • Say how you would choose on AWS: OpenSearch Serverless for hybrid search with Knowledge Bases, Aurora pgvector if data is already in Postgres, S3 Vectors for huge cheap collections, MemoryDB for the lowest latency.

  • Mention pre-filter vs post-filter and why tenant filters must be enforced in the query, not in the prompt.

  • Know how to evaluate: build a set of real queries, compute exact top-k offline, and measure recall@k and p99 latency of the index.

Challenge: Exact k Nearest Neighbours

Write knn(points, query, k) that returns the indices of the k points closest to query, closest first.

  • Use squared Euclidean distance (sum of (p[i] - q[i])²). All values are integers.
  • Break ties by the smaller index.
  • If k is bigger than the number of points, return all of them.

Example: knn([[0, 0], [1, 1], [5, 5], [2, 2]], [1, 2], 2) → [1, 3] (squared distances are 5, 1, 25, 1).

Solve it in the browser with tests, hints and an AI coach.

Practice problems

More in Retrieval-Augmented Generation

Previous: RAG: Chat With Your Own Documents · Next: Advanced RAG: Chunking, Hybrid Search & Reranking