On this page · 11 sections

At the end of the last article (opens in a new tab), our support assistant could finally find the refund policy, even when the customer never typed the word “refund”.

It did that in the most direct way possible. Embed the question, then compare it with every stored vector and keep the closest ones. With five help-center documents, that is instant.

Now let the product succeed.

The help center grows to a few thousand articles. You split them into chunks, as you should. You add product documentation, release notes, and a few years of resolved support tickets, because those often contain the best answers. Then you sell the assistant to other companies, and each of them brings its own documents.

You are now searching a few hundred thousand vectors instead of five. And every search comes with a condition: only this customer’s documents.

Two questions appear that the five-document demo never had to answer:

  1. How do we find the closest vectors quickly, without comparing against all of them?
  2. How do we find the closest vectors among only the ones this customer is allowed to see?

That is the problem a vector database is built to solve. This article walks through both questions with real measurements, because the interesting parts only show up when you run the numbers.

Why “Compare Against Everything” Stops Working

The approach from the last article has a name: exact search, also called brute-force or flat search. For every query, compute the similarity with every stored vector, then select the top K.

Its cost is easy to reason about. Each comparison is a dot product over every dimension, so the dominant cost of one query is roughly:

(number of vectors) × (dimensions) multiply-adds

Selecting the top K adds some work, but the expensive part is scoring every vector.

Nothing about the meaning of the vectors changes that. Double the vectors, double the work.

The companion demo measures it directly: exact search with 768-dimensional vectors (the size nomic-embed-text produces), one query at a time on one CPU core:

     10,000 vectors |  0.39 ms per query
     50,000 vectors |  1.99 ms per query
    250,000 vectors | 10.16 ms per query

Each 5× increase in data costs about 5× the time. That is what “linear” looks like.

Ten milliseconds might sound fine. Here is where it gets interesting.

That is ten milliseconds of a CPU core, per query. At that rate, one core handles roughly 100 searches per second. Many retrieval pipelines run several searches per user question, for example one per reformulated query. And the corpus keeps growing: extrapolating the same linear trend (an estimate, not a measurement), ten times the data would cost about ten times as much per query.

Memory grows the same way. A 768-dimensional vector stored as 32-bit floats is about 3 KB. The 250,000 vectors above take 768 MB. Ten million would take about 30 GB before any index, and exact search has to read all of it for every query.

So the real question is not “can we compare against everything?” We can. It is “do we have to?”

Try to Understand It This Way

Imagine you walk into a huge library looking for books about a specific topic.

The exact-search approach is to walk every aisle and look at every book on every shelf. It is guaranteed to work, and it gets slower with every book the library buys.

A real library does something smarter. Books are grouped into sections. You figure out which two or three sections are closest to what you want and only browse those. You might miss a relevant book shelved somewhere unexpected, but you will find most of the good ones in a fraction of the time.

That is the core trade every vector index makes:

Give up the guarantee of finding the exact nearest neighbors, in exchange for finding almost all of them very quickly.

This is called approximate nearest neighbor search, usually shortened to ANN. Most production vector search systems are built on some version of it.

The “sections” idea is one family of indexes, called IVF. The other dominant family, HNSW, works more like getting around a city: take the highway toward the right area, then main roads, then local streets, until you arrive at the right block. Both are explained in more detail below.

Approximate Search, Measured

Synthetic random vectors were fine for measuring the cost of exact search, because that cost only depends on size. Approximate search is different: how well it works depends on the shape of the data.

This is worth pausing on, because it came up while building the companion demo. On one synthetic dataset with tidy, well-separated clusters, the IVF index looked almost perfect. On another, with many small overlapping clusters, every index looked nearly useless. Same code, opposite conclusions, purely because of how the fake data was generated.

So the recall numbers below come from real embeddings: about 236,000 English words (the macOS system dictionary), each embedded with the same local nomic-embed-text model used in the last article. 500 of them are held out as queries.

Each index is measured against exact search on the same data. Recall@10 here means: of the 10 true nearest neighbors that exact search finds, how many did the index also find?

                                recall@10    median latency
Exact (Flat)                      1.000         9.587 ms

HNSW  efSearch  16                0.909         0.063 ms
      efSearch  64                0.962         0.169 ms
      efSearch 256                0.986         0.584 ms

IVF   nprobe     1                0.616         0.059 ms
      nprobe    16                0.882         0.227 ms
      nprobe    64                0.935         0.756 ms

Read the HNSW line at efSearch 64: it finds 96% of the true nearest neighbors in 0.17 ms instead of 9.6 ms. That is about 57 times faster. Raise the budget to 256 and recall climbs to 98.6%, still about 16 times faster than exact search.

That is the whole idea of approximate search in one table.

