# Cosine vs Dot Product vs Euclidean Distance?

> Cosine, dot product and Euclidean distance compared: what each one measures, when they agree, and which to pick, for your AI interview.

**In short:** Cosine looks only at the angle between two vectors. Dot product mixes angle and length, and Euclidean distance measures the straight-line gap. OpenAI and Azure both point to cosine for their own models, and all three give the same ranking when vectors are normalised to length 1.

AI and LLM interview question Q118, Retrieval-augmented generation (RAG). Intermediate, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/cosine-vs-dot-product-vs-euclidean-distance

## Say it in 30 seconds

Cosine, dot product and Euclidean distance all compare two vectors, which are lists of numbers that stand for text. Cosine looks only at the angle between them, so length does not matter. Dot product mixes angle and length, so a long chunk can outscore a better match. Euclidean distance measures the straight-line gap, where smaller means closer. I start with cosine, and when vectors are normalised to length 1, all three rank the same.

## Say it in 2 minutes

A search over company documents turns every chunk of text into a vector, which is a list of numbers, and does the same to the question. The search then scores each chunk against the question and sorts by score. The scoring rule is the similarity or distance measure, and interviewers ask which one you would pick and why.

Cosine looks only at the angle between two vectors. Its result runs from minus 1 to plus 1, and length is ignored, so a short FAQ and a long policy page that point the same way score the same. Dot product multiplies matching numbers and adds them up, so length counts. Euclidean distance is the straight-line gap between the two points, and smaller means closer.

The trap is dot product on vectors of different lengths. In a made-up bank example, a long card-terms page scores 3.4, while a short FAQ that points the same way scores 0.49. Dot product puts the long page first. Cosine ranks the FAQ first, which is what the customer needs. My default is cosine, and OpenAI recommends it too, while saying the choice usually matters little.

If vectors are normalised to length 1, cosine, dot product and Euclidean give the same ranking, so the choice matters less. Google Cloud suggests dot product with unit-length vectors instead of cosine, and says its algorithms are more optimized for that distance. I still test each option on real questions before launch.

## What are cosine, dot product and Euclidean distance, in plain words?

A search over text works with vectors. Each chunk of a document (a short piece of it, such as one FAQ answer) and each question becomes a vector, a list of numbers. A vector has a length, which is how big its numbers are overall, and a direction, which is where the list points. The search compares the question's vector with every chunk's vector and sorts the chunks by score.

Think of a new hire using a staff handbook. Two pages both cover leave. Cosine asks whether they cover the same topic. Dot product also counts how long each page is. Euclidean asks how far apart the two pages sit in meaning. A customer who asks how long they have to dispute a card charge needs the help page that answers it, and the measure decides which page comes first.

- **Chunk:** A short piece of a document, such as one FAQ answer or one policy clause, that the search compares.
- **Vector:** A list of numbers that stands for a piece of text. Google Cloud's vector search docs say it has magnitude and direction.
- **Embedding:** A vector made by an embedding model, so that text with similar meaning gets similar numbers.
- **Magnitude:** The length of a vector: how big its numbers are overall.
- **Normalised:** Scaled so the length is exactly 1. Only the direction is left.

## How does each measure work?

Cosine gives a score from the angle between two vectors. Vectors pointing the same way give 1, opposite ways give minus 1, and right angles give 0. The length of each vector is ignored, so only the angle counts.

- **Cosine: Angle only.** Compares direction and ignores length. Higher means more similar, from minus 1 to plus 1.
- **Dot product: Angle and length.** Multiplies matching numbers and adds them up. Long vectors score high, so length can decide the order.
- **Euclidean: Straight-line gap.** Measures how far apart the two points are. Smaller means closer, so sort in the opposite direction from cosine.

Here is one question scored three ways, in a made-up bank example. The numbers are small, but the pattern is the one you will meet at work.

