A distance metric is a mathematical function that defines a valid notion of distance between any two points in a vector space, satisfying the axioms of non-negativity, identity of indiscernibles, symmetry, and the triangle inequality. In vector databases and machine learning, these metrics quantify similarity, with common examples including Euclidean distance (L2), cosine similarity, and inner product. The choice of metric is critical, as it directly determines which vectors are considered 'nearest' during a k-NN search.
Glossary
Distance Metric

What is a Distance Metric?
A fundamental mathematical function for measuring similarity in vector search.
For normalized vectors, cosine similarity measures angular separation and is dominant in text retrieval, while Euclidean distance measures straight-line magnitude difference. The inner product is often used as a similarity proxy. Efficient approximate nearest neighbor (ANN) search relies on these metrics, with algorithms like HNSW and IVF optimized for specific distance calculations. Selecting the correct metric is essential for aligning search results with the semantic meaning of the embeddings.
Common Distance Metrics in AI
Distance metrics are mathematical functions that quantify the similarity or dissimilarity between two vectors in a high-dimensional space. The choice of metric directly impacts the performance and semantic meaning of similarity search in applications like retrieval-augmented generation (RAG) and recommendation systems.
Euclidean Distance (L2)
Euclidean Distance calculates the straight-line distance between two points in space. It is the most intuitive geometric distance, derived from the Pythagorean theorem. For vectors a and b, it is computed as the square root of the sum of squared differences: sqrt(Σ(a_i - b_i)²).
- Primary Use: Best for data where the absolute magnitude of the vector is meaningful, such as spatial coordinates or physical sensor readings.
- Key Property: It is sensitive to vector scale. Two documents with similar content but different lengths (e.g., a paragraph vs. a book chapter) can have a large Euclidean distance.
- Vector Database Note: Often the default metric for many indexes. Efficient computation is optimized in libraries like Faiss and HNSWlib.
Cosine Similarity
Cosine Similarity measures the cosine of the angle between two non-zero vectors, focusing purely on their orientation, not magnitude. It ranges from -1 (opposite directions) to 1 (identical direction). The formula is the dot product divided by the product of magnitudes: (a·b) / (||a|| * ||b||).
- Primary Use: The standard metric for text embeddings (e.g., from models like OpenAI's text-embedding-ada-002) and any scenario where semantic similarity is more important than size. It effectively compares document topics regardless of word count.
- Key Property: Invariant to scale. Multiplying a vector by a constant does not change its cosine similarity to another vector.
- Implementation Detail: Many vector databases internally use the negative cosine similarity or a normalized version to frame it as a distance (smaller values = more similar).
Inner Product (Dot Product)
Inner Product (or Dot Product) is a fundamental operation defined as the sum of the products of corresponding components: Σ(a_i * b_i). When vectors are L2-normalized (their magnitudes are scaled to 1), the inner product is mathematically equivalent to cosine similarity.
- Primary Use: A highly efficient similarity measure for normalized embeddings. Since the magnitude term is constant (1), maximizing the inner product is equivalent to maximizing cosine similarity.
- Performance Advantage: Computing a dot product is often faster than computing cosine similarity on unnormalized vectors, as it avoids the division by magnitude during query time. This makes it popular for high-throughput systems.
- Critical Consideration: Using inner product on non-normalized vectors is not a reliable similarity measure, as it is heavily influenced by vector magnitude.
Manhattan Distance (L1)
Manhattan Distance (or L1 distance, Taxicab distance) sums the absolute differences between vector components: Σ|a_i - b_i|. It represents the distance traveled on a grid-like path.
- Primary Use: Often used in computer vision and robotics for pixel-wise comparisons (e.g., image similarity) and in high-dimensional sparse data where differences are additive. It can be more robust to outliers than Euclidean distance.
- Key Property: It provides a different geometric perspective than L2. In a 2D plane, the set of points at a constant Manhattan distance from a center forms a diamond (rotated square), not a circle.
- Comparison: Less common than L2 or cosine for dense semantic embeddings but remains a foundational metric in machine learning and clustering algorithms like K-Medians.
Jaccard Similarity & Distance
Jaccard Similarity measures the similarity between finite sample sets. It is defined as the size of the intersection divided by the size of the union: |A ∩ B| / |A ∪ B|. Jaccard Distance is then 1 - Jaccard Similarity.
- Primary Use: Designed for binary or set-based data. Common in recommendation systems (e.g., users as sets of liked items), document similarity using shingling (sets of word n-grams), and genomic sequence analysis.
- Vector Representation: While defined for sets, it can be applied to binary vectors where each dimension indicates presence (1) or absence (0).
- Limitation: It ignores the frequency or weight of elements, considering only presence/absence. For weighted data, metrics like Cosine Similarity are more appropriate.
Hamming Distance
Hamming Distance counts the number of positions at which the corresponding symbols (or bits) are different between two strings or binary vectors of equal length.
- Primary Use: The fundamental metric for error detection and correction in information theory. In AI/ML, it's used for comparing binary hash codes generated by techniques like Locality-Sensitive Hashing (LSH) and for evaluating genetic algorithm chromosomes.
- Example: For binary vectors
[1, 0, 1, 1, 0]and[1, 1, 1, 0, 0], the Hamming distance is 2 (they differ in the 2nd and 4th positions). - Efficiency: Extremely fast to compute using bitwise XOR and popcount (population count) operations, making it ideal for massive-scale approximate nearest neighbor search in Hamming space.
Distance Metric Comparison
A comparison of the most common mathematical functions used to measure similarity or distance between vectors in high-dimensional space, detailing their properties, use cases, and computational characteristics.
| Metric / Property | Euclidean (L2) Distance | Cosine Similarity | Inner Product (Dot Product) | Manhattan (L1) Distance |
|---|---|---|---|---|
Mathematical Definition | sqrt(Σ(x_i - y_i)²) | (x·y) / (||x|| ||y||) | Σ(x_i * y_i) | Σ|x_i - y_i| |
Primary Use Case | General geometric distance; magnitude-sensitive comparisons. | Orientation comparison; text embeddings, NLP. | Similarity for normalized vectors; often a proxy for cosine. | Robustness to outliers; magnitude-sensitive in all dimensions. |
Sensitive to Vector Magnitude | ||||
Range of Values | [0, ∞) | [-1, 1] | (-∞, ∞) | [0, ∞) |
Common Normalization Requirement | Optional, but often applied (e.g., L2 normalization). | Vectors are typically L2 normalized. | Vectors are often L2 normalized for stable similarity. | Optional. |
Computational Complexity for d-dim vectors | O(d) | O(d) (after normalization) | O(d) | O(d) |
Indexing Support in Major Vector DBs (e.g., Pinecone, Weaviate) | ||||
Ideal Data Characteristics | When magnitude carries meaningful information (e.g., pixel intensities). | When direction/orientation is paramount (e.g., TF-IDF, word2vec). | When vectors are pre-normalized and speed is critical. | When features are sparse or outlier-resistant distance is needed. |
Mathematical Properties of a Valid Metric
A distance metric is a formal mathematical function that defines a consistent and meaningful notion of distance between any two points in a vector space. For a function to qualify as a valid 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 vectors x and y. To be mathematically valid, it must satisfy four core axioms: non-negativity, where d(x, y) ≥ 0; identity of indiscernibles, where d(x, y) = 0 if and only if x = y; symmetry, where d(x, y) = d(y, x); and the triangle inequality, where d(x, z) ≤ d(x, y) + d(y, z). These properties ensure distances behave intuitively, forming the foundation for reliable similarity search in vector databases.
In practical vector query optimization, these axioms guarantee that search results are consistent and stable. The triangle inequality, in particular, enables efficient indexing and pruning algorithms by bounding distances. Common functions like Euclidean distance (L2) satisfy all four axioms and are true metrics. Cosine similarity, while a popular similarity measure, is not a metric as-is but can be transformed into angular distance, which is. Understanding these properties is essential for selecting the correct function for a given embedding space and application.
Practical Use Cases
Distance metrics are the fundamental scoring functions for similarity. Their selection directly determines the semantic relationships captured by a vector search system.
Semantic Text Search
Cosine similarity is the predominant metric for comparing text embeddings (e.g., from models like BERT or OpenAI embeddings). It measures the angle between vectors, making it invariant to their magnitude. This is critical because the 'strength' or length of a text embedding often correlates with document length, not semantic meaning.
- Use Case: Finding support articles relevant to a customer's natural language query.
- Why Cosine? Two documents discussing the same topic with different word counts will have a high cosine similarity (angle near 0), whereas Euclidean distance would penalize the length difference.
Image & Multimedia Retrieval
Euclidean distance (L2) is frequently used for comparing image and audio embeddings from convolutional neural networks. In these spaces, the absolute position of the vector often corresponds to perceptual features where magnitude matters.
- Use Case: A reverse image search to find visually similar products.
- Why L2? If an embedding represents pixel intensity patterns or spectral features, the straight-line distance between two points is a natural measure of perceptual difference. For normalized image embeddings (e.g., from a final layer), inner product or cosine similarity may also be used.
Recommendation Systems
Inner product is the engine behind many collaborative filtering and recommendation algorithms. When user and item embeddings are learned such that a higher inner product indicates a stronger preference, it directly models predicted engagement.
- Use Case: "Users who liked this also liked..." recommendations.
- Implementation: In matrix factorization, the predicted rating is the inner product of the user and item vectors. For approximate nearest neighbor search in these spaces, maximizing inner product is equivalent to minimizing Euclidean distance only if the vectors are normalized.
Anomaly & Fraud Detection
Euclidean distance to a cluster centroid or to a known 'normal' profile is a core metric for identifying outliers. A vector far in L2 distance from its expected neighborhood signals a deviation.
- Use Case: Flagging fraudulent financial transactions based on behavioral embeddings.
- Process: Normal transaction patterns form dense clusters in the embedding space. A new transaction's embedding is scored by its distance to the nearest cluster centroid. Distances exceeding a threshold (a search radius) trigger an alert.
Cross-Modal Retrieval
A unified distance metric (often cosine) is essential for searching across different data modalities. Models like CLIP align images and text into a shared vector space where proximity indicates semantic correspondence.
- Use Case: Searching a stock photo database using a text description.
- Key Insight: The model is trained so that a photo of a dog and the text "a happy dog" have high cosine similarity. The same metric must be used for both intra-modal (image-to-image) and cross-modal (text-to-image) searches to ensure consistency.
Deduplication & Clustering
Choosing a distance metric defines what "duplicate" or "cluster member" means. Euclidean distance is common for dense, magnitude-sensitive data, while Jaccard distance (for sets) or Hamming distance (for binary hashes from LSH) are used for specific data types.
- Use Case: Identifying near-duplicate user-generated content in a moderation pipeline.
- Workflow: Embeddings are generated for all items. A range search with a small epsilon radius finds all vectors within a tolerance, flagging them as duplicates. The choice of metric determines the nature of the tolerance (angular vs. magnitude-based).
Frequently Asked Questions
A Distance Metric is a mathematical function that defines a notion of distance between two points in a vector space. In vector databases, these metrics are the core of similarity search, determining how 'close' or 'similar' two embeddings are. The choice of metric directly impacts the relevance of search results and the performance of the underlying index.
A distance metric is a mathematical function that quantifies the dissimilarity between two data points represented as vectors in a multi-dimensional space. It is the foundational operation for similarity search, clustering, and classification algorithms. The metric must satisfy four mathematical properties: non-negativity, identity of indiscernibles (distance is zero only for identical points), symmetry, and the triangle inequality. Common examples include Euclidean distance (L2), cosine similarity, and inner product. The choice of metric is dictated by the data's properties and the desired notion of similarity; for instance, cosine similarity is invariant to vector magnitude, making it ideal for comparing text embeddings where frequency is less important than direction.
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Related Terms
Distance metrics are the mathematical foundation for measuring similarity in vector spaces. These related concepts define how these measurements are applied, optimized, and evaluated within a vector database system.
Cosine Similarity
A distance metric that measures the cosine of the angle between two non-zero vectors. It evaluates orientation rather than magnitude, making it ideal for comparing semantic text embeddings where the vector length (e.g., document length) is not relevant to similarity.
- Range: Values from -1 (opposite direction) to 1 (identical direction), with 0 indicating orthogonality.
- Common Use: The default metric for many pre-trained language model embeddings (e.g., from OpenAI, Cohere).
- Optimization: Often implemented efficiently using the inner product on L2-normalized vectors.
Euclidean Distance (L2)
A distance metric that calculates the straight-line distance between two points in Euclidean space. It represents the magnitude of the difference between two vectors and is sensitive to both direction and vector length.
- Formula: sqrt(Σ (x_i - y_i)²).
- Common Use: Computer vision embeddings, geographic data, and any domain where the absolute difference in vector components is meaningful.
- Note: Smaller distances indicate greater similarity. For normalized vectors, it is related to cosine similarity.
Inner Product
A distance metric calculated as the sum of the products of corresponding vector components (dot product). It serves as a similarity measure, where higher values indicate greater similarity.
- Key Relationship: For L2-normalized vectors, inner product is mathematically equivalent to cosine similarity.
- Performance: Often the fastest metric to compute as it avoids square root operations required for Euclidean distance.
- Database Consideration: Some vector indexes (e.g., HNSW) require distance metrics that satisfy specific mathematical properties; inner product can be used directly or transformed for compatibility.
k-NN Search
A query type that retrieves the 'k' vectors in a database that are most similar to a given query vector according to a specified distance metric. It is the fundamental operation enabled by vector indexes.
- Exhaustive k-NN: Compares the query to every vector in the database (O(n) complexity), guaranteeing perfect recall but is prohibitively slow at scale.
- Approximate k-NN (ANN): Uses specialized indexes (like HNSW or IVF) to find highly similar vectors in sub-linear time, trading a small amount of recall for massive speed gains.
- Parameter 'k': Directly impacts query latency and result set size.
Recall & Precision
The primary evaluation metrics for the accuracy of an approximate nearest neighbor search compared to an exhaustive, ground-truth search.
- Recall: The fraction of true nearest neighbors (from an exhaustive search) that are successfully retrieved by the ANN system. Measures completeness.
- Precision: The fraction of retrieved items that are true nearest neighbors. Measures accuracy.
- Trade-off: Index hyperparameters (like EF Search in HNSW) allow tuning the balance between higher recall (slower) and higher throughput (potentially lower recall).
- Recall@K: A standard metric measuring recall within the top K retrieved results.
Query Latency & Throughput
The core performance metrics for a vector search system, directly influenced by the choice of distance metric and index algorithm.
- Query Latency: The end-to-end time to process a single search request. P99 Latency (99th percentile) is critical for defining service-level objectives.
- Throughput (QPS): The number of queries per second a system can sustain at a target latency.
- Optimization Levers:
- Metric Choice: Inner product is often faster than Euclidean distance.
- Vector Quantization: Techniques like Scalar Quantization reduce memory bandwidth, speeding up distance computations.
- Index Tuning: Parameters control the accuracy-speed trade-off.

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us