Cosine similarity explained for RAG developers
261206
Why cosine similarity matters
Cosine similarity is a single number between −1 and 1 that tells you how closely two vectors point in the same direction. In a RAG app, this number decides which chunks of your documents have similar meaning, and can be sent to the LLM as context. If you understand it, you understand how retrieval actually “finds” relevant text.
The idea comes from school trigonometry, so the math is small. The hard part for most developers is knowing what the vectors actually are. We’ll start there.
What the vectors represent
In RAG, each vector is an embedding: a list of numbers that an embedding model produces from a piece of text. The model reads a sentence, a paragraph or a chunk and turns it into something like this:
"How do I reset my password?" → [0.021, -0.314, 0.087, ..., 0.142]
A few things to know about these numbers:
- Each number is one dimension. Real embeddings have hundreds or thousands of dimensions (384, 768, 1536 and 3072 are common sizes). Every text embedded by the same model gets the same number of dimensions.
- No single dimension has a readable meaning. You can’t point at dimension 42 and say “this one means sport”. Meaning is spread across all of them together.
- Meaning becomes direction. The model is trained so that texts with similar meaning get vectors pointing in similar directions. “How do I reset my password?” and “I forgot my login credentials” share almost no words, but their vectors point nearly the same way.
- Unrelated texts point in different directions. A chunk about password resets and a chunk about holiday opening hours end up at a wide angle from each other.
So a vector is a point in a high-dimensional “meaning space”, drawn as an arrow from the origin. Two arrows that point the same way carry similar meaning. Cosine similarity is simply the tool that measures how much two arrows point the same way.
We can’t draw 1536 dimensions, so the examples below use 2D vectors. The math is identical in any number of dimensions. You just add more terms to the sums.
The formula
Cosine similarity between 2 vectors A and B is the dot product divided by the product of their lengths:
It has three parts.
- The dot product, A · B. Multiply the matching components and add the results. For 2D vectors A = (a₁, a₂) and B = (b₁, b₂), that’s a₁b₁ + a₂b₂. With 1536 dimensions there are 1536 products to add.
- The magnitude (length) of each vector, ‖A‖ and ‖B‖. Square every component, add them, take the square root. For A that’s √(a₁² + a₂²). This is just Pythagoras.
- The division. Dividing by both lengths removes the effect of size. What’s left depends only on the angle θ between the arrows.
The same formula in n dimensions:
In Python with NumPy it’s one line:
import numpy as np
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
print(cosine_similarity([3, 4], [4, 3])) # 0.96
The geometric intuition
The formula is the cosine of the angle between the two arrows, which is where the name comes from. It follows from a second way to write the dot product:
Rearrange it and you get the cosine similarity formula above.
A picture helps. Place both arrows at the origin. From the tip of B, drop a straight line down onto the line A lies on, meeting it at a right angle. You’ve built a right triangle:
- the hypotenuse is B, with length ‖B‖
- the adjacent side runs along A, with length ‖B‖ cos θ. This is the projection of B onto A.
So cos θ = adjacent / hypotenuse, the same definition from school. In plain words: cosine similarity is the share of B that points along A.
Because it’s a cosine, the value always lands between −1 and 1:
| Angle θ | cos θ | Meaning |
|---|---|---|
| 0° | 1 | Same direction: as similar as possible |
| 30° | 0.87 | Very similar |
| 60° | 0.5 | Somewhat related |
| 90° | 0 | Perpendicular: unrelated |
| 180° | −1 | Opposite directions |
Three cases: similar, unrelated, opposite
The three graphs below show the full range. In each one, vector A is blue, vector B is orange, and the shaded green wedge is the angle θ between them.

Here is the math behind each graph:
| Case | A | B | A · B | ‖A‖ × ‖B‖ | cos θ | θ |
|---|---|---|---|---|---|---|
| High similarity | (4, 3) | (3, 4) | 4·3 + 3·4 = 24 | 5 × 5 = 25 | 0.96 | about 16° |
| No similarity | (4, 1) | (−1, 4) | 4·(−1) + 1·4 = 0 | √17 × √17 = 17 | 0 | 90° |
| Opposite | (3, 2) | (−3, −2) | 3·(−3) + 2·(−2) = −13 | √13 × √13 = 13 | −1 | 180° |
Notice what drives the result. In the second case the two products cancel out exactly, so the dot product is 0. In the third, B is A flipped around, so every product is negative.
For text embeddings: the first case is like “reset my password” vs. “forgot my login”. The second is like “reset my password” vs. “holiday opening hours”. The third is rare with real text embeddings, which almost never point in fully opposite directions.
Why length is ignored, and why that helps
Cosine similarity only cares about direction. Double the length of B and the dot product doubles, but so does ‖B‖, so the two cancel out. Try it: (3, 4) and (6, 8) have a cosine similarity of exactly 1.
For text, this is what you want. Vector length can be influenced by things that have nothing to do with meaning, such as how long the text is or how often certain words appear. A short FAQ answer and a long manual page about password resets should count as a match. Cosine similarity lets them match, because it compares what the texts are about, not how much text there is.
Compare this with Euclidean distance, the straight-line distance between the two arrow tips. Two vectors pointing the same way but with different lengths can be far apart by Euclidean distance while having a cosine similarity of 1.
Cosine similarity in a RAG pipeline
Here’s where the number shows up in a typical RAG app.
- Indexing. Your documents are split into chunks. Each chunk goes through the embedding model and becomes a vector. The vectors are stored in a vector database next to the original text.
- Querying. The user’s question goes through the same embedding model and becomes a query vector.
- Retrieval. The vector database computes the cosine similarity between the query vector and the stored chunk vectors, and returns the top-k chunks with the highest scores (for example, the top 5).
- Generation. Those chunks are added to the prompt as context, and the LLM writes its answer from them.
Normalization: the shortcut most databases use
If every vector is scaled to length 1 before it’s stored (called normalizing), then ‖A‖ × ‖B‖ = 1 and the formula reduces to the plain dot product. Many embedding models already return normalized vectors, and many vector databases normalize on insert. That’s why you’ll often see “dot product” or “inner product” as the metric setting. For normalized vectors it gives the same ranking as cosine similarity, and it’s cheaper to compute.
Similarity vs. distance
Some databases report cosine distance instead of similarity:
Distance runs from 0 (identical direction) to 2 (opposite). With similarity, higher means more relevant. With distance, lower means more relevant. Check which one your database returns before you sort results or set a threshold.
Common pitfalls
- Mixing embedding models. Vectors from two different models live in different spaces. Comparing them gives meaningless scores. Always embed the query with the same model you used for the chunks.
- Expecting the full −1 to 1 range. With text embeddings, scores usually sit between about 0 and 1, and unrelated text often still scores well above 0. A score of 0.3 can mean “unrelated” for one model and “loosely related” for another.
- Hard-coding a threshold too early. A cutoff like “keep everything above 0.8” depends on the model and your data. Look at real queries and their scores before you choose one.
- Treating high similarity as a correct answer. Cosine similarity measures topic closeness, not truth. A chunk can be very similar to the question and still not contain the answer.
Key takeaways
- An embedding turns text into a vector, and its direction carries the meaning.
- Cosine similarity is the cosine of the angle between two vectors: dot product divided by both lengths.
- 1 means same direction, 0 means unrelated, −1 means opposite.
- Length is cancelled out, so short and long texts on the same topic can match.
- In RAG, it’s the score that decides which chunks the LLM gets to see.
Happy coding!
That’s it for now! I hope you enjoyed it!
Thanks for reading and stay tuned!
