Lesson 4.4: Vector stores and indexes for fast search
Learn how vector stores find similar embeddings fast: flat, IVF and HNSW indexes, recall against speed, memory maths, filters and how to choose a store.
You can now turn text into vectors, compare two vectors and cut documents into sensible chunks. What is left is the part that decides whether your retrieval system survives contact with real traffic: where do millions of vectors live, and how do you find the nearest ones in a few milliseconds instead of a few seconds? A vector store is the answer. It keeps your embeddings next to their text and metadata, and it builds an index, a structure that lets a search skip most of the collection and still find nearly the right neighbours. By the end of this lesson you will be able to explain what a vector store does that a plain database table does not, work out how much memory a collection of embeddings needs, estimate the cost of an exhaustive search, describe how the two most common index families (clusters and graphs) work, explain why approximate search trades a little accuracy for a lot of speed and how to measure that trade, combine similarity search with filters on metadata, reduce memory with compression, and choose between a library, an extension to a database you already run and a dedicated service. You should have read Lessons 4.1 to 4.3, on embeddings, similarity search and chunking, because this lesson assumes you know what a vector, a dimension and a cosine similarity are.
The problem: nearest neighbours at scale
Lesson 4.2 showed the basic move. Embed the question, compare it with the embedding of every chunk, sort by similarity and keep the top few. That works perfectly well for a few thousand chunks, and you can do it in a short loop with no special software. It stops working as the collection grows, for two reasons.
The first is time. Comparing a question with one chunk means multiplying and adding as many pairs of numbers as the vector has dimensions. If each embedding has 1,536 numbers, one comparison is about 1,536 multiplications and as many additions. A collection of N chunks needs N such comparisons for every single question. A million chunks means about 1.5 billion multiply-and-add steps per question. A modern processor can do this in a fraction of a second if everything is already in memory and the code is well written, but a fraction of a second per question becomes a real cost when a hundred people are asking at once.
The second is memory. Every embedding must be stored somewhere, and for a fast search it must be in memory, not on a slow disk. A number in a typical embedding takes 4 bytes (a 32-bit floating-point number). A 1,536-dimension vector therefore takes 1,536 × 4 = 6,144 bytes, a little over 6 kilobytes. A million of them take about 6.1 gigabytes. Ten million take 61 gigabytes, which is more than most single machines have to spare, and that is before the text, the metadata and the index itself.
So the engineering question is how to search quickly and store compactly without losing the quality that made embeddings useful in the first place. A vector store packages the answers.
What a vector store actually does
A vector store (also called a vector database) is a system with four jobs.
1. Store vectors with their payload. Each record holds an identifier, the vector, the original chunk text and metadata such as the document title, section, date, language or access group. You search with the vector, but you return the text and the metadata.
2. Build and maintain an index. The index is a data structure over the vectors that makes nearest-neighbour search fast. It is built when you load data and updated as you add, change or delete records.
3. Answer queries. Given a query vector and a number k, return the k most similar records, optionally restricted by a filter, along with their scores.
4. Look after the data. Persist it to disk so that a restart does not lose it, handle several readers and writers at once, and often copy it across machines for safety or for more capacity.
A plain relational table can hold a column of numbers, and with an extension it can search them. A dedicated vector store is built around the search. The difference between the options is mostly about scale, features and what you already run, which we return to near the end. What matters first is the index, because it is where the speed comes from.
Exhaustive search: the honest baseline
The simplest "index" is no index. You keep every vector in a big array and compare the query with all of them. This is called exact search, brute force or a flat index. It has real virtues.
The answer is always exactly right: you really do get the top k by similarity.
There is nothing to build, tune or keep in sync. Adding a record means adding a row to the array.
For small collections it is fast enough that nothing else is worth the trouble. Up to tens or low hundreds of thousands of vectors, a flat index on one machine is often the right choice, and a common mistake is to adopt something complicated before you need it.
Its weakness is that the cost grows in a straight line with the collection. Double the vectors and you double the work. Use the simulator below to see how memory and exhaustive-search time depend on your numbers.
Predict first: a team has 200,000 chunks with 768-dimension embeddings stored as 4-byte numbers, and a quiet internal tool that receives about one question every few seconds. Do they need a clever index? Decide, and estimate the memory, before you read on.
The memory is 200,000 × 768 × 4 = 614,400,000 bytes, about 0.6 gigabytes, which fits easily on a laptop. Each query needs about 2 × 200,000 × 768 = 307 million operations, which is a few hundredths of a second even on modest hardware. At one query every few seconds, a flat index is more than adequate. Adding an approximate index would add complexity, more settings and a small loss of accuracy in exchange for a speed-up nobody needs. The lesson is to measure first.
The idea behind approximate search
When a collection grows past what exact search can serve, we change the question. Instead of "give me the exact top 10", we ask "give me ten that are almost certainly among the top 10 or very close to them, and do it much faster". This is approximate nearest neighbour search, often shortened to ANN.
Why is that acceptable? Because the vectors themselves are already an approximation of meaning. If a chunk ranks 11th rather than 10th by cosine similarity, the difference in how well it answers the question is usually tiny, and the reranking and generation steps that follow are more sensitive to other things. Missing the 1st best chunk is a real loss; swapping the 9th and 12th is not. ANN indexes aim to make the first kind of miss rare.
The measure of an approximate index is recall at k: of the true top k neighbours (found by exact search), what fraction did the index return? A recall of 0.95 at k = 10 means that on average 9.5 of the real top ten came back. Do not confuse this with the "hit rate" from Lesson 4.3, which asks whether a passage containing the answer was retrieved. Recall at k asks only whether the index agrees with exact search. Both matter, and the second is the one that tells you whether the index is hurting you.
Every ANN index has settings that trade recall against speed and memory. Turning them up makes the search look at more of the data, so recall rises and speed falls. Turning them down does the opposite. There is no setting that is best for everyone; you choose a point on the curve by measuring on your own data. The two most common families work in quite different ways.
Index family 1: clusters (IVF)
The inverted file index, or IVF, borrows an idea from sorting letters at a post office. Instead of checking every letter against every address, you first sort letters into pigeonholes by region, and look only in the pigeonholes that matter.
Here is how it works.
1. Training. Run a clustering algorithm over the vectors (or a sample of them) to find nlist cluster centres, called centroids. For a million vectors you might choose around a thousand centroids.
2. Assigning. Put every vector in the cluster of its nearest centroid. Each cluster keeps a list of its members, which is why it is called an inverted file.
3. Searching. For a query, first compare it with the nlist centroids to find the nprobe nearest ones. Then compare it only with the vectors inside those nprobe clusters, and return the best.
The work is therefore about nlist comparisons (to find the clusters) plus about N × nprobe ÷ nlist comparisons (to scan them), assuming the clusters are of similar size. With N = 1,000,000, nlist = 1,000 and nprobe = 10, that is 1,000 + 10,000 = 11,000 comparisons instead of a million, roughly ninety times fewer.
The catch is the boundary. A vector that lies near the edge of two clusters may sit in the cluster that was not probed. The true nearest neighbour is missed if its cluster is not among the nprobe you chose. Raising nprobe fixes more of these misses at the price of scanning more. That is the entire speed-versus-recall dial for IVF.
Notice how the curve flattens. Going from 1 to 8 probes lifts recall by almost forty points, while going from 32 to 64 adds one point and doubles the work. A sensible setting sits where the curve starts to bend, and a simulator makes the cost side of the trade easy to see.
IVF has a few practical features. Training needs representative data, so if your collection changes a lot over time, the centroids can drift out of date and the index may need retraining. It is lean on memory, since it stores little beyond the vectors and the cluster lists. And it combines well with compression, which we meet shortly.
Index family 2: graphs (HNSW)
The other popular family builds a graph. Each vector is a point, linked to some of its near neighbours. To search, you start somewhere, look at the neighbours of your current point, move to whichever neighbour is closest to the query, and repeat until no neighbour is closer. It is like finding a house in an unfamiliar town by asking each person you meet who lives nearer to the address, and walking toward them.
A single flat graph would take many steps to cross a big collection. HNSW (hierarchical navigable small world) adds layers. The bottom layer holds all the vectors with links to close neighbours. Each layer above holds a random sample of the layer below, with longer-range links. A search starts at the top, where there are few points and big jumps, drops down a layer when it cannot get closer, and finishes at the bottom with careful local steps. It is like using a motorway, then a main road, then a lane.
Three settings matter.
M: how many links each point keeps. Higher M builds a better-connected graph, which raises recall and uses more memory.
efConstruction: how widely the builder looks when it adds each point. Higher values build a better graph, more slowly.
efSearch: how many candidates the search keeps in play. Higher values raise recall and cost more time per query. This is the main dial at query time.
Compared with IVF, HNSW typically gives very high recall with fast queries and needs no training step, and new vectors can be added one at a time. The costs are memory, because the links must be stored on top of the vectors (a rough estimate is about M × 2 links of 4 bytes each per vector at the bottom layer, plus a little for the upper layers), and slow, memory-hungry building for very large collections. Deleting vectors is awkward, since removing a point from the graph can leave its neighbours poorly connected, so many systems mark records as deleted and clean up later.
A reasonable rule of thumb: use a flat index while it is fast enough, HNSW when you want high recall and fast queries and can afford the memory, and IVF (often with compression) when the collection is so large that memory is the main constraint.
Compression: fitting more into memory
Memory is often the binding limit, so stores offer ways to shrink vectors.
Lower precision. Store each number in 2 bytes or even 1 byte instead of 4. Going from 4 bytes to 1 byte (called scalar quantisation) cuts memory to a quarter, with a small loss of accuracy that is usually acceptable.
Product quantisation. Split each vector into short pieces and replace each piece with the number of its nearest entry in a small codebook. A 1,536-number vector might shrink to 96 one-byte codes, about 64 times smaller than the original, at the cost of more noticeable accuracy loss.
Fewer dimensions. Some embedding models let you keep only the first part of the vector with a modest loss of quality, which reduces both memory and comparison time directly.
Rescoring. A common pattern is to search a compressed index quickly to get, say, 100 candidates, then fetch the full-precision vectors for just those candidates and rerank them exactly. You get most of the speed and memory saving and recover most of the accuracy.
Compression is a trade, like everything else here. You measure recall before and after, and you keep the setting that meets your quality target at the lowest cost.
Metadata filters: search with conditions
Real questions come with conditions. "What does the 2025 policy say about refunds?" "Show me only documents my team may see." "Only English." A similarity search that ignores these conditions returns text that is close in meaning but wrong in other ways, which is dangerous when the condition is about permission.
Filtering interacts with the index. There are three broad approaches.
Post-filtering. Search for the top k, then discard results that fail the filter. It is simple but can leave you with too few. If only 2 per cent of your records pass the filter and you retrieve 10, you expect to be left with 0.2 results on average, which means usually none.
Pre-filtering. Restrict the search to records that pass the filter, then find the nearest among them. The results are correct but the index structure is built for the whole collection, so a very selective filter can make a graph search slow or even disconnected, because the allowed points may not link to each other.
Filtered index search. The store applies the filter during the search, skipping nodes that fail it and continuing until it has k that pass. Good stores do this, and may switch to an exhaustive scan when the filter is very selective, since scanning a few thousand allowed vectors is quick.
Two practical consequences follow. First, index the metadata fields you filter on, as in a normal database, or the filter itself becomes the slow part. Second, if the filter is about security, treat it as a hard rule enforced by the store and your application, never as something the model is merely asked to respect. Also test with realistic filters: a search that is fast and accurate without a filter can behave quite differently with a selective one.
Hybrid search and updates
Two more features show up in real systems.
Hybrid search combines vector similarity with keyword matching. Embeddings are good at meaning but can miss exact strings: a product code, an error number, a person's name or a clause number. Keyword search (such as the classic BM25 scoring) is the reverse. Many stores can run both and merge the two ranked lists, often with a simple rule that rewards items ranked highly in either. Lesson 5.2 returns to this when we discuss retrieval quality.
Updates and deletes. Real collections change. Documents are edited, withdrawn or replaced. Your pipeline needs a stable identifier for each chunk, a way to delete the old chunks of a changed document and add the new ones, and a record of which embedding model made each vector. That last point matters: if you change embedding models, every vector must be re-created, because vectors from different models are not comparable. Plan for re-embedding the whole collection, cost it using the arithmetic from Lesson 4.3 and run the old and new indexes side by side until you have tested the new one.
Choosing where to keep your vectors
The options fall into three groups, and the right one depends on your size, your team and what you already run. This lesson does not recommend a product; products and their features change quickly, so check current documentation.
Option · What it is · Good when · Watch out forIn-process library · A search library that runs inside your application, with vectors in memory or in files · Prototypes, small and medium collections, tight control · You manage persistence, updates, concurrency and scaling yourself
Extension to a database you already run · A vector column and index inside your existing relational or search database · Your data and permissions already live there and you want one system · Fewer index options, and large collections or heavy traffic may strain the main database
Dedicated vector service · A system built for vectors, self-hosted or managed · Large collections, high traffic, rich filtering, managed scaling · Another system to run or pay for, and a copy of data that must stay in sync
Questions that help you decide: how many vectors, now and in a year? What queries per second and what latency target? How selective are your filters? Who may see which data, and does permission have to be enforced in the store? How often do records change? What is your team already good at running? Does your data have to stay within a particular country or network? Start with the simplest option that meets today's needs, put the store behind a small interface in your code so that you can change it, and revisit the choice when measurements, not guesses, say it is time.
Three worked examples
Example 1: a small internal assistant. A lender's operations team has 40,000 chunks of process documents, with 1,024-dimension embeddings stored as 4-byte numbers. Memory is 40,000 × 1,024 × 4 = 164 million bytes, about 0.16 gigabytes. Exhaustive search needs about 82 million operations per query, a few milliseconds. The team keeps a flat index inside their database with a vector column, filters by department and finds retrieval time is dwarfed by the model call that follows. They avoid an approximate index entirely, and their results are exact. The lesson: for small collections, simplicity wins.
Example 2: a large public knowledge base. A fintech support site holds 20 million chunks of 768 dimensions. At 4 bytes each, the vectors need 20,000,000 × 768 × 4 = 61.4 gigabytes. Exhaustive search needs about 30.7 billion operations per query, too slow for hundreds of simultaneous users. The team builds an IVF index with 4,096 clusters and probes 16, which scans about 4,096 + 20,000,000 × 16 ÷ 4,096 = 82,000 comparisons, roughly 240 times fewer than a full scan. They store 1-byte numbers in the index, cutting memory to about 15 gigabytes, and rescore the top 100 candidates with full-precision vectors held on disk. On a test of 500 real questions, recall at 10 against exact search is 96 per cent (an illustrative figure), and the latency fits their target. They then lower nprobe to 8 and watch recall drop to 91 per cent, which they judge too low, and return to 16.
Example 3: a filter that breaks the search. A company adds permission filtering to a document assistant. Each employee can see about 1 per cent of the documents. The team retrieves 10 candidates and then removes those the user cannot see, and testers complain that answers are often empty. The arithmetic explains it: 10 candidates × 1 per cent = 0.1 expected results. The fix is to pass the permission filter into the store so that it searches only allowed records, and to store each chunk's access group as an indexed metadata field. After the change, every query returns its full set of 10 allowed results, and the team adds a test that checks a user can never retrieve text from a group they do not belong to.
Common mistakes
Adopting an approximate index too early. Below a few hundred thousand vectors, exact search is often fast, simple and correct.
Never measuring recall. Without comparing the index against exact search on a sample, you do not know what the speed has cost you.
Tuning on too few queries. Test on hundreds of realistic questions, including rare and awkward ones.
Forgetting memory beyond the vectors. Indexes, metadata, text and replicas all take space. Estimate the total, not only N × d × bytes.
Post-filtering selective conditions, which leaves few or no results.
Treating a permission filter as optional. Enforce access in the store and your application, and test it.
Mixing vectors from different embedding models in one index, or changing the model without re-embedding.
Having no plan for updates and deletes, so that stale and withdrawn content keeps being retrieved.
Choosing a product by fashion. Choose by your size, traffic, filters, team and constraints, and check the current documentation.
Key takeaways
A vector store keeps embeddings with their text and metadata, builds an index to search them quickly, answers filtered queries and persists the data.
Memory for vectors is the number of vectors times the dimensions times the bytes per number, and exhaustive search costs about two operations per dimension per vector for every query.
A flat index is exact and simple, and is often the right choice up to a few hundred thousand vectors.
Approximate indexes such as IVF (clusters) and HNSW (layered graphs) skip most of the data and trade a small loss of recall for a large gain in speed, and you measure that loss as recall at k against exact search.
Compression, such as 1-byte numbers or product quantisation, cuts memory sharply, and rescoring a short list at full precision recovers much of the accuracy.
Filters belong inside the search, indexed and tested with realistic conditions, and permission filters must be enforced as hard rules.
Choose the simplest store that meets today's needs, keep it behind a small interface, and plan for updates, deletes and re-embedding.
Check yourself
1. Roughly how much memory do 5 million vectors of 768 dimensions need, stored as 4-byte numbers?
5,000,000 × 768 × 4 = 15.36 billion bytes, about 15.4 gigabytes, before the index, text and metadata.
2. Why can an approximate index be acceptable when exact search is available?
Embeddings are already approximate, so swapping near-equal neighbours rarely changes the answer, and the speed gain can be very large while recall stays high.
3. In an IVF index with 2,000 clusters and 20 probed, how many of the clusters does a query scan, and what happens if you raise the number probed?
It scans 20 of 2,000, one per cent. Raising it increases recall (fewer missed neighbours near cluster edges) and increases the work per query.
4. What does recall at 10 of 0.93 mean?
On average, 9.3 of the true top ten neighbours, as found by exact search, were returned by the index.
5. Only 4 per cent of records pass a filter, and you fetch 25 candidates and then filter. How many results do you expect?
25 × 0.04 = 1 result on average. Apply the filter inside the search instead, or fetch many more.
6. You switch to a new embedding model. What must you do to the stored vectors, and why?
Re-embed every chunk with the new model, because vectors from different models are not comparable, and test the new index before switching over.
Try this
Set aside 30 to 45 minutes. You need a spreadsheet and, optionally, a short script and a few hundred text chunks.
1. Choose a collection you might search and estimate the number of chunks now and in a year. Pick an embedding size (for example 768 or 1,536 dimensions) and a bytes-per-number figure.
2. Use the first simulator to find the memory and the time for an exhaustive query. Write the numbers down and decide whether a flat index is enough for your traffic.
3. If a flat index is not enough, use the second simulator to try three combinations of clusters and probes. Record the share of an exhaustive search each one scans.
4. Use the memory chart above as a model, and work out your memory with 4-byte numbers and with 1-byte numbers. Add 30 per cent for index links, metadata and headroom, and note the total.
5. List the metadata fields you would filter on (date, language, product, access group). Mark which are security rules, and estimate the share of records a typical filter lets through. Use the filter simulator to see how many candidates you would need under post-filtering.
6. Write down your choice among the three kinds of store in the table, with two reasons, and one thing that would make you change it.
7. Optional: if you can run code, build a flat index and an approximate index on a few thousand of your chunks, run 50 questions through both and compute recall at 10.
A good result is a one-page sizing note with memory and time estimates, an index choice with its settings and the reason, a list of filters with the security ones marked, and a plan to measure recall against exact search before you trust the approximate index.
Tags: AI Engineering Vector database Embeddings Retrieval Indexing