Implementation note: the exact setup behind these numbers
Machine:    Apple M4 Pro (12 cores, 24 GB), macOS 26.6.2
Software:   Python 3.12.13, faiss-cpu 1.16.0, numpy 2.5.4
Embeddings: Ollama 0.40.1, nomic-embed-text:latest (ID 0a109f422b47), 768 dimensions
Corpus:     /usr/share/dict/words, 235,976 items; 500 held out as queries (seed 42)
Search:     one query at a time, one thread, k = 10
HNSW:       M = 32, efConstruction = 64
IVF:        nlist = 1024, trained on the 235,476 indexed vectors (the 500 queries excluded)

Each script was run twice. Recall was identical between runs, and latency stayed within about 3%. Latency depends heavily on hardware. Recall is primarily determined by the dataset, the query set, how the index was built, and the search parameters, so the same settings can produce very different recall on a different corpus. The demo’s README has the full output and the commands to reproduce it.

Single dictionary words are short inputs, so real document chunks will behave differently. The shape of the trade-off is the point, not the exact digits.

The knob you will actually tune

Notice that each index has a setting that moves along the curve: efSearch for HNSW, nprobe for IVF. Think of it as a search budget: how much of the index to explore before answering.

  • A small budget is fast and misses more neighbors.
  • A large budget generally costs more latency and computation, and approaches exact results.

A bigger budget improves recall on average, but not every query improves by the same amount.

You usually choose this per query type, not once for the whole system. It is also the first thing to check when someone reports that “search got worse”: the budget, the data, or the embedding model probably changed.

Two kinds of recall

In the last article, Recall@K meant “did the correct document, as judged by a person, appear in the top K?” Here it means “did the index find the same neighbors that exact search finds?” Both are useful, and they measure different things:

  • Index recall (this article) tells you how much accuracy the index gives up compared with exact search.
  • Retrieval relevance (the last article) tells you whether the results actually answer the question.

An approximate index can only approximate the exact ranking. If exact search would not have found the right document, no index will. So measure both: index recall to tune the index, and labeled queries to know whether the system works.

Under the hood: how HNSW finds neighbors without checking everything

HNSW stands for Hierarchical Navigable Small World. It builds a graph where each vector is a node, connected to a handful of its near neighbors.

The “hierarchical” part is what makes it fast. The graph has several layers:

  • The top layer contains only a few nodes, with long-range connections. This is the highway.
  • Each lower layer contains more nodes with shorter connections. These are the main roads.
  • The bottom layer contains every vector. These are the local streets.

A search starts at the top, greedily moves to a neighbor closer to the query, and drops down a layer when it can’t get any closer. On the bottom layer it explores the query’s neighborhood, and efSearch sets how many candidates that exploration keeps track of: its budget. Then it returns the best k.

The build-time settings shape the graph:

  • M controls how many connections each node can maintain in the graph. Higher values generally mean more memory and slower construction, but can improve search quality.
  • efConstruction is how hard the builder searches when connecting each new node. Higher values make a better graph and slower builds.

In the demo, HNSW took 43 seconds to build over about 235,000 vectors using all 12 cores, and the graph added about 64 MB (roughly 9%) on top of the raw vectors. It needs no training step, so you can add vectors to it incrementally.

The original paper is linked under Related Sources.

Under the hood: how IVF searches only a few "sections"

IVF stands for inverted file index. It works in two phases:

  1. Training: cluster the vectors into nlist groups (k-means), each with a center point. These are the library sections.
  2. Search: compare the query with the cluster centers, pick the nprobe closest clusters, and search only the vectors inside them.

It can train and build quickly on suitable datasets. In the demo, it took under 3 seconds, compared with 43 for HNSW. It also adds almost no memory. The catch is the boundaries: a true neighbor that lives in a cluster you didn’t probe is simply missed. On real embeddings, the demo needed 64 of 1,024 clusters to reach 93.5% recall.

Because it needs a training step, IVF works best when the data’s distribution is known up front. If the data drifts a lot after training, the clusters fit it less well, and the index may need retraining.

Both families can also be combined with compression, such as product quantization, which stores a compact code instead of the full vector. That trades some accuracy for much less memory, and is how very large indexes fit in RAM. The FAISS documentation linked below covers these options.

The Filtering Trap

Now the second question: only this customer’s documents.

In the demo, every vector gets one of 20 tenant labels at random, so each tenant owns about 5% of the data. Each of the 500 held-out queries is also assigned one of the 20 tenants at random (seeded, so the run is reproducible), and must return results from that tenant only. The tenant labels are deliberately random rather than derived from document topics. This isolates the effect of filter selectivity, although real multi-tenant datasets may have a different distribution for each tenant. The “right answer” is exact search over just that tenant’s vectors.

