Skip to main content

Welcome to a Grasp lesson

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

Lesson 26

Vector Store for Efficient Document Search

Recommended resources

Introduction

In our last lesson, we mastered the art of transforming raw text into meaningful numerical representations called embeddings. We now have a way to convert a corpus of documents into a matrix of vectors, the fundamental raw material for our agent's knowledge base. However, having these vectors is only half the battle. The critical question remains: how do we efficiently search through potentially millions or even billions of these vectors to find the ones most relevant to a user's query?

This lesson will answer that question by guiding you through the implementation of a vector store. You will learn to build a system that can not only store document embeddings but also index them for high-speed similarity searches. True to your preference for first-principles engineering, we will start by building a minimal, in-memory vector store from scratch to understand the core mechanics. We will then explore the advanced indexing algorithms that power production systems, dissecting their trade-offs and preparing you to make informed architectural decisions.


The Foundation: A Simple In-Memory Vector Store

Before diving into complex indexing structures, let's build a vector store in its most fundamental form. This will consist of an in-memory list of vectors and a brute-force search function. This approach, also known as linear scan, provides a perfect, exact baseline against which we can compare more advanced methods. It guarantees 100% recall because it compares the query vector to every single vector in the store.

A blog post titled "How to Build Vector Storage" provides an excellent, minimal implementation that we can use as our starting point.

How to Build Vector Storage - OneUptime

This article provides a clear, from-scratch Python implementation of a basic vector store.

First, read the brief introductory sections What Is Vector Storage? to understand the core components. Then, carefully study the Python code in the section Building a Basic Vector Store. Pay close attention to the SimpleVectorStore class and its methods: add, search, save, and load.

Let's break down the key design choices in this implementation:

  • __init__(self, dimension: int): The store is initialized with the dimension of the vectors it will hold. This is a critical validation step to ensure consistency.
  • add(...): When a vector is added, it is first normalized to have a unit length (magnitude of 1). This is a crucial optimization. When all vectors (both stored and query vectors) are normalized, the cosine similarity between any two vectors can be calculated using a simple dot product, which is computationally much faster than the full cosine similarity formula.
  • _rebuild_matrix(): Instead of storing vectors as a list of individual NumPy arrays, they are stacked into a single large matrix (_vectors_matrix). This enables a highly efficient, vectorized search operation. The _matrix_dirty flag is a simple but effective caching mechanism to avoid rebuilding this matrix unnecessarily.
  • search(...): This is the core of the brute-force approach. It calculates the dot product of the normalized query vector with the entire _vectors_matrix in a single operation (self._vectors_matrix @ query_normalized). This is the O(N) step, where N is the number of documents. NumPy's argsort is then used to efficiently find the indices of the top-k most similar vectors.
  • save() and load(): The implementation demonstrates a straightforward persistence strategy. The vector matrix is saved as a binary NumPy file (.npy), and the associated metadata (IDs, etc.) are saved in a separate JSON file. This fully covers the "persist" aspect of our learning outcome.

While simple, this implementation is a complete, functional vector store. For small datasets (e.g., up to a few tens of thousands of vectors), it's often a perfectly reasonable and effective solution.


The Challenge of Scale: Approximate Nearest Neighbor Search

The O(N) complexity of our simple store becomes a bottleneck at scale. Searching through 10 million vectors of 768 dimensions would require roughly 7.68 billion multiplication-addition operations for a single query, which is too slow for real-time applications.

This is where Approximate Nearest Neighbor (ANN) search algorithms come in. These algorithms build clever data structures (indexes) that allow for sub-linear query times (often O(log N)). The trade-off is a small sacrifice in accuracy; they find vectors that are very likely to be the nearest neighbors, but without the 100% guarantee of a brute-force scan. In practice, achieving 95-99% recall with a 1000x speedup is a common and highly desirable outcome.

A fantastic GitHub repository, "vector-db-from-scratch," provides an excellent overview of the most common ANN algorithms and their performance characteristics.

