# How to Implement Cosine Similarity and Top-K Search

> How to score two vectors with cosine similarity, find the top k matches with a plain search, and avoid the usual bugs, explained simply for your AI interview.

**In short:** Cosine similarity scores how alike two vectors are by the angle between them, from minus 1 to 1. Brute-force top-k search scores every stored vector against the query, keeps the k best and returns them. It is exact, but it slows down as the collection grows.

AI and LLM interview question Q475, Coding and practical. Beginner, very common (our estimate). From Venkat R. Murty's free Interview Kit: https://designervenkat.online/interview/ai/implement-cosine-similarity-and-top-k-search

## Say it in 30 seconds

Cosine similarity compares two embedding vectors by their direction. You take the dot product, divide by both lengths, and get a score from minus one to one. Brute-force top-k search scores every stored vector against the query, keeps the k best with a heap, and returns them. It is exact, which is its strength. The cost is that every question touches every vector, so past a certain size I would add an approximate index and measure how often it misses.

## Say it in 2 minutes

Embeddings turn text into lists of numbers. To find the most relevant items, I compare the question's vector with each stored vector. Cosine similarity does the comparison: it takes the dot product of the two vectors (multiply matching numbers and add them up) and divides by both lengths. That leaves only the direction, so length has no say in the score. The result is near one for vectors that point the same way, and near zero when they sit at right angles.

Brute-force top-k search applies that score to every stored vector, then keeps the k best. A heap, a small structure that holds only the best k so far, does the keeping without sorting everything. The answer is exact, so it never misses a true best match. That makes it the right baseline, and fine for small collections.

The risks sit in the edge cases and in scale. A zero vector would divide by zero, so I guard it. Vectors of different lengths mean the pipeline changed, so I raise an error rather than score mixed numbers. Top-k always returns k results, even poor ones, so I add a minimum score. Past a certain size I would switch to an approximate index such as HNSW, a graph that jumps to likely neighbours, and measure its recall, the share of the true best matches it still finds, against brute force on a sample of questions.

Before I trust the function, I test it with a zero vector, two vectors of different length, and a k bigger than the collection.

## What are cosine similarity and top-k search, in plain words?

An embedding turns a piece of text into a list of numbers, called a vector. Texts with similar meaning get vectors that point in similar directions. Cosine similarity is the score for how closely two vectors line up. Top-k search uses that score to find the k best matches for a question.

Picture a claims adjuster at an insurer with 4,000 policy clauses. A customer asks: "Is flood damage covered under our home policy?" She could read every clause and rank them by hand. Brute-force search does the same job for a computer: it scores every clause, with no shortcut.

The code later in this answer does that for the claims team. Its numbers are made up, and a real embedding has many more numbers than three.

- **Vector:** A list of numbers. Here, one list stands for one piece of text.
- **Embedding:** A vector made by an embedding model, which places texts with similar meaning close together.
- **Cosine similarity:** A score from minus 1 to 1 for how closely two vectors point the same way.
- **Top-k:** The k best matches, such as the best 3 clauses.
- **Brute force:** Checking every item, with no index to skip most of them.

## How does cosine similarity work?

Cosine similarity starts with the dot product. Multiply each pair of matching numbers, then add the results. Then divide by the length of each vector. Dividing by the lengths removes size, so only direction is left. Two clauses on the same topic can still score high, even if one is much longer, because cosine compares direction, not size.

scikit-learn, a Python machine learning library, describes it the same way: the normalised dot product of two vectors.

*Diagram, Cosine similarity, step by step: Two vectors go in. The dot product and the two lengths are worked out separately, then divided. The score sits between minus 1 and 1, and is near 1 when the two vectors point the same way.*
1. The pair goes into the dot product: multiply matching numbers.
2. The same pair goes to the lengths: square, add, take the root.
3. The dot product is handed over to be divided.
4. The two lengths are multiplied and used as the divisor.
5. The result is the score. Near 1 means the same direction.

A worked example with made-up numbers. The query is [0.85, 0.15, 0.05] and the flood cover clause is [0.8, 0.2, 0.2]. The dot product is 0.72. The two lengths multiply to about 0.734. Divide, and the score is 0.981.

> **Tip:** Scale a vector by ten and its cosine score stays the same. That is why cosine ignores length.