The most obvious implementation is to search as usual, then drop results that belong to other tenants. This is called post-filtering. Here is what happened:

                                       results returned   queries with 0 results   recall@10
Post-filter (top-10, then filter)           0.51 / 10              61%                0.051
Over-fetch (top-200, then filter)           8.70 / 10               0%                0.761
Filter during search (efSearch 64)         10.00 / 10               0%                0.787
Filter during search (efSearch 256)        10.00 / 10               0%                0.948

Read the first line again. Post-filtering returned half a result per query on average, and 61% of queries returned nothing at all.

It makes sense once you see it. The index found the 10 nearest vectors in the whole corpus. Only about 5% of the corpus belongs to this tenant, so on average only half of those 10 survive the filter. The customer asks a question their own documents answer perfectly well, and the assistant finds nothing.

This isn’t just a quirk of the demo. pgvector’s documentation describes the same behavior: with approximate indexes, filtering is applied after the index is scanned, so a condition that matches 10% of rows returns about 4 rows on average with its default search settings.

The other strategies show what it takes to do better:

  • Over-fetching asks for 200 results and filters down to 10. Most queries get close to a full list, but recall is still only 76%, and the right over-fetch factor depends on how selective the filter is.
  • Filtering during the search applies the eligibility condition as part of the index search, so vectors that don’t match the filter are never returned. Every query gets a full 10 results. With graph indexes such as HNSW, the search may still pass through other tenants’ nodes internally to reach eligible neighbors. That is different from restricting the whole graph traversal to one tenant.

There is one more lesson hidden in the last two lines. Filtering during the search at the default budget reached only 79% recall, well below the 96% that the same budget achieves without a filter. Only about 5% of the corpus is eligible to be returned. The search may still traverse other nodes to navigate the graph, but fewer of the candidates it explores can contribute to the final result. The same search budget therefore finds fewer of the true tenant-specific neighbors. Raising the budget to 256 brought recall back to 95%, at 0.63 ms per query instead of 0.18 ms.

That trade-off belongs to FAISS. The demo’s JavaScript version uses hnswlib, which keeps exploring until it has found enough matching results. At the same budget it reached 99% recall, but took about 6 ms per query instead of 0.4 ms unfiltered. Filtered search behaves differently from one implementation to the next, so measure the one you use, with your real filters.

A filter is part of the search, not something you do afterwards. Restrictive filters need either filter-aware search, a bigger search budget, or a different data layout, such as a separate index per tenant.

Filters are also access control

In a multi-tenant assistant, the tenant filter is a security boundary as well as a relevance feature. Correct post-filtering can prevent other tenants’ documents from being returned, but those vectors may already have been examined inside the retrieval service. A missing or incorrectly applied filter can expose data.

Derive the tenant identity from the authenticated request, not from a value the client or the language model gets to choose. Enforce the filter inside the trusted retrieval layer, and make sure every retrieval path applies it. The language model should never receive documents the user is not authorized to see. Never rely on the prompt to keep tenants separate.

The same discipline applies when documents are ingested or updated: tenant and permission metadata must be assigned by trusted application logic, not accepted blindly from uploaded content.

So What Is a Vector Database?

Everything so far used FAISS, which is an index library. It is excellent at one job: given vectors in memory, find nearest neighbors fast.

A real system needs much more than that:

  • Persistence: the index has to survive restarts and deploys.
  • Updates and deletes: documents change and customers leave. Some indexes impose operational constraints here. FAISS’s HNSW index, for example, does not support removing individual vectors, which complicates document deletion and index maintenance.
  • Metadata and filtering: tenant, language, permissions, dates, and document type, all handled during the search, as the trap above shows.
  • Hybrid search: combining vector similarity with keyword matching for exact terms (the last article’s “order 48291” problem).
  • Scaling and availability: sharding, replication, and backups once a single machine is not enough.
  • Operations: monitoring, access control, and consistency guarantees about when a newly added document becomes searchable.

A vector database is a system for storing, indexing, and querying vectors, usually alongside the metadata and operational capabilities an application needs. It may use exact search, approximate indexes, or both. That is the answer to the title’s question: the index solves “find the nearest vectors”, and the database adds the persistence, filtering, updates, and operational capabilities around that search.

In practice, the options fall into a few broad categories. They overlap, and many products fit more than one, so read the examples as typical rather than exclusive:

Category Typical examples When it tends to fit
Index libraries FAISS, hnswlib Embedded in your own service; you own persistence and filtering
Extensions to an existing database pgvector for PostgreSQL You already run Postgres and want vectors next to your relational data
Dedicated vector databases Qdrant, Weaviate, Milvus, Pinecone Vector search is central, large, or heavily filtered
Search engines with vector support Elasticsearch, OpenSearch You already run them, or need strong keyword and hybrid search