GitHub - PeterP22/vector-db-from-scratch: A complete vector database implementation from scratch featuring HNSW, IVF, LSH, KD-Tree indexes with quantization (4-64x compression) and SIMD optimizations. · GitHub

This resource compares various indexing algorithms and explains the core concepts behind them.

Focus on the Performance Characteristics table. This table is critical for understanding the trade-offs between different indexing strategies. Also, read the brief explanations under Key Concepts Demonstrated, especially on the "Curse of Dimensionality" and "Approximate vs Exact Search."

As you noted from the reading, the Curse of Dimensionality is a key concept. It explains why traditional spatial indexing structures like KD-Trees, which work well in 2D or 3D space, become ineffective for the high-dimensional vectors produced by embedding models (typically 384 to 4096 dimensions). In high-dimensional space, the concept of "nearby" breaks down, and most points become roughly equidistant from each other, forcing these algorithms to degrade to a linear scan.

This necessitates specialized algorithms designed for high-dimensional spaces. Let's examine the principles behind two of the most important ones: IVF and HNSW.


Indexing Strategy 1: Inverted File (IVF)

The Inverted File index is one of the most widely used ANN algorithms, especially for extremely large datasets. The core idea is to partition the vector space into smaller, manageable regions and only search within the most promising ones.

The process involves two stages:

  1. Training (Partitioning): Before indexing, a k-means clustering algorithm is run on a sample of the data. This divides the entire vector space into a predefined number of clusters, nlist. The center of each cluster is called a centroid. These centroids act as a coarse map of the vector space.
  2. Indexing: Each vector in the full dataset is then assigned to its nearest centroid. The index stores this mapping, creating an "inverted file" where each centroid ID points to a list of the vectors within that cluster.
  3. Searching: When a query arrives:
    • The query vector is compared to all nlist centroids to find the closest ones.
    • A parameter nprobe determines how many of the nearest clusters will be searched.
    • A brute-force (linear) search is performed only on the vectors within those nprobe selected clusters.
This diagram visualizes the IVF search process. A query vector is first compared to all cluster centroids (C1-C5). With `nprobe=2`, the two nearest clusters (C2 and C4) are selected. A final, exhaustive search for the nearest neighbor is then performed only on the vectors within those two clusters, ignoring all others.

The key trade-off is between nlist and nprobe. A larger nlist creates a finer-grained partitioning, but might require a larger nprobe to maintain high recall. A larger nprobe increases search time but improves accuracy, as it's more likely to include the cluster containing the true nearest neighbor.


Indexing Strategy 2: Hierarchical Navigable Small World (HNSW)

HNSW is a graph-based algorithm that has become the de-facto standard for high-performance, high-recall ANN search in many production systems. It builds a multi-layered graph where nodes are the vectors and edges represent proximity.

To build the intuition, let's watch a video that breaks down the concepts.

Vector Database Search - Hierarchical Navigable Small Worlds (HNSW) Explained

The video "Vector Database Search - HNSW Explained" by DataMListic provides a superb conceptual walkthrough of HNSW's components.

Please watch the following segments: The problem with brute-force O(N) complexity. Navigable Small World graphs, which introduce the idea of greedy graph traversal. Skip link lists, which provide the analogy for the hierarchical, layered structure. The HNSW search process, which combines these ideas into a multi-layer search. The resulting O(log N) complexity.

The core idea is brilliant: HNSW creates multiple layers of graphs. The top layer is very sparse, with only a few nodes and long-range connections, like an interstate highway system. Each subsequent layer becomes progressively denser, with more nodes and shorter-range connections, like local roads.

This diagram illustrates the HNSW search process. A search starts at a random entry point in the sparsest top layer (layer 2). It greedily navigates to find the nearest neighbor in that layer. This node then becomes the entry point for the next layer down (layer 1). The process repeats until it finds a local minimum in the densest bottom layer (layer 0), which contains all the vectors.

This hierarchical approach allows the search to quickly traverse vast regions of the vector space in the upper layers and then zoom in for a fine-grained search in the lower layers, resulting in its logarithmic time complexity.


Practical Application: Using an HNSW Index

