Inferensys

Glossary

Distance Metric

A distance metric is a mathematical function that quantifies the similarity or dissimilarity between two vectors, forming the core of semantic search in vector databases.
Engineer reviewing vector database search results on laptop, embeddings visualization on screen, home office coding session.
VECTOR DATABASE API

What is a Distance Metric?

A distance metric is a mathematical function used by a vector database's Query API to measure the similarity or dissimilarity between two vectors, determining the order of search results.

A distance metric is a mathematical function that defines a distance between two points in a vector space, quantifying their similarity or dissimilarity. In vector databases, it is the core parameter for a nearest neighbor query, determining how the k-NN (k-Nearest Neighbors) algorithm ranks results. Common metrics include Euclidean distance (L2), cosine similarity, and inner product, each suited to different data distributions and embedding models. The choice of metric is specified in the Query API request payload and is intrinsically linked to the vector index structure for efficient search.

The metric must satisfy mathematical axioms: non-negativity, identity, symmetry, and the triangle inequality. Cosine similarity measures angular separation, ideal for normalized text embeddings, while Euclidean distance measures straight-line distance in space. Manhattan distance (L1) and Hamming distance are used for specific data types. The metric directly impacts recall and precision; an incorrect choice degrades semantic search quality. API clients must ensure the metric used for querying matches the one used during index creation to guarantee correct results.

VECTOR DATABASE INFRASTRUCTURE

Common Distance Metrics & Similarity Measures

Distance metrics are mathematical functions used by a vector database's Query API to quantify the similarity or dissimilarity between two high-dimensional vectors. The choice of metric directly impacts search relevance and performance.

01

Euclidean Distance (L2)

Euclidean distance calculates the straight-line distance between two points in vector space. It is the most intuitive geometric distance, computed as the square root of the sum of squared differences between corresponding vector dimensions. It is highly sensitive to the absolute magnitude of vectors.

  • Formula: √(Σ(x_i - y_i)²)
  • Use Case: Best for data where the absolute magnitude of the feature values is meaningful, such as physical measurements or pixel intensities in images.
  • Property: It is a true metric, satisfying the triangle inequality.
02

Cosine Similarity

