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.
Glossary
Distance Metric

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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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 / Property | Cosine Similarity | Euclidean 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 |
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.
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 core of vector similarity search. These functions quantify how 'close' or 'similar' two vectors are within a high-dimensional space, directly determining the results of a nearest neighbor query.
Cosine Similarity
Cosine similarity measures the cosine of the angle between two vectors, ignoring their magnitudes. It ranges from -1 (perfectly opposite) to 1 (identical orientation). It is the most common metric for text embeddings generated by models like Sentence-BERT, as it focuses on semantic direction rather than vector length.
- Key Use Case: Comparing text embeddings where magnitude is less informative than direction.
- Formula: cos(θ) = (A · B) / (||A|| ||B||)
- Database Implementation: Often optimized by indexing normalized vectors, turning cosine similarity into a dot product or Euclidean distance on normalized vectors for faster computation.
Euclidean Distance (L2)
Euclidean distance (L2 norm) measures the straight-line distance between two points in vector space. It is the most intuitive geometric distance. Lower values indicate greater similarity. It is often the default metric for image and other dense embeddings.
- Key Use Case: Computer vision embeddings, general-purpose dense vectors.
- Formula: √(Σ(Aᵢ - Bᵢ)²)
- Database Consideration: Some indexing algorithms like HNSW are highly optimized for L2 distance. For normalized vectors, Euclidean distance is monotonically related to cosine similarity.
Inner Product (Dot Product)
Inner product (dot product) is the sum of the products of corresponding vector components. For normalized vectors (unit length), it is equivalent to cosine similarity. For non-normalized vectors, it combines both direction and magnitude, which can be desirable for some ranking tasks.
- Key Use Case: Recommendation systems where both user and item embedding magnitudes signal preference strength.
- Formula: A · B = Σ(Aᵢ * Bᵢ)
- Database Note: Many vector databases internally convert high dot product searches to equivalent cosine or Euclidean searches on normalized data for index compatibility.
Manhattan Distance (L1)
Manhattan distance (L1 norm or taxicab distance) is the sum of the absolute differences between vector coordinates. It measures distance along axes at right angles, like navigating city blocks. It can be more robust to outliers than Euclidean distance.
- Key Use Case: Sparse, high-dimensional data, certain computer vision applications, and scenarios where robustness to outliers is critical.
- Formula: Σ|Aᵢ - Bᵢ|
- Performance: Computationally simpler than Euclidean distance but less commonly the primary metric for mainstream vector search indexes.
Jaccard Similarity
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 of the sets. For vectors, it is typically applied to binary or tokenized representations (e.g., word sets).
- Key Use Case: Comparing document token sets, recommendation systems based on binary user-item interactions.
- Formula: J(A,B) = |A ∩ B| / |A ∪ B|
- Vector Database Context: Often used in hybrid search scenarios where sparse, set-based data is combined with dense vector similarity.
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. It is a fundamental metric for comparing categorical or binary data.
- Key Use Case: Comparing binary hash codes (like locality-sensitive hashing outputs), error detection in information theory, and genomic sequence analysis.
- Example: The Hamming distance between
[1,0,1,1]and[1,1,1,0]is 2. - Database Role: Used in specific indexing techniques for ultra-fast, approximate filtering before a more precise distance calculation.

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