esc
  • WorkflowsPages
  • Case studiesPages
  • Machine Learning FoundationsLearn
  • AI EngineeringLearn
  • AI Guardrails & Red TeamingLearn
  • UI/UXLearn
  • Design SystemsLearn
  • Production System DesignLearn
  • AI papersPages
  • Interview KitPages
  • Book a callContact
  • Download ResumeContact
Let’s talk

I’ll build the agent for it.

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.

13 min readBeginnerVery common · estimateFacts checked 26 November 2026

Say it out loud

Read it once, then say it without looking. Start with the short one; use the long one when they ask you to go deeper.

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.

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.

Key words

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.

Cosine similarity, step by step

Two vectors

the question and one stored clause

Two numbers to work out

Dot product

multiply matching numbers, then add

Both lengths

square, add, then square root

Divide

dot product over the two lengths

Similarity score

1 = same way, 0 = right angles

  1. 1The pair goes into the dot product: multiply matching numbers.
  2. 2The same pair goes to the lengths: square, add, take the root.
  3. 3The dot product is handed over to be divided.
  4. 4The two lengths are multiplied and used as the divisor.
  5. 5The result is the score. Near 1 means the same direction.
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.

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. 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. 2

    Score every stored vector

    Cosine similarity against the query, one clause at a time.

  3. 3

    Keep the k best

    A heap holds only the best k as it goes, so the list is never fully sorted.

  4. 4

    Return them best first

    Sort the k items and return them with their scores.

Brute-force top-k search

Stored and asked

Clause vectors

every clause, embedded in advance

Query vector

the question, embedded once

Score every clause

work grows with every clause

Keep the best k

a small heap instead of a full sort

k results, best first

the best k, each with its score

  1. 1Each stored clause vector goes in to be scored.
  2. 2The query goes in too, for the same comparison.
  3. 3The scores go to a heap that keeps only the best k.
  4. 4The k best come out, highest score first.
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.
  • “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

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."

    BetterNot 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."

    BetterAzure recommends cosine for its OpenAI embedding models. Check which metric your own model and index expect.

  • Trap"Top-k gives you good matches."

    BetterIt 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?

Quick check

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

Can you answer these from memory?

Flash cards · tap a card to flip it

1 / 6

What will they ask next?

  1. Q118Cosine vs dot product vs Euclidean distance?11 min
  2. Q119What is approximate nearest-neighbour search?10 min
  3. Q117What is a vector database?12 min
  4. Q146How do you pick top-k?11 min
  5. Q150How would you design RAG for 10 million documents?12 min
  6. Q006What is an embedding?11 min

Learn it in depth

Last updated on 26 November 2026

Building search over your own documents or records?

I design and build AI search and agents, including the retrieval layer and the checks around it. Book a short call and tell me how many items you need to search and how fast the answers must come back.