*Diagram, One question, three scores: One question is scored against three help-page chunks. Cosine and Euclidean both put the 60-day FAQ first, while dot product puts the long card-terms page first because it is long. The numbers are made up.*
1. The question is turned into a list of numbers.
2. Its numbers are compared with each chunk's cosine score.
3. The same numbers also get a dot product score.
4. And a Euclidean distance to each chunk.
5. Cosine ranks the 60-day FAQ first.
6. Dot product ranks the long card terms first.
7. Euclidean also picks the FAQ, the closest point.

Read the scores. Cosine ranks the FAQ first. Dot product ranks the long card terms first, at 3.4 against 0.49. Euclidean also picks the FAQ, then the fee table, and the card terms come last, because the card terms sit furthest away.

```python
# A bank's card-dispute assistant scores three chunks of its help text against one question.
# Made-up numbers: real embeddings have hundreds or thousands of values (OpenAI's text-embedding-3-small uses 1536), not three.
import math

query = [0.9, 0.1, 0.4]
chunks = {
    "FAQ: dispute within 60 days": [0.45, 0.05, 0.2],
    "Card terms, section 7": [3.0, 0.6, 1.6],
    "Wire fee table": [0.1, 0.9, 0.2],
}

def dot(a, b):
    return sum(x * y for x, y in zip(a, b))

def cosine(a, b):
    return dot(a, b) / (math.sqrt(dot(a, a)) * math.sqrt(dot(b, b)))

def euclidean(a, b):
    return math.sqrt(sum((x - y) ** 2 for x, y in zip(a, b)))

for name, vec in chunks.items():
    print(
        f"{name}: cosine {cosine(query, vec):.3f}, "
        f"dot {dot(query, vec):.3f}, euclidean {euclidean(query, vec):.3f}"
    )
print("best by cosine (higher is better):", max(chunks, key=lambda n: cosine(query, chunks[n])))
print("best by dot product (higher is better):", max(chunks, key=lambda n: dot(query, chunks[n])))
print("closest by Euclidean (lower is better):", min(chunks, key=lambda n: euclidean(query, chunks[n])))
```

Output:

```text
FAQ: dispute within 60 days: cosine 1.000, dot 0.490, euclidean 0.495
Card terms, section 7: cosine 0.995, dot 3.400, euclidean 2.470
Wire fee table: cosine 0.283, dot 0.260, euclidean 1.149
best by cosine (higher is better): FAQ: dispute within 60 days
best by dot product (higher is better): Card terms, section 7
closest by Euclidean (lower is better): FAQ: dispute within 60 days
```

> **Tip:** Python's max() picks the highest score and min() picks the lowest. Euclidean needs min(), because a small distance is the good result. Mixing the two up is a common bug, and it returns the worst chunks first.

## What changes when the vectors are normalised?

Normalising scales every vector to length 1, so only direction is left. Then dot product gives the same ranking as cosine, and Euclidean distance also ranks the results the same way. Google Cloud's index settings say the same thing: normalise, then dot product matches cosine.

OpenAI's embedding guide says its own vectors are normalised to length 1, and that on vectors like that, cosine can be computed with a plain dot product, which is a little faster. It adds that cosine and Euclidean give identical rankings.

> **Tip:** Before you choose, check whether your vendor already normalises its vectors, and make sure every vector in the index is treated the same way.

## Which one should you pick?

OpenAI and Azure name cosine in their own guides. Google names a different setup. Here is what the three vendors say:

> "We recommend cosine similarity. The choice of distance function typically doesn't matter much." (OpenAI)
>
> "Azure OpenAI embedding models use cosine similarity, so if you're using Azure OpenAI embedding models, cosine is the recommended metric." (Azure AI Search)
>
> "We strongly suggest using DOT_PRODUCT_DISTANCE + UNIT_L2_NORM instead of the COSINE distance." (Google Cloud)

Google's guide leans the other way: dot product with unit-length vectors, which ranks the same as cosine. Azure's index setting says cosine for its OpenAI models, and for anything else, the metric the embedding model was built for.

