Lesson 4.4: Vector stores and indexes
Learn how vector stores find nearest neighbours fast: exact against approximate search, IVF and HNSW indexes, memory sums, filters and choosing a store.
In the last three lessons you learned that an embedding turns a piece of text into a list of numbers, that similarity search finds the pieces closest to a question, and that documents must be chunked before any of this works. There is one question left, and it is the one that decides whether your system works at 10,000 chunks and still works at 10 million: where do all those vectors live, and how do you find the nearest ones quickly? The answer is a vector store and, inside it, an index. 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 vectors needs, explain why checking every vector stops being practical, describe how the two most common indexes work (clusters and graphs) in plain words, understand why they return approximate answers and how to measure what you lose, combine vector search with filters such as date or customer, handle updates and deletes, and choose between the main kinds of store for a project of your size. You should have read Lessons 4.1 to 4.3, on embeddings, similarity search and chunking, because this lesson takes their vectors and chunks as given. You do not need to write code to follow it, although the final exercise is easier if you can run a short script.
The problem: finding a needle quickly
Start with what similarity search needs. You have a collection of N vectors, each with d numbers. A user asks a question, which you embed into one more vector, the query. You want the k stored vectors closest to the query, usually the top 5 or 10. In Lesson 4.2 you saw that "closest" is measured by cosine similarity, dot product or distance.
The simplest way to do this is to compare the query with every stored vector, score each one and keep the best k. This is called brute-force or exact search. It is perfectly correct, because nothing is skipped. For a few thousand vectors it is also fast enough that nobody needs anything cleverer. A laptop can compare a query against ten thousand vectors in a few milliseconds.
The trouble is how the cost grows. Each comparison costs about d multiplications and additions. Comparing against N vectors costs about N × d of them. Double the number of vectors and you double the work for every single query. A company that starts with 20,000 chunks from a handbook, and later adds ten years of emails, support tickets and contracts, can end up with 20 million chunks. The same brute-force search is now a thousand times slower, and it must run for every user's every question.
Three things are therefore needed that a spreadsheet or a plain table does not give you.
1. Storage for large numbers of vectors, kept together with the text and the details about each one (the source, the date, the owner).
2. A fast way to find near neighbours, which means an index: an extra data structure, built in advance, that lets a search skip most of the collection.
3. The ordinary things a database does: adding, changing and deleting records, filtering them, backing them up and keeping them safe.
A system that offers these is a vector store, also called a vector database. Some are dedicated products built for the job. Some are extensions that add vector search to a database you may already use. Some are libraries that you run inside your own program. The differences matter later in this lesson. First, the core idea.
How big is a collection of vectors?
Before choosing anything, work out the size. Memory is the first thing that surprises people, and the arithmetic is simple.
A vector of d numbers, where each number is stored as a standard 32-bit floating-point value, takes 4 bytes per number. So one vector takes 4 × d bytes. A collection of N vectors takes N × d × 4 bytes. This is the raw size of the vectors alone, before any index, any text and any extra details.
Take a model that produces vectors of 768 numbers. One vector is 768 × 4 = 3,072 bytes, about 3 kilobytes. A million of them is 3.07 billion bytes, about 3 gigabytes. Ten million is about 30 gigabytes. A hundred million is about 300 gigabytes, which will not fit in the memory of an ordinary server.
Vector length matters directly. Models differ in how many numbers they produce, and a longer vector can hold more detail but costs more everywhere: more memory, more comparison work, more to move across a network.
There are two practical consequences. First, chunking choices change cost. If chunks are small and overlap, there are more of them, and every extra chunk is another vector to store. The arithmetic in Lesson 4.3 and the arithmetic here multiply. Second, precision is a lever. A number does not always need 32 bits. Storing each number in 16 bits halves the memory, and storing it in 8 bits cuts it to a quarter. Methods that do this, called quantisation, usually cost a little accuracy and save a lot of memory. We return to them below.
Predict first: a team has 5 million chunks, a model that produces vectors of 1,024 numbers stored as 32-bit values, and a server with 16 gigabytes of memory. Will the raw vectors fit? Work it out before you read on.
Each vector takes 1,024 × 4 = 4,096 bytes. Five million of them take 5,000,000 × 4,096 = 20.48 billion bytes, about 20.5 gigabytes. That does not fit in 16 gigabytes, and it leaves nothing for the index, the operating system or the text. The team must choose: a bigger machine, shorter or compressed vectors (storing 8 bits per number would need about 5.1 gigabytes), a store that keeps most vectors on disk, or fewer chunks.
The simulator below lets you try your own numbers. It also estimates the time for a brute-force search using an assumed speed, which you can change.
Move the number of vectors up to 100 million and watch both lines. The memory leaves ordinary machines far behind, and the time per query climbs past anything a user would wait for. This is the pressure that created approximate indexes.
Why we accept approximate answers
Here is the bargain at the heart of vector search. If you must guarantee that you find the true nearest vectors, you generally have to look at all of them, or close to it. In high dimensions, with hundreds of numbers per vector, there is no known cheap trick that always gives the exact answer without checking most of the collection. But if you are willing to occasionally miss one of the true top results, you can skip nearly everything.
This is called approximate nearest neighbour search, or ANN. It returns neighbours that are very likely, but not certain, to be the true closest ones. The measure of how well it does is recall: of the true top k neighbours, what share did the search actually return? A recall of 95 per cent at k = 10 means that on average 9.5 of the 10 true nearest vectors were found.
Is a miss a disaster? Usually not, for three reasons. First, the vectors are themselves an approximation of meaning, so the difference between the 3rd and 4th nearest chunk is rarely a difference between a good answer and a bad one. Second, a missed neighbour is often replaced by one almost as close. Third, in a RAG system the retrieved chunks are further sorted by a reranker, as you will see in the next module. So a small loss of recall at the index level is usually invisible in the final answer, while the gain in speed is large and obvious.
But "usually" is not "always", and recall should be measured. We will see how shortly.
Every index is a way of buying speed with recall and memory. The settings of an index let you dial the trade: search a little harder, get higher recall and slower queries; search a little less, go faster and miss more. Keep that dial in mind, because both indexes below have one.
The simplest index: flat, and when it is enough
Not every system needs a clever index. A flat index is just the brute-force method, stored neatly: every vector in an array, searched by comparing the query with all of them. Its recall is 100 per cent, it has nothing to tune, building it takes no time, and adding or removing a vector is trivial.
Flat search is a sensible choice more often than people expect. If you have up to a few hundred thousand vectors, and your queries can take tens of milliseconds, a flat search on a modern machine, perhaps with the comparisons spread across several processor cores, is often fast enough. It is also the baseline you must use to measure everything else, because only the flat result tells you the true top k against which approximate recall is measured.
A rule of thumb that many engineers follow is this: start flat, and move to an approximate index when your measured query time or memory becomes a real problem, not before. An index you do not need adds settings to tune, build time to wait for and a small loss of recall for no benefit.
Index idea one: clusters (IVF)
The first big family of indexes is based on a simple observation. If you want to find books about cricket in a library, you do not walk past every shelf. You go to the sports section. Divide the collection into groups of similar items, and for each query search only the groups most likely to contain the answer.
The most common version is called IVF, short for inverted file. Here is how it works in four steps.
1. Cluster the vectors. Run a clustering method on the collection to find a number of centre points, called centroids. Suppose you choose 1,000 centroids (often called nlist, the number of lists). Every stored vector is assigned to its nearest centroid, so the collection is split into 1,000 groups, each with about N ÷ 1,000 vectors.
2. Store the groups. Each centroid keeps a list of the vectors that belong to it.
3. At query time, compare the query with the 1,000 centroids only. Pick the few closest. The number you pick is the nprobe setting: with nprobe = 10, you look in the 10 nearest groups.
4. Search only those groups, exactly, and return the best k.
For a collection of 1,000,000 vectors with 1,000 centroids and nprobe of 10, the work is: 1,000 comparisons with the centroids, plus about 10 × 1,000 = 10,000 comparisons inside the chosen groups. That is about 11,000 comparisons instead of 1,000,000, around 90 times fewer. The speed-up comes with a cost: if the true nearest neighbour sits in a group whose centroid was not among the 10 closest, you miss it. This happens most for queries that fall near the border between two groups, where the nearest vector may lie just on the other side.
The dial is nprobe. Raise it and you search more groups, recall climbs and queries slow down. Set it equal to the total number of groups and you have rebuilt brute-force search.
Two features of this curve are typical. The first few probes give large gains. Later ones give little. Choosing the setting is therefore about finding the knee of the curve: the point after which each extra group buys very little recall for a lot of extra time.
There is one more practical detail. The centroids are learned from your data, so an IVF index must be trained before use. If the data later changes a lot, for example when you add a whole new kind of document, the centroids may no longer fit it and recall can quietly fall. Rebuilding or retraining the index from time to time is part of running one.
The simulator below turns the cluster arithmetic into numbers you can try. It counts only comparisons and does not model recall, so read it together with the chart.
Try fixing nprobe and changing the number of groups. You will find a sweet spot: with very few groups each group is large, and with very many groups the centroid comparisons themselves become the main cost. A rule of thumb sometimes used is to set the number of groups near the square root of the number of vectors, which balances the two parts. For a million vectors that is about 1,000, the value used above. Treat it as a starting point to test, not a law.
Index idea two: graphs (HNSW)
The second big family works very differently, and it is the default in many vector stores. Imagine finding a person in a large city using only a chain of acquaintances. You ask someone who knows many people; they point you to someone closer to the person you want; that person points you to someone closer still. In a few hops you arrive. The method works because each person knows both some nearby people and a few well-connected people far away.
A graph index builds exactly this kind of network. Each stored vector is a node, and each node is linked to a handful of its near neighbours. To search, you start at some entry node, look at its neighbours, move to whichever is closest to the query, and repeat, walking greedily downhill in distance until no neighbour is closer than where you stand. The nodes you passed are your candidates.
The most widely used version is HNSW, which stands for hierarchical navigable small world. The word "hierarchical" is the clever part. It builds several layers. The top layer holds only a small sample of the nodes, linked to each other with long-range links, like a motorway map. The next layer down holds more nodes, with shorter links, like a road map. The bottom layer holds every node, with links to its close neighbours, like a street map. A search starts at the top, makes a few big jumps to land in the right region, drops down a layer, makes smaller moves, and finishes on the bottom layer with a careful local search. The number of steps grows slowly with the size of the collection, which is why this method stays fast on very large collections.
HNSW has three settings you will meet in almost every store.
M, the number of links each node keeps. More links give a better-connected graph and higher recall, but use more memory, since the links are stored for every vector.
Build effort (often called efConstruction). When a vector is added, the index searches for its neighbours with this much care. Higher effort builds a better graph and takes longer.
Search effort (often called efSearch). How many candidates the search keeps while walking. Higher effort gives higher recall and slower queries. This is the day-to-day dial, like nprobe for IVF.
Compared with IVF, graph indexes tend to give very high recall at low query time, and need no training step, so vectors can be added one at a time. The price is memory: the graph links sit on top of the vectors, and a typical HNSW index uses noticeably more memory than the raw vectors alone. Building a large graph also takes time.
Property · Flat · IVF (clusters) · HNSW (graph)Recall · Exact, 100 per cent · Tunable with nprobe · Tunable with search effort, often very high
Query speed at large N · Slow · Fast · Fast
Extra memory beyond the vectors · None · Small (centroids and lists) · Larger (links for every vector)
Needs training on the data · No · Yes · No
Adding vectors later · Trivial · Easy, but centroids can go stale · Easy, but deletes are harder
Good first choice when · Under a few hundred thousand vectors · Very large collections, memory tight · Speed and recall matter, memory allows
Which one is best depends on your data and limits, which is why the table says "good first choice when" and not "winner". Many stores offer both, and some combine them, for example using a graph to find the right groups.
Shrinking vectors: quantisation
You saw that memory is often the first limit. The usual cure is to store each vector in a smaller form, at some cost in accuracy. There are two common ways.
Scalar quantisation keeps every number but stores it with fewer bits. Instead of a 32-bit decimal, each number becomes an 8-bit whole number, found by mapping the range of values onto 256 levels. The vector is four times smaller, and comparisons are faster too. Recall drops a little, because tiny differences between numbers are rounded away.
Product quantisation is more aggressive. It cuts each vector into several short pieces, and for each piece stores only the identifier of the closest entry in a small codebook of typical pieces. A vector of 768 numbers might become 96 one-byte codes: 96 bytes instead of 3,072, a 32-fold reduction. Distances are then estimated from the codebooks. Recall falls further, so this is usually combined with a second step: use the compressed vectors to find a few hundred candidates quickly, then re-score those candidates with the full vectors and keep the best k.
The design question is always the same. How much recall are you prepared to lose to save how much memory? You answer it with a test, not by guessing, and the test is the next section.
Measuring what the index costs you
An approximate index should never be switched on without a measurement. The method is short and uses what you already know from Lessons 4.2 and 4.3.
1. Take a sample of real queries, say 200, from your logs or from your test questions.
2. Run each one against a flat index. The results are the "truth": the exact top k for each query.
3. Run the same queries against the approximate index at a chosen setting.
4. Compute recall at k for each query: the number of true top-k vectors that appeared, divided by k. Average over the queries.
5. Time the queries at the same setting. Record the median and also the slowest few per cent, because users feel the slow ones.
6. Repeat for several settings and plot recall against time.
Then choose the cheapest setting that meets your target. A target of 95 per cent recall at 10 is a common starting point, but it is your decision. A search over legal contracts, where a missed clause matters, may ask for more than a search over a help centre, where several chunks say the same thing.
A second, deeper check connects back to your whole system. Recall measures the index against exact search, but your real goal is correct answers. After you choose a setting, run your end-to-end test questions again, as in Lesson 4.3, and confirm that the answers did not get worse. If the index loses a little recall and the answers are unchanged, you made a good trade.
Filters: search within a slice
In real products you almost never want the nearest vectors in the whole collection. You want the nearest vectors among those that belong to this customer, were published after January, are in English, or are visible to this user's role. Each stored vector therefore carries metadata: fields such as customer identifier, date, language, document type and access level. A query then says: find the nearest vectors where customer = X and date is after Y.
How a store applies the filter changes both speed and correctness.
Post-filtering searches first and filters afterwards. Ask for the top 10, throw away those that fail the filter, and return what is left. It is simple, but it can return fewer than 10, or none at all. If only 1 per cent of the collection passes the filter, the top 10 overall are very unlikely to contain many that pass.
Pre-filtering applies the filter first and searches only the vectors that pass. The results are correct, but the index structure was built for the whole collection, and searching a thin slice of a graph can break its connectivity, so some stores slow down or lose recall when the filter is very selective.
Integrated filtering lets the index check the filter while it searches, expanding the search until enough passing vectors are found. Many modern stores do this, with varying quality.
Separate collections or partitions give each customer or tenant their own index. This is the simplest and safest way to enforce who can see what, and it makes the searches fast, at the cost of managing many indexes.
Two cautions. First, test your filters with the most selective values you expect, because a store that is fine at a 50 per cent filter may fail at 0.5 per cent. Second, access control belongs in the filter or the partition, not in the prompt. If a user must not see another customer's documents, those documents must never be retrieved in the first place. Telling the model to "ignore documents the user may not see" is not a security measure.
Keeping the index fresh: updates, deletes and rebuilds
Documents change. Policies are revised, customers leave and mistakes get corrected. A vector store has to handle this, and indexes differ in how gracefully they do so.
Adding new chunks is usually cheap. Flat and graph indexes accept new vectors at once. A cluster index puts each new vector in its nearest group.
Updating a chunk is normally a delete followed by an add, because the vector itself changes when the text changes. Store a stable identifier for each source document so that you can find and replace all of its chunks.
Deleting is where indexes differ. Many graph indexes mark a vector as deleted and skip it, rather than removing it, so that the graph is not broken. Over time the deleted ones pile up, memory use grows and speed falls, until a rebuild or a compaction step cleans up. Plan for periodic rebuilds.
Drift in the data can make an old cluster index go stale. If your collection changes character, retrain it and re-measure recall.
Changing the embedding model is the biggest change of all. Vectors from different models, or even different versions of one model, are not comparable. You cannot mix them. Switching means re-embedding everything and building a new index alongside the old one, then moving traffic across. Store the model name and version with every vector so you always know what you have.
For legal and privacy reasons, deletion must also be real. If a customer asks for their data to be removed, check that the vectors, the text and any backups follow your policy. A vector can sometimes be used to recover something of the text it came from, so treat vectors as sensitive data and not as harmless numbers.
Choosing a store
There are four broad kinds of store, and the best choice depends on your size, your team and your other systems. Product names change fast, so this lesson describes the kinds and not the brands.
Kind · What it is · Strengths · Watch out forA library in your program · A code library that holds an index in memory, with no server · Simple, fast, free, good for prototypes and small data · You must build persistence, filtering, backups and access control yourself
An extension to your existing database · Vector columns and indexes inside a database you already run · One system, familiar tools, filters and joins with ordinary data · Very large collections or very high query rates may strain it
A dedicated vector database · A server built for vectors, often with sharding, replication and filtering · Scale, features, tuning options · One more system to run, pay for and keep in step with your source data
A managed cloud service · A dedicated store run by a provider · Little operations work · Cost, data location, vendor lock-in and your data's privacy rules
Questions that settle the choice usually come in this order.
1. How many vectors, now and in two years? Under a million and growing slowly, an extension or even a library is usually enough. Tens or hundreds of millions point to a dedicated store.
2. What are the latency and traffic needs? A back-office tool used by 20 people is a different problem from a consumer app at thousands of queries per second.
3. How strong must the filters be? Per-customer separation and permissions push you towards stores with solid filtering or partitions.
4. Where may the data live? Regulated data in India, such as financial records, may need to stay on infrastructure you control or in a given region. Check the rules that apply to you before picking a service.
5. Who will run it? A small team with a database already in place is often better served by adding to what it knows than by learning a new system.
6. How often does the data change? Frequent updates and deletes favour indexes and stores that handle them well.
A sensible pattern for most teams is to prototype with a library or an extension, measure with the method above, and move to a dedicated store only when the measurements say the first choice has run out of room.
Three worked examples
Example 1: a small company handbook. A mid-sized Indian logistics company embeds its HR and operations handbook: 2,000 pages, cut into about 12,000 chunks, with vectors of 768 numbers. The raw vectors take 12,000 × 768 × 4 bytes = 36.9 million bytes, about 37 megabytes. An exact search over 12,000 vectors takes a fraction of a millisecond to a few milliseconds. The team uses a flat index inside its existing database. They need no clustering, no graph and no tuning, and recall is exactly 100 per cent. Adding an approximate index here would only have added settings to maintain.
Example 2: a support archive. A fintech company has 8 million past support tickets and knowledge-base chunks, vectors of 768 numbers. Raw memory is 8,000,000 × 768 × 4 = 24.6 billion bytes, about 25 gigabytes. With a graph index adding, say, half as much again for links (an illustrative figure; measure yours), the total is nearer 37 gigabytes. The team's server has 64 gigabytes, so it fits, with room to grow. They choose a graph index, run 200 real queries against a flat baseline, and find that at one setting recall at 10 is 96 per cent with a median query time of a few milliseconds. They raise the search effort until recall reaches their target of 97 per cent and check that the median time is still comfortably inside their budget. They filter by product line and by language, and they test the most selective filter they expect: a small product with 0.3 per cent of tickets. Post-filtering returns too few results there, so they switch to the store's integrated filtering.
Example 3: a multi-tenant product. A start-up sells a document assistant to 300 companies. Each company must see only its own documents. The largest has 4 million chunks and the median has 50,000. The team considers one big index with a company filter, and rejects it for two reasons: a mistake in a filter would leak data across customers, and small companies would be slowed by sharing a huge index. They give each company its own partition. Small tenants use flat search, which is exact and cheap at 50,000 vectors. Only the largest tenants get a graph index. When a customer leaves, they delete the partition, which makes deletion simple to prove. The design costs more operational work, and the team accepts that for the safety it buys.
Common mistakes
Adding an approximate index too early. A flat search is exact, simple and often fast enough up to a few hundred thousand vectors.
Never measuring recall. A faster index that silently misses the right chunk is a quiet cause of wrong answers. Compare against flat search on real queries.
Forgetting memory. Counting only the raw vectors and not the index, the text and the headroom, then running out in production.
Testing filters only at easy settings. A filter that passes half the data behaves very differently from one that passes a hundredth.
Using the prompt for access control. Permissions must be enforced in the retrieval step, by filters or partitions.
Mixing vectors from different embedding models in one index. They are not comparable.
Ignoring deletes and rebuilds, so that the index grows slower and larger over months.
Choosing a store for its features list and not for your own numbers: size, traffic, filters, data location and who will run it.
Treating vectors as harmless. They can leak information about the text and need the same care as the documents.
Key takeaways
A vector store keeps vectors with their text and metadata, finds near neighbours quickly through an index and handles adding, changing and deleting records.
Raw memory is vectors times numbers per vector times bytes per number. Work it out before you choose hardware, and remember the index and text come on top.
Exact search compares the query with everything, and its cost grows with the collection. Approximate indexes skip most of the collection and trade a little recall for a large gain in speed.
Cluster indexes (IVF) search only the groups nearest the query, with nprobe as the dial. Graph indexes (HNSW) hop through a layered network of neighbours, with search effort as the dial and more memory as the cost.
Quantisation shrinks vectors to save memory, at some loss in accuracy, and is best paired with a re-scoring step.
Measure recall against a flat baseline on real queries, then check that your end-to-end answers did not get worse.
Apply filters carefully, test the most selective ones, enforce permissions in retrieval, and plan for updates, deletes, rebuilds and any change of embedding model.
Check yourself
1. Why does exact search stop being practical as a collection grows?
Its cost is about the number of vectors times the numbers per vector for every query, so doubling the collection doubles the work for every question.
2. A collection has 2 million vectors of 512 numbers, stored as 32-bit values. How much memory do the raw vectors need?
2,000,000 × 512 × 4 = 4.096 billion bytes, about 4.1 gigabytes, before any index.
3. In a cluster index with 2,000 groups and nprobe of 20, roughly what share of the collection is searched, ignoring the centroid comparisons?
20 ÷ 2,000 = 1 per cent. The query also compares against the 2,000 centroids, which is small next to the rest.
4. What does a recall of 90 per cent at 10 mean?
On average, 9 of the true 10 nearest vectors were found by the approximate search.
5. Why can post-filtering return fewer results than you asked for?
The search takes the overall top results first and then removes those that fail the filter, so a selective filter can leave few or none.
6. You change to a newer embedding model. Can you add its vectors to the existing index?
No. Vectors from different models are not comparable. Re-embed everything, build a new index and switch across, storing the model version with each vector.
Try this
Set aside 30 to 45 minutes. You need a spreadsheet and, if you can, a short script that has a vector library installed; the first five steps need only the spreadsheet.
1. Choose a collection you might search, such as a company handbook, product manuals, past tickets or your own notes. Estimate how many chunks it would produce, using what you learned in Lesson 4.3.
2. Choose a vector length, for example 768, and compute the raw memory in gigabytes at 32, 16 and 8 bits per number. Put the three results in a small table.
3. Open the first simulator and enter your numbers. Record the total memory, with the overhead multiplier at 1.5, and the exact search time at the speed you assume. Then change the number of vectors to ten times your estimate and record both again.
4. Open the second simulator. Enter your number of vectors, set the number of groups near the square root of it, and find the nprobe at which you would scan about 2 per cent of the collection. Write down the speed-up.
5. Decide, in two sentences, whether you would start with a flat index or an approximate one, and which kind of store you would try first. Name the number that decided it.
6. Write down your plan for filters: which metadata fields each chunk needs (for example source, date, owner and access level), and the most selective filter you would have to support.
7. Optional: if you can run code, embed 2,000 of your chunks, build a flat index and an approximate one, run 50 queries against both, and compute recall at 10 and the median query time.
A good result is a memory table at three precisions, a decision on index and store with the number behind it, a list of metadata fields with the hardest filter named, a short plan for updates and deletes, and, if you ran the optional step, a recall and timing comparison against a flat baseline.
Tags: AI Engineering Vector Search Embeddings Retrieval RAG