Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 1 of 6 · Concept · 15 min · revision 2

Nearest-Neighbor Search Explained

What a vector index is asked to do, why the similarity metric decides the ranking, what exact search costs, and how recall@k measures an approximate index against it.

Contentsand lesson path

What you will learn

  • Implement exact k-nearest-neighbor search and use it as the baseline for an approximate index.

Prerequisites: Embeddings

01. Why it matters

In the Embeddings skill you turned text into vectors and compared two of them. A retrieval system has a larger job: given one query vector, find the few most similar stored vectors among thousands or millions, fast enough for a person waiting on an answer. That is nearest-neighbour search, and every RAG pipeline, semantic search box and "similar items" feature depends on it.

Whatever this step misses, later steps never see: a prompt cannot ground an answer in a passage that was not retrieved. So before choosing a vector database or tuning an index, you need a precise picture of the question the index answers, what answering it exactly costs, and how to tell how far a faster, approximate answer drifts from the exact one. The next lesson builds the exact search, and the rest of the skill measures approximate indexes against it.

02. The question a vector index answers

k-nearest-neighbour (kNN) search takes a query vector q, a collection of N stored vectors and a number k, and returns the k stored vectors that score best against q under a chosen metric, best first. In retrieval, k is small (often 5 to 50), N is large, and each vector has a few hundred to a few thousand dimensions.

Three metrics are common:

  • Dot product: higher is closer. Fast, but it rewards vectors that are simply long.
  • Cosine similarity: the dot product of the two vectors after scaling each to length 1, so only direction counts. Higher is closer.
  • Euclidean (L2) distance: the straight-line distance. Lower is closer.

The metric decides the ranking, so it is part of the question, not a detail. The small example below ranks four stored vectors against one query, first as they are and then after scaling every vector to length 1. On unit vectors, the plain dot product is the cosine similarity, so the script computes cosine that way.

Python · metrics.py
import numpy as np

docs = np.array([
    [0.9, 0.1, 0.0],   # A: close in direction to the query
    [0.6, 0.8, 0.0],   # B
    [0.0, 0.6, 0.8],   # C: a different direction
    [2.0, 1.8, 0.0],   # D: between A and B in direction, but much longer
])
query = np.array([1.0, 0.2, 0.0])
names = np.array(list("ABCD"))


def ranking(scores: np.ndarray, higher_is_better: bool = True) -> str:
    order = np.argsort(-scores if higher_is_better else scores)
    return " ".join(names[order])


def l2(vectors: np.ndarray, q: np.ndarray) -> np.ndarray:
    return np.linalg.norm(vectors - q, axis=1)


print("raw dot product: ", ranking(docs @ query))
print("raw L2 distance: ", ranking(l2(docs, query), higher_is_better=False))

unit_docs = docs / np.linalg.norm(docs, axis=1, keepdims=True)
unit_query = query / np.linalg.norm(query)
print("cosine:          ", ranking(unit_docs @ unit_query))
print("unit L2 distance:", ranking(l2(unit_docs, unit_query), higher_is_better=False))
Expected output
raw dot product:  D A B C
raw L2 distance:  A B C D
cosine:           A D B C
unit L2 distance: A D B C

On the raw vectors the metrics disagree. The dot product puts the long vector D first because its length inflates every score; Euclidean distance puts D last because its length puts it far away. Cosine ranks by direction alone.

Once every vector has length 1, all three agree: cosine and the dot product become the same number, and the squared distance is 2 - 2 × (a · b), so a larger dot product always means a smaller distance. This is why most pipelines normalise embeddings once, when indexing and when querying, and then use the cheapest operation, the dot product. Two rules follow:

  • Use the metric your embedding model was trained for (its model card says which), and configure the index with the same one.
  • If the dot product stands in for cosine, check that stored and query vectors really are unit length. One unnormalised batch silently changes the ranking.

05. Check your understanding

Practice check · 3 questions

Metrics, cost and recall

Work each one out before you choose.

Q1. Your index ranks by dot product because every stored vector has length 1. A new batch of documents is added without normalising, and those vectors have length about 3. What happens to search results?
Q2. You plan exact search over 2 million chunks embedded by a 1,024-dimension model and stored as float32. Roughly how much memory do the vectors alone need?
Q3. For one query, the exact top 5 is [9, 3, 27, 51, 14] and an approximate index returns [3, 9, 14, 27, 40]. What is recall@5 for this query?
Practice only: not graded, not saved, not evidence.

06. Apply it

The practice project for this skill indexes 10,000 embeddings and measures an approximate index against exact search. Prepare its inputs now:

  1. Take 10,000 chunks you embedded in the Embeddings skill (or embed them now) and save the matrix as a float32 .npy file with the chunk ids in the same order.
  2. Write down the dimension, the metric your model's card recommends, and whether the vectors are unit length. Check the last point in code: np.linalg.norm(vectors, axis=1) should be 1.0 everywhere if you normalised.
  3. Collect 100 to 200 query strings that were not used to build the corpus, ideally real questions, and embed them the same way.
  4. Estimate the memory of the vectors and the multiply-adds per query, and write down the k you will retrieve and a latency budget per query.

07. Review prompt

Without looking back:

  1. State the kNN question in one sentence, naming its three inputs.
  2. Why can dot product, cosine and Euclidean distance rank the same vectors differently, and when do they always agree?
  3. Estimate the memory and multiply-adds for one exact query over 500,000 vectors of 1,536 dimensions in float32.
  4. Define recall@k for an approximate index, and say what it does not tell you about retrieval quality.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check