*Diagram, Picking the metric: A short path for picking a metric. Start with what the model's guide says, then test every choice on real questions before you trust it.*
1. Your team asks the model's guide which metric it uses.
2. If the guide names one, that metric is the first choice.
3. If it names none, cosine is the starting point.
4. The named metric goes to the testing step.
5. The cosine default goes to the same testing step.

1. **Read the model's guide:** Look for the metric the vendor names. Azure points to cosine for its OpenAI-based models.
2. **Match the index setting:** The search index must use the metric the vectors were made for, or the scores mean something else.
3. **Test on real questions:** Write questions with known right answers, and keep the metric that puts those answers on top.

### How would you pick the metric for a bank's help search?

A mid-size bank has 40,000 help pages, and its search keeps returning long policy pages first. I would start with the embedding model's guide and the index settings, then check that they agree. Next I would write about 200 real staff questions, each with the page that answers it, and score every metric against that list.

> **Tip:** Decide the metric before the index is filled, so you do not have to redo the work on 40,000 pages.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Vectors are lists of numbers, with a length and a direction.
- [ ] Cosine ignores length. Dot product and Euclidean distance do not.
- [ ] Euclidean: smaller is closer. Cosine and dot product: bigger is closer.
- [ ] With vectors of length 1, all three give the same ranking.
- [ ] Pick the metric the model's guide names, then test on real questions.

**Common traps**

- Trap: "Cosine is always the best measure." Better: It is the usual default. Check the model's guide and test on your own questions.
- Trap: "A bigger score means closer for every measure." Better: For Euclidean, smaller is closer. Sort the other way, or the nearest chunks end up last.
- Trap: "Dot product is the same as cosine." Better: Only when both vectors have length 1. Otherwise long vectors win on dot product.

## Can you spot the mistake?

**Spot the bug:** Which team setup has a bug?

A. We use cosine, the metric our embedding model's guide names.
B. We sort Euclidean distances from highest to lowest and show the top three.
C. We normalise vectors to length 1 and use dot product, which ranks like cosine.
D. We test the metric on 200 real staff questions before launch.

**Answer:** B. Euclidean distance is smaller when things are closer. Sorting highest first returns the farthest chunks, so the top three are the worst matches.

**Quick check:** A bank's help search keeps returning a long policy page first, and its vectors are not normalised. What is the most likely cause and fix?

A. The embedding model is too small, so switch to a bigger one.
B. The index has too few replicas, so add more copies.
C. Dot product rewards length, so switch to cosine or normalise first.
D. Cosine is too slow, so switch to Euclidean distance.

**Answer:** C. Dot product scores grow with a vector's length, so a long page can beat a better match. Cosine ignores length, and normalising removes it. A bigger model or more replicas does not change the score rule that ranks the chunks.

## Can you answer these from memory?

**Flash cards**

- **What does cosine measure?** The angle between two vectors. Length is ignored. Range: minus 1 to plus 1.
- **What does dot product add?** Length as well as direction. Long vectors can score high.
- **Euclidean: higher or lower is closer?** Lower. It is the straight-line gap between two points.
- **BigQuery's default distance in VECTOR_SEARCH?** Euclidean. It also supports cosine and dot product.
- **What happens when vectors have length 1?** Cosine and dot product match, and Euclidean ranks the same way.
- **Which metric do OpenAI and Azure recommend for their own models?** Cosine. Then check the model's guide and test on real questions.

## Likely follow-up questions

- Q111 What is RAG, and why use it? https://designervenkat.online/interview/ai/what-is-rag
- Q116 How do you choose an embedding model? https://designervenkat.online/interview/ai/how-do-you-choose-an-embedding-model
- Q117 What is a vector database? https://designervenkat.online/interview/ai/what-is-a-vector-database
- Q119 What is approximate nearest-neighbour search? https://designervenkat.online/interview/ai/what-is-approximate-nearest-neighbour-search
- Q120 How does HNSW work? https://designervenkat.online/interview/ai/how-does-hnsw-work

## Learn it in depth

- [Performing Similarity Search](https://designervenkat.online/learn/ai-engineering/performing-similarity-search)