While implementing HNSW from scratch is a significant undertaking, understanding how to use and tune it is a crucial engineering skill. The "vector-db-from-scratch" repository gives you access to a full Python implementation in src/indexes/hnsw.py if you wish to explore the code.

For practical use, we often rely on highly optimized libraries like Faiss (from Meta) or HNSWLib. The following video demonstrates how to use Faiss to build an HNSW index and, more importantly, how to tune its key parameters.

HNSW for Vector Search Explained and Implemented with Faiss (Python)

The video "HNSW for Vector Search Explained and Implemented with Faiss" by James Briggs provides a practical guide to building and tuning an HNSW index.

Watch the section on implementing HNSW with Faiss to see how an index is initialized and populated. Then, pay close attention to the section on parameter tuning, which analyzes the impact of m, efConstruction, and efSearch.

The key parameters for production tuning are:

  • m: The maximum number of connections (degree) for each node in the graph layers. A higher m creates a denser graph, which can improve recall at the cost of higher memory usage and longer build times.
  • efConstruction: The size of the dynamic candidate list used during index construction. A larger value leads to a higher-quality graph (and better recall) but significantly increases the index build time.
  • efSearch: The size of the dynamic candidate list used during search. This is the most critical knob for balancing search speed and recall. Increasing efSearch makes the search more exhaustive and thus more accurate, but also slower.

Production-Grade Persistence with pgvector

Our initial save/load implementation using NumPy files is fine for prototypes, but a production system requires a more robust persistence layer. Instead of reinventing the wheel, we can leverage battle-tested databases.

pgvector is a PostgreSQL extension that adds vector similarity search capabilities directly to a standard Postgres database. This is a powerful pattern because it allows you to store your vector embeddings alongside your existing relational data, enabling complex queries that combine vector search with traditional SQL filters. Given your background, integrating vector search into a familiar, ACID-compliant database like PostgreSQL should be a very natural fit.

The "How to Build Vector Storage" article provides a complete implementation of a vector store backed by pgvector.

How to Build Vector Storage - OneUptime

This section demonstrates how to use PostgreSQL with the pgvector extension as a durable and scalable backend for a vector store.

Please read the section PostgreSQL with pgvector. Focus on the PgVectorStore class. Notice how standard psycopg2 is used to execute SQL commands like CREATE EXTENSION IF NOT EXISTS vector, create a table with a vector(dimension) column, and create an HNSW index directly in the database. The search method uses the <=> operator for cosine distance search.

This approach demonstrates a production-ready architecture. Your embeddings are durable, transactional, and can be backed up and replicated using standard PostgreSQL procedures. The database itself handles the complexity of the HNSW index, while you interact with it through a familiar SQL interface.


Conclusion

In this lesson, we have constructed a complete understanding of a vector store, from first principles to production-grade implementations. We started with the raw mechanics and built our way up to the sophisticated algorithms that make modern RAG systems possible.

Here are your key takeaways:

  • A vector store combines indexing and persistence. The simplest form uses a linear scan (brute-force) and saves vectors to flat files.
  • ANN algorithms are essential for scale. They trade a small amount of recall for massive gains in search speed, moving from O(N) to O(log N) complexity.
  • IVF and HNSW are two dominant ANN strategies. IVF partitions the space into clusters and searches a subset of them, while HNSW builds a hierarchical graph for efficient traversal.
  • Tuning is critical for production. Parameters like nprobe (for IVF) and m, efConstruction, and efSearch (for HNSW) control the fundamental trade-off between search speed, recall, and memory usage.
  • Leverage robust databases for persistence. Using extensions like pgvector in PostgreSQL allows you to build a durable, scalable, and ACID-compliant vector store without needing a separate, specialized database.

We have now assembled the two primary components of a retrieval system: a method to generate embeddings and a vector store to search them efficiently. In our next lesson, we will put these two pieces together to implement the full Retrieval-Augmented Generation (RAG) loop. We will build an agent that can take a user query, retrieve relevant documents from the vector store we designed today, and use that information to generate an accurate, contextually-aware response.