Inferensys

Glossary

Distance Metric

A distance metric is a mathematical function that defines a distance between two points in a vector space, forming the foundation for similarity search in AI and machine learning.
Engineer reviewing vector database search results on laptop, embeddings visualization on screen, home office coding session.
VECTOR INDEXING ALGORITHMS

What is a Distance Metric?

A mathematical function that defines a distance between two points in a vector space, directly influencing similarity search and index construction.

A Distance Metric is a mathematical function that defines a distance between two points in a vector space, satisfying the properties of non-negativity, identity of indiscernibles, symmetry, and the triangle inequality. In vector search, it quantifies dissimilarity; common metrics include Euclidean distance (L2), inner product, and cosine similarity. The choice of metric dictates how an index organizes vectors and performs Approximate Nearest Neighbor Search (ANNS), directly impacting search accuracy and latency.

Selecting the correct metric is foundational to index performance. Euclidean distance measures straight-line distance, ideal for spatial data. Cosine similarity measures angular separation, often used for text embeddings. For maximum inner product search (MIPS), the inner product is optimized. Index algorithms like HNSW and IVF are designed to efficiently compute these metrics, and techniques like Asymmetric Distance Computation (ADC) are used to approximate them when vectors are compressed via Product Quantization (PQ).

FOUNDATIONAL CONCEPTS

Key Distance Metrics for Vector Search

A distance metric is a mathematical function that defines a distance between two points in a vector space. The choice of metric fundamentally shapes how a vector index organizes data and performs similarity search.

01

Euclidean Distance (L2)

Euclidean distance calculates the straight-line distance between two points in Euclidean space. It is the most intuitive geometric distance, computed as the square root of the sum of squared differences between corresponding vector components.

  • Formula: (d(\mathbf{x}, \mathbf{y}) = \sqrt{\sum_{i=1}^{n} (x_i - y_i)^2})
  • Use Case: The default for many similarity tasks where absolute magnitude matters, such as image feature matching or physics-based embeddings.
  • Index Impact: Algorithms like k-means clustering for IVF and graph construction for HNSW often optimize for L2 distance, making it the most widely supported metric.
02

Cosine Similarity & Distance

Cosine similarity measures the cosine of the angle between two vectors, assessing orientation rather than magnitude. Cosine distance is derived as 1 - cosine similarity.

  • Formula: Similarity = (\frac{\mathbf{x} \cdot \mathbf{y}}{|\mathbf{x}||\mathbf{y}|}). Distance = (1 - \text{similarity}).
  • Use Case: Dominant in text and NLP applications (e.g., sentence embeddings from models like SBERT) where document length is irrelevant to meaning.
  • Index Impact: Many vector databases internally optimize cosine distance by L2-normalizing all vectors, allowing the use of highly optimized Euclidean distance indexes. The distance between normalized vectors is: (d_{\text{cos}} = |\mathbf{x} - \mathbf{y}|^2 / 2).
03

Inner Product (Dot Product)

