Understanding Distance Metrics

1. Using Cosine Similarity

PropertyValue
Formulacos(θ) = (A·B) / (|A| × |B|)
Range[-1, 1]; 1=identical, 0=orthogonal, -1=opposite
MagnitudeIgnored (length-invariant)
Best forText embeddings (most LLM models)

Example: Create Index with Cosine

from pinecone import ServerlessSpec

pc.create_index(
    name="docs",
    dimension=1536,
    metric="cosine",
    spec=ServerlessSpec(cloud="aws", region="us-east-1"),
)

2. Using Euclidean Distance

PropertyValue
Formulad = √Σ(Aᵢ − Bᵢ)²
Range[0, ∞); 0=identical (lower=closer)
MagnitudeSensitive to vector length
Best forImage features, spatial coords, raw numerical data

3. Using Dot Product

PropertyValue
FormulaA·B = Σ Aᵢ × Bᵢ
Range(-∞, ∞); higher=more similar
MagnitudeSensitive (favors longer vectors)
Best forHybrid search (required), recommenders, MIPS

4. Choosing Appropriate Metric

Use case?
 ├── Text / semantic similarity ─→ cosine
 ├── Hybrid (dense + sparse) ────→ dotproduct (required)
 ├── Recommenders (MIPS) ────────→ dotproduct
 ├── Image / spatial features ───→ euclidean
 └── Normalized embeddings ──────→ cosine ≡ dotproduct
      
WorkloadRecommended Metric
RAG / semantic searchcosine
Hybrid searchdotproduct
Recommendationdotproduct
Image similaritycosine or euclidean

5. Understanding Score Interpretation

MetricHigher Score MeansTypical "Good" Threshold
cosineMore similar> 0.75
dotproductMore similarDomain-specific
euclideanAPI returns sorted best-first< 0.5 (normalized)
Warning: Pinecone always returns scores sorted best-first regardless of metric. The raw score field reflects the underlying metric semantics.

6. Normalizing Vectors for Cosine Similarity

Example: L2 Normalization

import numpy as np

def normalize(v):
    norm = np.linalg.norm(v)
    return (v / norm).tolist() if norm > 0 else v

vec = normalize([0.3, 0.8, 0.5])  # |vec| = 1
ReasonBenefit
Cosine ≡ dotproduct on unit vectorsFaster compute, same results
Stable scoringRemoves magnitude bias

7. Converting Between Metrics

From → ToConversion
cosine ↔ dotproductNormalize vectors to unit length
euclidean → cosinecos = 1 − d² / 2 (on unit vectors)
dotproduct → cosinecos = dot / (|A|·|B|)

8. Understanding Metric Performance Tradeoffs

MetricCompute CostIndex Build
dotproductLowest (multiply-add)Fastest
cosineLow (norm cached)Fast
euclideanMedium (sqrt)Standard

9. Handling Negative Dot Product Scores

Note: Dot product can be negative. Filter score > threshold, or normalize vectors to bound scores in [-1, 1].
StrategyWhen
Filter by min scoreQuality control on results
Normalize vectorsNeed bounded, comparable scores
Shift scoresUI: (score + 1) / 2

10. Optimizing for Specific Metrics

OptimizationApplies To
Pre-normalize at upsertcosine, dotproduct
Reduce dimensions (PCA)All metrics — faster query
Quantization (int8)Storage savings, minor accuracy loss
Match metric to modelUse embedding provider's recommendation