OpenAI's embeddings are already scaled to length 1. For vectors like that, the plain dot product gives the same score as cosine, and it can be computed a little faster. Check your model's documentation before you skip the division.

## How does brute-force top-k search work?

Brute force means there is no index. For each stored vector, compute the score, keep the best k, and return them best first. Because every vector is checked, the answer is exact. Azure's documentation calls this exhaustive KNN, which is a brute-force scan of the whole vector space.

1. **Embed the question once:** Use the same embedding model as the stored clauses. Use the same embedding model as the stored clauses. Vectors from two different models do not share a meaning, so their scores tell you nothing.
2. **Score every stored vector:** Cosine similarity against the query, one clause at a time.
3. **Keep the k best:** A heap holds only the best k as it goes, so the list is never fully sorted.
4. **Return them best first:** Sort the k items and return them with their scores.

*Diagram, Brute-force top-k search: The query and the stored clause vectors feed a scoring step. A heap keeps the best k, and the k results come out best first. The scoring step is the cost: it runs once per stored clause, on every question.*
1. Each stored clause vector goes in to be scored.
2. The query goes in too, for the same comparison.
3. The scores go to a heap that keeps only the best k.
4. The k best come out, highest score first.

> "To retrieve the most relevant documents we use the cosine similarity between the embedding vectors of the query and each document, and return the highest scored documents." (OpenAI, embeddings guide)
>
> "Exhaustive K-Nearest Neighbors (KNN), which performs a brute-force scan of the entire vector space." (Microsoft, Azure AI Search)

Python's heapq.nlargest does the keeping step. Its documentation says it gives the same result as sorting everything and cutting the list. Its own page also says that sorting is the more efficient choice for larger values of n, the number of results asked for. So for a small k the heap changes only the speed.

Here is the whole search in plain Python, with made-up numbers. The marked lines are the length check, the zero guard, the floor, the heap call and the floor demo.

```python
# A claims team's clause search. Made-up 3-number vectors; real embeddings have many more numbers.
import heapq
import math

def cosine(a, b):
    if len(a) != len(b):
        raise ValueError("vectors must have the same length")
    dot = sum(x * y for x, y in zip(a, b))
    norm = math.sqrt(sum(x * x for x in a)) * math.sqrt(sum(y * y for y in b))
    return dot / norm if norm else 0.0  # a zero vector matches nothing

def top_k(query, clauses, k, min_score=0.5):
    # Brute force: score every clause, drop weak ones, keep the best k.
    scored = [(cosine(query, vec), cid) for cid, vec in clauses.items()]
    good = [pair for pair in scored if pair[0] >= min_score]
    return heapq.nlargest(k, good)  # ties go to the higher clause id first, so output is stable

clauses = {
    "C-101 flood damage excluded": [0.9, 0.1, 0.0],
    "C-204 sudden burst pipe": [0.7, 0.6, 0.1],
    "C-310 claim filing deadline": [0.0, 0.2, 0.9],
    "C-455 flood cover add-on": [0.8, 0.2, 0.2],
}
query = [0.85, 0.15, 0.05]  # "is flood damage covered?" as an embedding
for score, cid in top_k(query, clauses, k=3):
    print(f"{score:.3f}  {cid}")
print("with floor:", len(top_k(query, clauses, k=4)))
print("no floor:", len(top_k(query, clauses, k=4, min_score=-1.0)))
```

Output:

```text
0.996  C-101 flood damage excluded
0.981  C-455 flood cover add-on
0.861  C-204 sudden burst pipe
with floor: 3
no floor: 4
```

The last two lines show the floor at work. With k set to 4, the floor drops the filing-deadline clause. Without the floor, that clause comes back as a fourth match.

The cost, in plain words: each question touches every stored vector. So the work grows with the number of clauses and with the length of each vector.

## What goes wrong in a first version?

Most bugs hide in the edge cases. Check these before the code ships.

- **A zero vector:** Its length is 0, so the division fails. The code returns 0 for it, as the example does.
- **Vectors of different lengths:** They come from different models or settings. Raise an error rather than score mixed numbers.
- **A k bigger than the collection:** The heap returns everything it has. Nothing crashes, but the caller should expect fewer results.
- **Equal scores:** Give ties a stable tie-breaker, such as the clause id, so results do not change when the input order or the index changes.

The biggest one is the top-k rule itself. It always returns k results, even poor ones. Azure says so in its own words.

