Skip to main content

Dot products and cosine similarity: geometry behind relevance

From angles between vectors to embedding similarity, follow a simple piece of linear algebra into search and AI systems.

Mathematics for AIIntermediate

Learning goal

Compute dot products and cosine similarity, and explain magnitude versus direction in a search problem.

Prerequisites

  • Vectors and matrices
  • Basic algebra
  • Basic geometry

Dot product

The dot product combines the magnitude and relative direction of two vectors.

Dot product
x\cdot y=\sum_i x_i y_i

Geometric interpretation

Geometric identity
x\cdot y=\|x\|\,\|y\|\cos\theta

θ is the angle between the vectors. Dot product therefore depends on both angle and vector magnitude.

Cosine similarity

Cosine similarity
\cos(x,y)=\frac{x\cdot y}{\|x\|_2\|y\|_2}

Dividing by the norms removes the scale effect and focuses the comparison on relative direction.

Numerical example

Two vectors
x=\begin{bmatrix}1\\0\end{bmatrix},\quad y=\begin{bmatrix}0.8\\0.6\end{bmatrix}
Calculation
x\cdot y=0.8,\qquad \|x\|_2=\|y\|_2=1

The cosine similarity is 0.8 and the angle is about 36.9 degrees.

Connection to search and embeddings

In retrieval, a query and a document can be represented as vectors and compared with a similarity measure. Similarity choice and embedding quality still need validation against real data.

Connection to the Elasticsearch project

The Elasticsearch Search Platform focuses on relevance, text analysis, filtering, and explainability. This lesson is one mathematical foundation for vector retrieval, not a complete relevance model.

Exercises

  • Compute cosine similarity for (1,1) and (1,0).
  • Construct an example where dot product is large but cosine similarity is lower.
  • Explain why normalization is useful when comparing vector direction.

Related projects

Elasticsearch Search Platform

Relevance and search behavior are implemented in an inspectable platform.

Open source

HowAttentionWorks

Dot products appear directly in attention calculations.

Open source

Working on search or representation?

Similarity and retrieval can be evaluated against the real data and requirement.