Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 27

Vector Search for Document Retrieval

Recommended resources

Introduction

In our previous lesson, we established the foundations of a vector store, exploring how to index and persist document embeddings for efficient access. We now have the "what" and the "where" of our agent's knowledge base. This lesson tackles the "how": we will implement the core retrieval function that actually performs the search. This function is the engine that drives Retrieval-Augmented Generation, enabling an agent to find relevant information from a vast corpus in response to a query.

Today, we will delve into the mathematics of similarity, moving from intuition to concrete implementation. You'll start by building a retrieval function from first principles using Python and NumPy, focusing on the most critical component: the similarity metric. We'll then scale this up, showing how the same principles apply within high-performance libraries like FAISS, and analyze the crucial trade-offs between search accuracy and speed.


Defining "Similarity": The Geometry of Meaning

Before we can find the "most similar" vectors, we must rigorously define what "similar" means. This is not a matter of opinion but a choice of a specific mathematical distance metric. Each metric captures a different geometric relationship, and understanding them is fundamental to building an effective retrieval system.

To build a strong intuition for the most common metric, cosine similarity, let's start with a short, clear explanation.

Cosine Similarity, Clearly Explained!!!

This StatQuest video, "Cosine Similarity, Clearly Explained!!!", provides an excellent visual and conceptual introduction to cosine similarity using simple 2D examples.

Watch the first two main segments. The first, about sentences, sets up the problem. The second, on plotting word counts, explains the core geometric idea: similarity is the angle between vectors, not their length.

The video beautifully illustrates that cosine similarity is about orientation. Now, let's formalize this and explore other key metrics. Different metrics can lead to different search results, especially when vector magnitudes are not normalized.

The article "Vector Similarity Search: Metrics & Approximate Methods" offers a fantastic deep dive into this topic.

Vector Similarity Search: Metrics & Approximate Methods - Interactive

This article provides a detailed mathematical and geometric breakdown of the most important vector similarity metrics.

Please read the entire section on Distance Metrics. Pay close attention to the formulas and the geometric intuition behind: Cosine Similarity: Why it's the default for text and ignores magnitude. Dot Product: Its relationship to cosine similarity and when magnitude matters. Euclidean Distance: How it measures spatial separation and its relation to cosine for normalized vectors. Manhattan Distance: Its robustness to outliers. Also, focus on the derivation showing that for normalized vectors, Euclidean distance and cosine similarity produce the same ranking. This is a critical insight for system optimization.

Let's distill the key points from that reading.

  • Cosine Similarity measures the angle between two vectors. It's the standard for text embeddings because semantic meaning is encoded in the vector's direction, not its length.
  • Dot Product is computationally cheaper and becomes identical to cosine similarity when vectors are normalized to unit length. This is why pre-normalizing vectors is a common and powerful optimization.
  • Euclidean Distance measures the straight-line "physical" distance between the tips of two vectors. It's sensitive to both direction and magnitude.

The image below provides a clear geometric view of the difference between angle-based and distance-based similarity.

A 2D projection showing a query vector `q`. Vector `v2` is perfectly aligned (high cosine similarity) but far away (large Euclidean distance). Vector `v1` is close in both angle and distance. This visualizes the core distinction between orientation (cosine) and position (Euclidean) metrics.

For normalized vectors, the choice between these metrics doesn't change the search ranking, as shown by the relationship . Maximizing cosine similarity is equivalent to minimizing Euclidean distance. This allows you to choose the most computationally efficient metric your hardware and libraries support, which is often the dot product.

The following radar chart summarizes the properties of these metrics, which is useful when making design decisions.

This radar chart compares Cosine, Dot Product, Euclidean, and Manhattan metrics. Note how Cosine excels at ignoring magnitude and text retrieval, while Dot Product is fastest. Euclidean and Manhattan distances offer different robustness profiles.

Implementing the Retrieval Function from Scratch

True to your preference for first-principles understanding, let's now implement a complete, if simple, vector retrieval function in Python. We will use the concepts we've just discussed to build a brute-force search that compares a query to every document in a small collection.

The tutorial "Implementing Vector Search from Scratch" provides a clear, step-by-step guide.

Implementing Vector Search from Scratch: A Step-by-Step Tutorial

This article walks through building a basic vector search engine using only NumPy.