> "Vector queries always return k results, assuming at least k documents exist, even if some documents have poor similarity." (Microsoft, Azure AI Search)

The fix is a minimum score, the floor in the code. The floor of 0.5 in the example is a made-up starting point. Set the real one from a test set of questions with known answers, and say how you chose it.

### How would you search 40 million chunks?

A bank's policy library has 40 million chunks, and the support chat must reply quickly. The numbers are made up, but the stakes are real. Brute force would score 40 million vectors for every question. That is usually too slow for a chat box, so the design changes.

I would use an approximate index, such as HNSW, which links vectors into a graph so it can jump to likely neighbours. Azure says HNSW performs an approximate nearest neighbour search, and that ANN methods trade some accuracy for speed. Approximate means it can miss a true neighbour. Google defines recall as the percentage of nearest neighbours the index returns that are actually true nearest neighbours, so I would measure it.

The test is simple. Run exact brute-force search on a sample of questions, treat that as the answer key, and count how many of its results the index also finds. Azure notes that exhaustive search can serve as that answer key.

> **Tip:** Name the trade-off. Exact search is slow and sure. An index is fast and sometimes wrong, and you measure how often.

## What does the interviewer want to hear?

**A strong answer covers**

- [ ] Cosine is the dot product divided by both lengths, so only direction counts.
- [ ] Brute force is exact: it scores every vector and never misses a best match.
- [ ] A heap keeps the best k, which beats a full sort when k is small.
- [ ] Edge cases: zero vectors, mismatched lengths, ties and k bigger than the collection.
- [ ] A minimum score, because top-k always returns k, even poor matches.
- [ ] When it stops scaling: an approximate index, and how you measure its recall.

**Common traps**

- Trap: "Brute force is too slow, so always add an index." Better: Not for a few thousand vectors. Exact search is fast enough and never misses. Add an index only when measured speed needs it.
- Trap: "Cosine is always the right metric." Better: Azure recommends cosine for its OpenAI embedding models. Check which metric your own model and index expect.
- Trap: "Top-k gives you good matches." Better: It always gives k results, even weak ones. Add a minimum score and decide what you show when nothing passes it.

## Can you spot the bug?

**Spot the bug:** A claims team's search returns the first five clauses in the file instead of the five best. Which line is the bug?

A. norm = math.sqrt(sum(x * x for x in a))
B. top = scored[:5]  # first five clauses in file order
C. return heapq.nlargest(5, scored)
D. return dot / norm if norm else 0.0

**Answer:** B. scored[:5] takes the first five in file order. The five best need a sort or a heap. The heap call and the zero guard are fine.

**Quick check:** Two clause vectors point the same way, but one is ten times longer. What is their cosine similarity?

A. About 0, because the lengths differ
B. About 1, because cosine ignores length
C. About 10, the length ratio
D. Negative, because the lengths differ

**Answer:** B. Cosine divides out both lengths, so only direction counts. The raw dot product would be ten times bigger.

## Can you answer these from memory?

**Flash cards**

- **What is cosine similarity?** Dot product over both lengths. Runs from minus 1 to 1. Near 1 means the same direction.
- **What is brute-force top-k?** Score every stored vector, keep the k best. Exact, but the work grows with every item.
- **Why divide by the lengths?** So size is removed and only direction counts.
- **What does the heap do?** Keeps the best k as it goes, so the whole list is never fully sorted.
- **Why add a minimum score?** Top-k always returns k results, even poor ones. A floor blocks weak matches.
- **When does brute force become too slow?** When the collection is large and queries must be fast. Then use an index and measure recall.

## Likely follow-up questions

- Q118 Cosine vs dot product vs Euclidean distance? https://designervenkat.online/interview/ai/cosine-vs-dot-product-vs-euclidean-distance
- Q119 What is approximate nearest-neighbour search? https://designervenkat.online/interview/ai/what-is-approximate-nearest-neighbour-search
- Q117 What is a vector database? https://designervenkat.online/interview/ai/what-is-a-vector-database
- Q146 How do you pick top-k? https://designervenkat.online/interview/ai/how-do-you-pick-top-k
- Q150 How would you design RAG for 10 million documents? https://designervenkat.online/interview/ai/how-would-you-design-rag-for-10-million-documents
- Q006 What is an embedding? https://designervenkat.online/interview/ai/what-is-an-embedding

## Learn it in depth

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