The inner product (or dot product) is a measure of vector alignment and magnitude. For Maximum Inner Product Search (MIPS), the goal is to find vectors maximizing this value.

  • Formula: (\text{IP}(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^{n} x_i y_i).
  • Use Case: Critical for recommendation systems and learned embeddings where both direction and magnitude contribute to relevance (e.g., user and item embeddings).
  • Index Impact: MIPS is not a true distance metric (it doesn't satisfy the triangle inequality). Libraries like SCANN specialize in it. A common technique is to transform vectors to enable L2 search: append a dummy dimension to convert MIPS to nearest neighbor search in L2 space.
04

Manhattan Distance (L1)

Manhattan distance (or L1 norm, Taxicab distance) sums the absolute differences between vector components. It represents the distance traveled on a grid-like path.

  • Formula: (d(\mathbf{x}, \mathbf{y}) = \sum_{i=1}^{n} |x_i - y_i|).
  • Use Case: Useful in domains where differences are additive and independent, such as certain computer vision features, histogram comparison, or robust statistics where outliers have less influence than in L2.
  • Index Impact: Less common than L2 or cosine in mainstream vector databases. Support depends on the underlying index library (e.g., FAISS supports L1 for Flat indexes).
05

Jaccard & Hamming Distances

These metrics are designed for binary or set-based data representations.

  • Jaccard Distance: Measures dissimilarity between finite sample sets. Defined as 1 minus the Jaccard similarity coefficient (size of intersection over size of union).
  • Hamming Distance: Counts the number of positions at which the corresponding symbols are different. Used for binary vectors or strings of equal length.
  • Use Case: Jaccard for set similarity (e.g., shopping baskets, document shingles). Hamming for compact binary codes generated by hashing or Locality-Sensitive Hashing (LSH) schemes.
  • Index Impact: Specialized indexes, like those for LSH, are built directly on these discrete metrics. They are not typically used with dense, float-based embedding indexes.
06

Metric Properties & Selection

A true mathematical distance metric must satisfy four axioms:

  1. Non-negativity: (d(x, y) \ge 0)
  2. Identity of Indiscernibles: (d(x, y) = 0) iff (x = y)
  3. Symmetry: (d(x, y) = d(y, x))
  4. Triangle Inequality: (d(x, z) \le d(x, y) + d(y, z))

Selection Guide:

  • L2: Default for general-purpose, magnitude-sensitive data.
  • Cosine: For text, NLP, and any domain where vector direction is primary.
  • Inner Product: For recommendation systems and learned similarity where magnitude signals strength.
  • L1/Jaccard/Hamming: For specialized binary, set, or robust statistical data.

The metric dictates index algorithm choice, vector preprocessing (e.g., normalization), and the mathematical validity of graph or tree traversal assumptions.

FOUNDATIONAL CONCEPT

Mathematical Properties of a Valid Metric

A distance metric is a formal mathematical function that defines a valid notion of distance between points in a space. For a function to qualify as a metric, it must satisfy four non-negotiable axioms.

A distance metric is a function d(x, y) that assigns a non-negative real number to any pair of points x and y in a space, satisfying four core axioms. These are: non-negativity (d(x, y) ≥ 0), identity of indiscernibles (d(x, y) = 0 iff x = y), symmetry (d(x, y) = d(y, x)), and the triangle inequality (d(x, z) ≤ d(x, y) + d(y, z)). These properties ensure consistent geometric behavior, making metrics like Euclidean distance (L2) and Manhattan distance (L1) suitable for similarity search in vector databases.

In vector search, these properties directly influence index construction and search behavior. The triangle inequality, for instance, enables efficient pruning in tree-based indexes. While cosine similarity and inner product are common similarity measures, they are not true metrics unless specific transformations are applied. Understanding these axioms is crucial for selecting the correct distance function for an application and for designing efficient Approximate Nearest Neighbor (ANNS) algorithms that rely on geometric consistency.

CORE METRICS

Distance Metric Comparison

A comparison of the most common distance and similarity metrics used in vector search, detailing their mathematical definitions, computational properties, and primary use cases.

MetricMathematical DefinitionPrimary Use CaseIndexing ImpactNormalization Required

Euclidean Distance (L2)

sqrt(∑(x_i - y_i)²)

General similarity search in geometric spaces

Favors balanced, isotropic index structures (e.g., HNSW, IVF)

Inner Product (Dot Product)

∑(x_i * y_i)

Maximum Inner Product Search (MIPS) for recommendations

Requires index support for MIPS (e.g., SCANN); non-metric

Cosine Similarity

(x·y) / (||x|| ||y||)

Semantic similarity for text embeddings (e.g., from transformers)

Implies vectors are L2-normalized; reduces to max inner product search

Manhattan Distance (L1)

∑|x_i - y_i|

Robust distance in high-dimensional spaces, less sensitive to outliers

Less common; may use specialized partitioning

Jaccard Distance

1 - (|A∩B| / |A∪B|)

Similarity for binary or set-based data (e.g., recommendation systems)

Often used with MinHash or other set-similarity indexes

Hamming Distance

∑(x_i ≠ y_i)

Distance between binary strings or categorical codes

Used for binary quantization or fingerprint matching

FOUNDATIONAL CONSTRAINT

Impact on Vector Index Construction

The choice of distance metric is not merely a search parameter; it fundamentally dictates the data structures, algorithms, and optimization strategies used to build a vector index. It defines the geometry of the search space.

01

Determining Index Algorithm Suitability

Different distance metrics are optimized by different index families. Euclidean distance (L2) works naturally with Voronoi partitioning in IVF indexes and is the native geometry for many graph-based methods. Inner product (MIPS) requires specialized adaptations, as maximizing inner product does not obey the triangle inequality, making standard graph traversal less reliable. Algorithms like SCANN and HNSW with specific graph construction rules are engineered for MIPS.

02

Influencing Quantization & Compression

Compression techniques like Product Quantization (PQ) and Scalar Quantization must preserve the relative distances defined by the metric. For cosine similarity, vectors are often L2-normalized first, converting the problem to Euclidean distance on a unit sphere, which allows the use of standard PQ codebooks. For inner product, quantization must be designed to minimize error in dot product estimation, often leading to asymmetric distance computation (ADC) where the query remains in full precision.

03

Dictating Graph Construction Rules

In graph-based indexes like HNSW, the distance metric defines "closeness." Edge creation during index build uses the metric to connect each new node to its nearest neighbors. For cosine similarity, this typically requires all vectors to be normalized, making the graph a representation of the unit hypersphere. The search traversal algorithm (e.g., greedy search with a priority queue) uses the same metric to evaluate candidates, making the metric intrinsic to the index's connectivity.

04

Defining Partition Boundaries (IVF)

In an Inverted File (IVF) index, the dataset is partitioned into Voronoi cells using a coarse quantizer (like k-means clustering). The centroid of each cell is computed using the chosen distance metric. For Euclidean space, centroids are arithmetic means. For cosine similarity on normalized vectors, the centroid must also be normalized, often involving spherical k-means. The probe strategy—how many neighboring cells to search—is also a function of the metric's local geometry.

05

Impacting Build-Time Complexity & Cost

The computational cost of index construction is heavily influenced by the metric. k-means clustering for IVF, which requires many distance calculations, is more expensive with high-precision metrics. Graph construction for HNSW involves exhaustive nearest-neighbor searches during insertion, again dominated by distance computations. Choosing a simpler or optimized metric (e.g., using squared L2 to avoid sqrt operations) can significantly reduce index build time and resource consumption.

06

Governing Hybrid Search & Filtering

In production systems, vector search is often combined with metadata filtering. The distance metric influences how these operations are interleaved. For Euclidean distance, filters can be applied before or after the vector search with predictable results. For inner product, where scores are unbounded, applying a filter post-search can drastically alter rankings. This forces index architectures to support advanced filtered search strategies, such as modifying graph traversal or IVF probing based on filter predicates.

DISTANCE METRIC

Frequently Asked Questions

A Distance Metric is a mathematical function that defines a distance between two points in a vector space. The choice of metric is fundamental to vector indexing and search, as it directly determines which vectors are considered 'similar'.

A distance metric is a mathematical function that measures the dissimilarity between two vectors in a multi-dimensional space, forming the foundational rule for similarity search in vector databases. It quantifies how 'far apart' two points are, with common metrics including Euclidean distance (L2), cosine similarity, and inner product (dot product). The choice of metric is not arbitrary; it dictates the geometric shape of the 'neighborhood' around a query vector and directly influences which indexing algorithm (e.g., HNSW, IVF) is most effective. For instance, graph-based indexes like HNSW are agnostic to the specific metric, while algorithms optimized for Maximum Inner Product Search (MIPS) require specialized indexing techniques.

Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.