Similarity Metrics and ANN Indexes

Cosine similarity, dot product and distance, plus the approximate nearest neighbour indexes that make search over millions of vectors fast.

Intermediate · about 3 hours · difficulty 3/5

Learn first: Text Embeddings

Once text is vectors, "how similar" becomes math.

Metrics

  • Cosine similarity: the angle between vectors, ignoring length. The default for most text embeddings.
  • Dot product: equal to cosine when vectors are normalized to length 1 (many embedding models already do this), and slightly faster.
  • Euclidean (L2) distance: straight-line distance; for normalized vectors it ranks results the same as cosine.

Use whatever metric the embedding model was trained for; the model card will say.

Why exact search does not scale

Comparing a query with every stored vector (brute force) is fine for thousands of vectors and fine for small apps. With millions it gets slow, so databases use approximate nearest neighbour (ANN) indexes:

  • HNSW: a layered graph; fast and accurate, memory hungry. The most common default.
  • IVF: clusters vectors and only searches the nearest clusters.
  • Quantization (product or binary quantization) compresses vectors to save memory at some accuracy cost.

The trade-off

ANN trades a little recall (sometimes missing the true nearest neighbour) for large speed gains. Index parameters such as HNSW's ef_search tune this balance.

Pitfalls

Applying metadata filters after ANN search can return too few results. Learn how your database handles filtered search. And similarity scores are not calibrated probabilities; do not hardcode a universal threshold without testing.

Good enough to move on

You can implement cosine similarity by hand, explain what HNSW trades off, and measure recall of an ANN index against brute force on a sample.

Key concepts

  • Cosine similarity
  • Dot product and normalization
  • Euclidean distance
  • Brute force vs ANN
  • HNSW
  • IVF and quantization
  • Filtered vector search

Mini project

Implement brute-force cosine search in numpy over 50,000 vectors, then index the same vectors with an HNSW library (such as hnswlib or FAISS) and report speed and recall at 10.

Check yourself

Why might you get only 2 results when you asked a vector database for the top 10 matches with a strict metadata filter?

Free resources