The Retrieval Problem: Relevance, Similarity, and the Geometry of Scores
Retrieval as ranking by a relevance functional — and the three similarity scores that agree on the sphere and diverge off it
Overview & motivation
Every retrieval system, lexical or neural, does the same thing: it scores documents against a query and returns the highest-scoring few. The entire apparatus the rest of this curriculum builds — inverted indexes, approximate-nearest-neighbor graphs, learned encoders, rerankers — exists to compute or approximate that scored ordering quickly and well. Before any of it, we should be precise about what the ordering is. Retrieval is ranking by a relevance functional, and the functionals we actually use are geometric: a query and a document are vectors, and relevance is a similarity between them.
There are three similarity scores in near-universal use, and they are usually introduced as interchangeable: the Euclidean distance , the dot product , and the cosine similarity . They are not interchangeable, and the single most useful fact in this topic is the precise statement of when they agree and when they part ways. The short version: on the unit sphere, the three induce the same ranking; off it, they can disagree on which document is most relevant, because the dot product rewards magnitude and cosine does not. That divergence is not a technicality — it is the reason embeddings are normalized, the reason BM25 normalizes by length, and the seed of a genuine hardness result later on. Before the algebra, drag the controls and watch it happen:
- 1.10-K · on-point (concise)0.979
- 2.News · Fed rate decision0.824
- 3.Earnings call · padded (long)0.794
- 4.10-K · FX risk (off-topic)0.316
Pick a score with the toggle and the laboratory draws its equal-score locus through the marked document — a line for the dot product, a circle for Euclidean distance, a pair of rays for cosine. Slide ‘s magnitude and watch the ranking on the right: under the dot product it climbs and eventually seizes the top spot from the long, large-norm transcript; under cosine it never moves. Tick “normalize all to the unit circle” and the three rankings snap into agreement.
What we cover
- Retrieval as ranking by a relevance functional, and why only the order matters.
- The three similarity scores and the one identity that ties them together.
- On the unit sphere: why the three rankings coincide.
- Off the sphere: why magnitude makes them diverge.
- Which of these are genuine metrics, and why the triangle inequality matters downstream.
- The level-set geometry, a finance case study, the honest caveats, and the tested implementation.
Retrieval as ranking by a relevance functional
Fix a query drawn from a query space and a corpus of documents. A retrieval model is, at bottom, a function that scores each document for its relevance to the query.
Definition 1 (Relevance functional and the induced ranking).
A relevance functional is a map . For a fixed query , it induces a ranking of the corpus: the total preorder in which is ranked at least as high as whenever . Documents are returned in order of decreasing .
The output a user sees is not the scores but the order, and usually only its top. We make that explicit.
Definition 2 (Top-k retrieval).
For a fixed query and an integer , top-k retrieval returns
ties broken by a fixed rule. It is a set-valued operator that depends on only through the order it induces, not through the score values themselves.
That last clause is worth dwelling on, because it has a consequence we will use repeatedly. If the score is only ever consumed through the ranking, then any transformation of the score that preserves the order leaves the retrieval output identical.
Proposition 1 (Rank invariance under monotone transforms).
Let be strictly increasing. Then the relevance functionals and induce the same ranking of every corpus, and hence the same top-k set for every and .
Proof.
Fix and two documents . Because is strictly increasing, holds if and only if . So the two functionals order every pair of documents identically, and a total preorder is determined by how it orders pairs; the rankings coincide. The top-k set, being a function of the ranking alone, is therefore unchanged.
∎Relevance, in other words, is ordinal: the scores are cardinal numbers, but the retrieval system reads only their order. This is why we may pass a score through a logarithm, an exponential, or a positive rescaling whenever it is mathematically convenient — a freedom the probabilistic models exploit when they move to log-odds, and one we use immediately below to compare distances with inner products. The companion code checks it directly: the cosine ranking of the finance corpus is unchanged under , , , and .
Three similarity scores and one identity
We now make the relevance functional concrete. Embed the query and each document as vectors in , and write for the inner product and for the Euclidean norm.
Definition 3 (Euclidean distance, dot product, cosine similarity).
For query and document in ,
The distance is a dissimilarity — the nearest document ranks first, so the corpus is ordered by increasing distance — while the dot product and cosine are similarities, ordered by decreasing value.
These three are not independent. A single algebraic identity, the expansion of a squared norm, connects all of them.
Theorem 1 (The cosine-distance identity).
For any ,
Proof.
Expand the squared norm using the bilinearity of the inner product:
The inner product is symmetric, so , and the middle two terms combine into , leaving .
∎Read geometrically, this is the law of cosines: writing for the angle between and recovers , the relation between a triangle’s third side and the angle it subtends. The identity is the linear-algebra bridge between the additive world of distances and the multiplicative world of inner products and angles, and every comparison that follows is an application of it.
On the unit sphere the three rankings coincide
The cleanest consequence of the identity appears when every vector has the same length. Suppose the documents are L2-normalized — projected onto the unit sphere — as they are in most dense retrieval systems. Then the three scores, despite measuring apparently different things, rank the corpus identically.
Theorem 2 (Equivalence of rankings on the sphere).
Let the query be fixed and the documents lie on the unit sphere, for all . Then ranking by decreasing cosine similarity, by decreasing dot product, and by increasing Euclidean distance produce the identical order.
Proof.
On the sphere , so the cosine denominator is a positive constant across all documents; cosine is therefore a fixed positive multiple of the dot product, , and the two rank the corpus identically. For the distance, apply Theorem 1 with , and :
The right-hand side is a strictly decreasing affine function of — the only document-dependent term is . So increasing means decreasing , hence decreasing . By Proposition 1, ranking by the increasing distance is ranking by the decreasing dot product under the strictly monotone map , so all three orders agree.
∎This is the result that lets a normalized dense retriever use whichever score is cheapest to compute — most systems store unit vectors and take dot products, knowing the cosine and Euclidean rankings are identical. The companion code confirms the coincidence not only on the finance corpus but on random corpora up to dimensions, where the cosine, dot, and Euclidean orders match exactly. The whole story of the unit hypersphere, where normalized embeddings actually live, begins from this equivalence.
Off the sphere they diverge: magnitude matters
The equivalence is conditional on normalization, and the condition bites. The moment document norms vary, the dot product and cosine can disagree, because the dot product sees magnitude and cosine does not.
Proposition 2 (Magnitude sensitivity of the dot product).
Fix a query and a document with , and scale the document by . Then
The dot product is linear in the document’s magnitude while the cosine is invariant to it. Consequently, enlarging a document’s norm can lift it arbitrarily high in the dot-product ranking without changing its cosine ranking at all.
Proof.
By the linearity of the inner product in its second argument, , which is strictly increasing in when . For the cosine, for , so
the factor canceling. Cosine quotients magnitude out; the dot product does not.
∎The laboratory above is a direct illustration. Its marked document is a concise, on-point filing; the corpus also contains a long, padded transcript with a larger norm. Under cosine, leads — it points most nearly in the query’s direction. Under the dot product, the padded transcript leads on the strength of its magnitude alone, and only when ‘s norm is scaled past does it overtake the transcript. Same query, same corpus, two different “most relevant” documents. This is exactly the pathology that BM25 addresses with length normalization, and the reason dense retrievers normalize before they compare.
Which of these are metrics?
We have been calling a distance and, loosely, a “cosine distance.” It is worth being exact about which of these is a genuine metric, because the difference governs which data structures can index them.
Definition 4 (Metric axioms).
A function is a metric if for all : (i) with if and only if (non-negativity and identity of indiscernibles); (ii) (symmetry); and (iii) (the triangle inequality).
Euclidean distance satisfies all four conditions; the load-bearing one is the triangle inequality.
Proposition 3 (Euclidean distance is a metric).
The map on is a metric.
Proof.
Non-negativity and symmetry are immediate from the definition of the norm, and forces , i.e. , giving identity of indiscernibles. For the triangle inequality, set and , so . Expanding and applying the Cauchy-Schwarz inequality — the convex-analytic bound at the heart of inner-product geometry — gives
Taking square roots, .
∎Cosine “distance” is a different story. It is symmetric and, on non-negative data, non-negative, but it is not a metric.
Proposition 4 (Cosine distance violates the triangle inequality).
The map is not a metric: there exist with .
Proof.
Take , , . Then while , so
The direct “distance” exceeds the detour , a violation by . The companion code computes this gap and asserts the violation.
∎The dot product fails even more basically: it is not a distance at all.
Proposition 5 (The dot product is not a metric).
The dot product cannot be a metric on : it lacks identity of indiscernibles, since for , and it ranks in the opposite sense, with larger values meaning more similar. A document need not even be its own best match: a longer vector in the same direction scores higher, .
Why insist on this taxonomy? Because the triangle inequality is precisely the structure that makes fast search possible. Tree- and graph-based indexes prune the corpus using bounds of the form , which is the triangle inequality rearranged; without it, a pivot tells you nothing about points it has not directly measured. Euclidean distance admits such indexes, cosine distance does not without first normalizing onto the sphere (where it becomes a monotone function of Euclidean distance, by Theorem 2), and the bare dot product admits none — a fact that becomes a genuine complexity barrier for maximum inner-product search later in this track. Production indexes encode the distinction directly: a vector store exposes separate inner-product, L2, and normalized-cosine modes precisely because they are different problems.
Level sets: the decision geometry
There is a clean way to see why the three scores rank differently: look at the set of points that score equally with the query. Each score has a level set of a characteristic shape, and those shapes explain the rankings at a glance.
Proposition 6 (Equal-score loci).
For a fixed query and a target value , the locus is:
- a hyperplane for the dot product;
- a sphere centered at for Euclidean distance;
- a cone through the origin for cosine.
Proof.
The dot-product locus is the solution set of a single linear equation in , an affine hyperplane with normal vector . The Euclidean locus is by definition the sphere of radius about . For cosine, means ; this condition is invariant under positive scaling for , since both sides scale by , so the locus is a union of rays from the origin — a cone with axis and half-angle .
∎The laboratory draws exactly these loci through the marked document: toggle the score and the dashed locus switches between a line, a circle, and a pair of rays. The shapes make the magnitude story visual. The cosine cone is anchored at the origin and cares only about direction, so sliding a document outward along a ray leaves its cosine score fixed; the dot-product hyperplane is perpendicular to , so pushing a document farther in the -direction strictly raises its dot score. That single picture — direction-only cone versus magnitude-sensitive hyperplane — is the whole of Proposition 2 made geometric.
Finance case study
A candid note on the companion code, in the spirit of the rest of the series: the four document vectors are a synthetic two-dimensional construction, chosen so the notebook is deterministic, CPU-only, and reproducible to the decimal with no model download. They are not the output of a trained encoder. The phenomenon being illustrated — that dot-product and cosine rankings diverge when norms vary, and coincide once they do not — is exact and dimension-independent, which is why the same coincidence holds in the harness up to dimensions.
Honest caveats
Implementation
The companion notebook (notebookPath) is self-contained, CPU-only, and runs in a fraction of a second on numpy. It defines the three similarity primitives and the ranking operator, builds the finance corpus, and prints the score table that the SimilarityGeometryLaboratory mirrors to the decimal. Its verification harness makes each claim of the topic executable: the cosine-distance identity holds to machine precision up to dimensions (Theorem 1); the cosine ranking is invariant under a battery of strictly monotone transforms (Proposition 1); on the unit sphere the cosine, dot, and Euclidean rankings coincide on the finance corpus and on random corpora up to dimensions (Theorem 2); off the sphere the dot product tops the padded transcript while cosine tops the on-point filing, and scaling ‘s magnitude flips the dot ranking at while leaving cosine fixed (Proposition 2); Euclidean distance satisfies all four metric axioms over a battery of point triples (Proposition 3); the cosine-distance triangle-inequality counterexample violates the inequality by (Proposition 4); the dot product fails identity of indiscernibles (Proposition 5); and points sampled along each computed level set carry a constant score, confirming the hyperplane, sphere, and cone classification (Proposition 6). The three pillars — the proofs above, the laboratory, and the tested code — agree by construction.
Connections
- the vector space model is the first concrete instance of the relevance functional defined here — documents and queries become weighted term vectors and rel(q,d) is their cosine similarity, the exact off-sphere-versus-on-sphere distinction this topic formalizes vector-space-model-tfidf
- BM25's length normalization is the lexical-retrieval answer to the magnitude sensitivity shown here: when document norms vary, dot-product ranking favors long documents, and normalization is what removes that bias bm25-binary-independence-model
- this topic defines the similarity scores in any dimension; the next asks what happens to them as the dimension grows, where the cosine-distance identity meets concentration of measure and near-orthogonality high-dimensional-geometry
- once embeddings are L2-normalized they live on the unit sphere, the exact regime where this topic proves the three similarity scores induce the same ranking; that topic builds the directional-statistics model of a cluster on that sphere hypersphere-vmf-geometry
References & Further Reading
- book Introduction to Information Retrieval — Manning, Raghavan & Schütze (2008) Chapter 6: scoring, term weighting, and the vector space model — retrieval as ranking by a similarity functional, and cosine versus inner product
- book Foundations of Data Science — Blum, Hopcroft & Kannan (2020) The geometry of inner products, norms, and distances that the cosine-distance identity rests on
- book Metric Spaces — Ó Searcóid (2007) The metric axioms — identity of indiscernibles, symmetry, triangle inequality — used to classify which similarity scores are true metrics
- paper Efficient and Robust Approximate Nearest Neighbor Search Using Hierarchical Navigable Small World Graphs — Malkov & Yashunin (2018) Why the triangle inequality is load-bearing downstream: graph ANN indexes exploit metric structure that cosine distance lacks
- documentation Faiss: Metric Types and Distances How a production vector index distinguishes inner-product, L2, and normalized-cosine search — the off-sphere divergence in code