Vector search: ANN, FAISS and pgvector

Exact versus approximate nearest-neighbour search, HNSW and IVF, filtering, and when a database beats a library.

Intermediate about 5 h

The picture

  1. 01

    Vectors

    N × d

  2. 02

    Index

    flat, HNSW, IVF

  3. 03

    Query

    k nearest

  4. 04

    Filter

    metadata, ACL

  5. 05

    Tune

    recall vs latency

Exact search first

For up to a few hundred thousand vectors, exact brute-force search is fast and has perfect recall. Start there.

import numpy as np
def knn(D, q, k=5):
    scores = D @ q                          # unit vectors, so dot = cosine
    idx = np.argpartition(-scores, k)[:k]
    return idx[np.argsort(-scores[idx])]

At millions of vectors, exact search is too slow, so you trade a little recall for a lot of speed with an approximate index.

import faiss, numpy as np
d = D.shape[1]

flat = faiss.IndexFlatIP(d)                 # exact inner product
flat.add(D.astype("float32"))

hnsw = faiss.IndexHNSWFlat(d, 32, faiss.METRIC_INNER_PRODUCT)   # M = 32 links per node
hnsw.hnsw.efConstruction = 200
hnsw.add(D.astype("float32"))
hnsw.hnsw.efSearch = 64                     # raise for higher recall, slower queries

Q = queries.astype("float32")
_, truth = flat.search(Q, 10)
_, approx = hnsw.search(Q, 10)
recall = np.mean([len(set(a) & set(t)) / 10 for a, t in zip(approx, truth)])
print("recall@10 vs exact:", recall)
  • HNSW builds a layered proximity graph. M (links per node) and efConstruction set index quality and memory; efSearch sets the recall-versus-latency trade at query time. It is fast and accurate but memory hungry.
  • IVF clusters vectors and searches only the nearest clusters (nprobe). Product quantisation (PQ) compresses vectors to save memory at some accuracy cost. IVF-PQ is the usual choice for very large collections.

Always measure recall against the exact answer on your own data before trusting an index.

A database instead of a library

Libraries give you speed; databases give you durability, transactions, updates, and filtering next to your other data. With PostgreSQL and pgvector you get both.

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE chunks (
  id        bigserial PRIMARY KEY,
  source    text NOT NULL,
  section   text,
  acl       text[] NOT NULL DEFAULT '{}',
  body      text NOT NULL,
  embedding vector(384)
);

CREATE INDEX chunks_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);

-- nearest 5 chunks the caller may see; <=> is cosine distance
SELECT id, source, section, 1 - (embedding <=> $1) AS score
FROM chunks
WHERE acl && $2
ORDER BY embedding <=> $1
LIMIT 5;

Filtering combined with an approximate index can return fewer than k rows if the filter is very selective. Tune the index's search width, or partition by the filter, and test it.

Choosing

  • Under about a million vectors, one team, simple needs: exact search or pgvector.
  • Very large or high QPS: a dedicated vector database or FAISS service.
  • Frequent updates and metadata filters: a database with vector support.

Common mistakes

  • Mixing metrics (building with inner product, querying with L2).
  • Forgetting to normalise when the index assumes unit vectors.
  • Benchmarking latency without checking recall.

Exercises

  1. Build flat and HNSW indexes on 100k vectors and plot recall against latency as you vary efSearch.
  2. Add a metadata filter in pgvector and check what happens to result counts.

You are done when you can…

  • Run exact and approximate search and measure recall against the exact answer
  • Explain HNSW's two main parameters and what each trades off
  • Create a pgvector table with an HNSW index and a filtered query