Cosine similarity measures the cosine of the angle between two vectors, ignoring their magnitudes. It focuses solely on orientation. A value of 1 means identical direction, 0 means orthogonal, and -1 means diametrically opposite.

  • Formula: (A · B) / (||A|| ||B||)
  • Use Case: The default for most text embeddings (e.g., from models like OpenAI's text-embedding-ada-002), where the semantic meaning is encoded in the vector's direction, not its length.
  • Note: Often converted to a distance via cosine distance = 1 - cosine similarity.
03

Inner Product (Dot Product)

The inner product (or dot product) is the sum of the products of corresponding vector components. When vectors are normalized (unit length), it is equivalent to cosine similarity. For unnormalized vectors, it combines both direction and magnitude.

  • Formula: Σ(x_i * y_i)
  • Use Case: Used in maximum inner product search (MIPS) for recommendation systems, where the goal is to find items with the highest predicted affinity (score), not just similar direction.
  • Performance: Many optimized vector indexes (like FAISS) have dedicated modes for maximum inner product search.
04

Manhattan Distance (L1)

Manhattan distance (or L1 norm, Taxicab distance) sums the absolute differences between vector coordinates. It represents the distance traveled along grid-like paths.

  • Formula: Σ|x_i - y_i|
  • Use Case: Useful in high-dimensional spaces where the Euclidean distance might become less discriminative, or for data with sparse features. Often used in computer vision and clustering algorithms like K-Medians.
  • Interpretation: More robust to outliers than Euclidean distance, as it does not square the differences.
05

Jaccard & Hamming Distances

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

  • Jaccard Distance: Measures dissimilarity between finite sample sets. Calculated as 1 minus the size of the intersection divided by the size of the union of the sets. Ideal for comparing document shingles or user behavior sets.
  • Hamming Distance: Counts the number of positions at which the corresponding symbols are different between two strings or binary vectors of equal length. Fundamental for error-correcting codes and comparing encoded categorical data.

These are less common for dense float embeddings but are crucial for specific binary quantization or set-similarity search scenarios.

06

Metric Properties & Selection

A true distance metric must satisfy four mathematical properties: non-negativity, identity of indiscernibles, symmetry, and the triangle inequality. This last property is crucial for many indexing algorithms to prune the search space efficiently.

Choosing a Metric:

  • Text Embeddings: Start with cosine similarity.
  • Image/Physical Data: Try Euclidean distance.
  • Recommendations: Use inner product.
  • The metric must match the property preserved by the embedding model used to generate your vectors. Using the wrong metric is a primary cause of poor search quality.
VECTOR DATABASE API DESIGN

How to Choose a Distance Metric

Selecting the optimal distance metric is a foundational decision for the performance and accuracy of a vector database's Query API.

Choosing a distance metric involves matching the mathematical properties of the function to the data's characteristics and the search objective. For normalized embedding vectors where direction matters more than magnitude, cosine similarity is standard. For geometric spaces where absolute distance is meaningful, such as with GPS coordinates, Euclidean distance (L2) is appropriate. For high-dimensional, sparse data like text represented via TF-IDF, inner product or Manhattan distance (L1) may be more suitable. The metric dictates how the vector index organizes data.

The choice directly impacts recall, precision, and computational efficiency. Cosine similarity on unit vectors is equivalent to Euclidean distance on normalized data, allowing optimization. For hybrid search, the metric must be compatible with applied filter expressions. Ultimately, the selection is validated through empirical benchmarking on a representative query set, measuring the trade-off between search latency and the relevance of returned nearest neighbors for the specific use case.

QUERY API

Distance Metric Comparison

A comparison of the primary mathematical functions used to measure similarity or dissimilarity between vectors in a vector database's nearest neighbor search.

Metric / PropertyCosine SimilarityEuclidean Distance (L2)Inner Product (IP)Manhattan Distance (L1)

Primary Use Case

Directional similarity (text embeddings)

Geometric distance (image embeddings)

Unnormalized projection magnitude

Grid-like distance (sparse data)

Mathematical Formula

cos(θ) = (A·B) / (||A|| ||B||)

√Σ(Aᵢ - Bᵢ)²

Σ(Aᵢ * Bᵢ)

Σ|Aᵢ - Bᵢ|

Range of Values

-1 to 1

0 to ∞

-∞ to ∞

0 to ∞

Interpretation of High Value

More similar (vectors point same way)

More dissimilar (vectors far apart)

More similar (large positive projection)

More dissimilar (vectors far apart)

Requires Normalized Vectors

Common for Text Embeddings

Common for Image Embeddings

Index Support (e.g., HNSW, IVF)

Performance Impact

Low (after normalization)

Medium

Low

Medium

DISTANCE METRICS

Frequently Asked Questions

Distance metrics are the mathematical core of vector similarity search. These functions quantify how similar or dissimilar two vectors are, directly determining the results of a nearest neighbor query. This FAQ covers their purpose, common types, selection criteria, and implementation details for developers working with vector database APIs.

A distance metric is a mathematical function used by a vector database's Query API to measure the similarity or dissimilarity between two high-dimensional vectors, determining the order of results for a nearest neighbor search.

Formally, for vectors A and B, a valid distance metric must satisfy four properties:

  • Non-negativity: (d(A, B) \ge 0)
  • Identity of Indiscernibles: (d(A, B) = 0) if and only if (A = B)
  • Symmetry: (d(A, B) = d(B, A))
  • Triangle Inequality: (d(A, C) \le d(A, B) + d(B, C))

The choice of metric is specified as a parameter in the API request payload (e.g., {"metric": "cosine"}) and is intrinsically linked to the vector index type. Common metrics include Euclidean distance (L2), inner product, and cosine similarity.

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.