None of these is universally best. They differ in operational burden, filtering behavior, scaling model, and how well they fit what you already run.

Do You Even Need One?

This is the question worth asking before choosing a product.

From the measurements above, exact search over 50,000 vectors took about 2 ms per query. For an internal tool, a single team’s documentation, or a prototype, that may be all you need: keep the vectors in memory, compare against all of them, and skip the infrastructure. It is simpler, and it has perfect recall.

A practical way to think about it:

  • Small and stable corpus: exact search in memory, or in the database you already have.
  • Already on PostgreSQL: pgvector. It does exact search by default, so you can start with perfect recall and add an HNSW or IVFFlat index when latency demands it.
  • Large corpus, heavy filtering, many tenants, or high query volume: this is where a dedicated vector database earns its operational cost.

The mistake to avoid is adopting a distributed vector database for 20,000 chunks because “that’s what RAG uses”. Every new system you run is something to monitor, upgrade, back up, and debug at 2 a.m.

Engineering Decisions Before Production

1. Measure on your own data

The synthetic-data surprise is the strongest argument here. Index settings that look perfect on one dataset can be poor on another. Hold out a few hundred real queries, compute exact results once as the ground truth, and measure your index’s recall against them. Repeat after changing the model, the chunking, or the index settings.

2. Choose the search budget deliberately

efSearch or nprobe is a direct trade between latency and recall. Pick it from a measured curve, not a default, and expect filtered queries to need a larger budget than unfiltered ones.

3. Plan memory, not just storage

At 768 dimensions and 32-bit floats, every vector is about 3 KB before any index. That is 768 MB for 250,000 vectors and about 30 GB for 10 million. HNSW adds graph overhead on top of that (about 9% in the demo). If that doesn’t fit, the levers are fewer dimensions, which “Embeddings Explained: The Building Block Behind Semantic Search (opens in a new tab)” covered with Matryoshka embeddings, and compression.

4. Budget for building and rebuilding

The HNSW index in the demo took 43 seconds to build on 12 cores for about 235,000 vectors. Real corpora are bigger. And as the last article explained, changing the embedding model means re-embedding everything and rebuilding the index. Treat that as a planned migration.

5. Design filtering and tenant isolation up front

Decide which filters exist, how selective they are, and whether a shared index with filter-aware search is enough, or whether some tenants need their own index. Test the worst case: the smallest tenant with the most restrictive filter.

What to Take Away

  • Exact search is simple, perfect, and linear. Its cost grows with the number of vectors times their dimensions. For small corpora it is often the right answer.
  • Approximate indexes trade a little recall for a lot of speed. On real embeddings, HNSW found 96% of the true nearest neighbors about 57 times faster than exact search.
  • The search budget is the knob. efSearch and nprobe move you along the recall and latency curve. Choose them from measurements on your own data.
  • Synthetic benchmarks can mislead in both directions. Always measure recall on real embeddings from your domain.
  • Filters are part of the search. Post-filtering a small tenant returned almost nothing in the demo. Use filter-aware search, a larger budget, or a separate index.
  • A vector database combines vector search with capabilities such as persistence, updates, filtering, hybrid search, scaling, and operational management. You need one when those problems are real, not by default.

Think About These Use Cases

Each of these comes down to the same two questions: how fast, and among which vectors.

  • Multi-tenant knowledge base: You host 500 customers. Three of them own 60% of the data, and the rest are tiny. Would you use one shared index with filtering, one index per tenant, or a mix? What happens to your smallest customer’s search quality?

  • Permission-aware enterprise search: Every document has an access list, and every user sees a different subset. How would you make sure the language model never receives a document the user isn’t allowed to read, without making search unusably slow?

  • Fresh content: A support team publishes a fix for an outage and wants the assistant to use it within a minute. How long does your system take from “document saved” to “document searchable”, and what does it depend on?

  • Choosing a budget: Your product manager wants the search step under 50 ms, including embedding the query. How much of that can the index lookup have, and how would you pick efSearch to fit it?

  • Starting small: A team has 30,000 document chunks and wants to “add a vector database”. What would you measure first to decide whether they need one?

If you want to talk one of these through, take it to GPT along with this article. Ask GPT ↗️

What’s Next?

Our support assistant can now find the right documents quickly, even among hundreds of thousands, and only among the ones each customer is allowed to see.

Finding the right context is half the job. The other half is telling the model what to do with it. In the next article, we’ll look at Prompt Engineering: Beyond Writing Better Prompts, and why a prompt behaves more like an interface than a magic phrase.

← All articles