We will implement the core components of this tutorial. First, understand how a sentence is converted into a vector in the section Converting Sentences to Vectors. The approach here (averaging word vectors) is a simplification, but the principle is the same for more advanced models. Next, study the Python code for the cosine similarity function. This is the heart of our retrieval logic. Finally, see how these pieces are assembled in the Vector Search Function. This function encapsulates the full retrieval process: vectorize the query, compute similarity against all documents, and return the top-k results.

The vector_search function you just reviewed is a complete implementation of the learning outcome. It takes a query, a document collection, and embeddings, and returns the most relevant documents. This is the fundamental "retrieval function." While simple, this O(N) linear scan is the ground truth against which all faster, more complex methods are measured.


Scaling Up: From Exact to Approximate Retrieval

Our from-scratch implementation is perfect for understanding the mechanics, but as we discussed in the previous lesson, its O(N) complexity makes it too slow for production-scale systems. This is where Approximate Nearest Neighbor (ANN) search comes in.

The core similarity calculation remains the same, but ANN algorithms use intelligent indexing structures (like the HNSW graphs we saw last time) to avoid comparing the query to every single document. They trade a tiny amount of accuracy for massive speed gains.

To evaluate this trade-off, we use the recall@k metric. It measures what percentage of the true top-k results (as found by our brute-force function) are successfully found by the ANN algorithm.

recall@k = (Number of true top-k results found by ANN) / k

A recall of 0.99 means the approximate search finds 99% of the actual nearest neighbors, which is often an excellent trade-off for a 1000x speed improvement.

Let's return to the "Vector Similarity Search" article to see how to implement both exact and approximate retrieval functions using a production-grade library, FAISS.

Vector Similarity Search: Metrics & Approximate Methods - Interactive

This reading connects our from-scratch understanding to high-performance implementations and evaluation.

Please read the following sections: Exact Search: This describes the professional version of the function we just built. Notice the discussion on SIMD and memory bandwidth—key considerations in systems engineering. Approximate Nearest Neighbor Search: A conceptual overview of why ANN is necessary and the families of algorithms. This will be a good review from our last lesson. Measuring ANN Quality: A detailed explanation of recall@k. Code Implementation with FAISS: Carefully study the Python code here. It demonstrates how to implement a retrieval function using IndexFlatIP (exact search), IndexIVFFlat (approximate), and IndexHNSWFlat (approximate). The code also calculates recall, showing you how to benchmark your retrieval function's performance.

The FAISS examples demonstrate the power of abstraction. The interface for search() is consistent across different index types (IndexFlat, IndexIVF, IndexHNSW). This allows you, as a systems architect, to switch out the underlying search strategy (e.g., from exact to approximate) with minimal code changes, depending on the scale and latency requirements of your application. The tuning parameters like nprobe for IVF and efSearch for HNSW are the critical knobs you would adjust to balance the speed-accuracy trade-off.


Conclusion

In this lesson, we have dissected and implemented the core retrieval function for vector search. We moved from the high-level concept of "similarity" to its precise mathematical and geometric definitions, and then translated that theory into practice.

Here are the key takeaways:

  • Similarity is a choice of metric: Cosine similarity (direction), Euclidean distance (position), and dot product are the most common metrics. Your choice should align with how your embedding model was trained.
  • Normalization is key: For normalized vectors, cosine similarity, dot product, and Euclidean distance all produce the same ranking of results, simplifying the choice to computational efficiency.
  • A retrieval function is straightforward to implement: At its core, it involves vectorizing a query, iterating through a collection of document vectors, calculating a similarity score for each, and returning the top-k results.
  • Exact vs. Approximate Search: While exact (brute-force) search guarantees perfect recall, its O(N) complexity is prohibitive at scale. ANN algorithms provide a sub-linear alternative, trading a small, measurable amount of recall for significant speedups.
  • Performance is measurable: Using recall@k allows you to quantify the accuracy of your ANN-based retrieval function against a brute-force baseline, enabling you to tune parameters like nprobe and efSearch to meet your system's specific needs.

You have now built the retrieval component of our RAG system. In our next lesson, we will complete the circuit. We will take the relevant documents returned by the retrieval function you designed today, inject them into an LLM's context, and prompt the model to generate a final, knowledge-grounded answer.