Skip to main content

Chapter 7: From Library to Database

Time: 65 minutes, plus a few minutes to download the database image the first time. Cost: $0. This lab needs Docker or Podman from the Setup page and reuses the shared dataset from Chapter 4.

The short version
  • A vector library is fast, but it lives inside your program. A database adds what a product needs: data that survives a restart, filters, updates while people search, and backups.
  • PostgreSQL stores the document and its metadata in a row. The HNSW index keeps vectors and links that help a query find candidate rows without comparing every document.
  • Filters are where approximate search breaks. Ask for 10 results for one customer and you may get 4, with no warning. A database can fix that, if you know which setting to change.
  • If you already run PostgreSQL, start with pgvector, and check its recall regularly against its own exact search. One SQL setting does it.

The FAISS index from Chapter 5 answered a question in about a tenth of a millisecond. Now put it behind a real product and listen to the questions you get.

A customer uploads a document. When can people search it? Another customer cancels, and legal wants their documents gone today. Customer A must never see customer B's documents. The server restarts at 3 a.m. Someone asks where the backups are.

None of those are search problems. They are database problems. This chapter moves the 18,896 paragraphs from a Python library into PostgreSQL with pgvector, measures what changes, and ends with how I would choose between an extension like pgvector and a purpose-built vector database. First, we will follow a document into the database and a query back out.

What a database adds​

Think of the difference between a calculator and a bank. A calculator adds perfectly and forgets everything when you switch it off. A bank keeps a ledger, survives a power cut, lets thousands of people make deposits at once, and never shows you a transfer that is half done.

FAISS, Annoy, and hnswlib are libraries. The index lives inside your program's memory. If the program stops, the index is gone unless you saved it to a file yourself. There is no idea of a user, a transaction, or a column called customer_id. That is not a flaw. A library does one job, very fast, and leaves everything else to you.

A database takes on the everything else:

You needWith a libraryWith a database
Survive a crash or restartSave and reload index files yourselfA recovery log protects committed changes
Add and delete while people searchRebuild, or coordinate it yourselfInserts, updates, and deletes are normal operations
Search only one customer's documentsFilter the results yourselfA WHERE clause
Never show a half-finished updateYour problemTransactions
Backups and a standby copyCopy files aroundBuilt-in backup and replication tools

That log in the first row is PostgreSQL's write-ahead log (WAL). pgvector writes its vectors and indexes through it, which is why pgvector's documentation can say replication and point-in-time recovery simply work. We will come back to where that log fits in a write.

Three ways the market got here​

The tools arrived in three waves, and the lines between them have blurred since.

Libraries came first. Annoy from Spotify, FAISS from Facebook, and hnswlib, written alongside the HNSW research. They are still what many products run underneath.

Purpose-built vector databases came next. Milvus, Pinecone, Qdrant, Weaviate, Chroma, and others were built around the vector index and added database features around it.

Then existing databases added vectors. pgvector is an extension that adds a vector column type and vector indexes to PostgreSQL. Elasticsearch, MongoDB, and others added vector search the same way. These started from a database people already ran and added the index.

The two directions meet in the middle. pgvector adopted HNSW. Purpose-built databases added filters, updates, and backups. The choice today is less about whether a product can search vectors and more about which system you want to operate.

Who built what, and when

Erik Bernhardsson wrote Annoy at Spotify in 2013. Facebook released FAISS in 2017. Zilliz open-sourced Milvus in October 2019. Pinecone, founded in 2019 by Edo Liberty, launched its managed vector database as a public beta in January 2021.

Andrew Kane started pgvector in April 2021, and it added HNSW in version 0.5.0 in 2023. Elasticsearch shipped approximate kNN search in version 8.0 in February 2022, and MongoDB made Atlas Vector Search generally available in December 2023. Amazon RDS added pgvector in May 2023. pgvector 0.8.0 added iterative index scans in October 2024.

pgvector in four statements​

Here is the whole setup from the lab. One statement turns the extension on, one creates a table with a vector column, one searches it, and one adds an HNSW index:

CREATE EXTENSION vector;

CREATE TABLE paragraphs (
id integer PRIMARY KEY,
title text,
body text,
customer_id integer,
year integer,
embedding vector(768)
);

SELECT id FROM paragraphs ORDER BY embedding <=> '[0.01, -0.03, ...]' LIMIT 10;

CREATE INDEX ON paragraphs USING hnsw (embedding vector_cosine_ops);

<=> is cosine distance: 0 means the same direction, so smallest first is most similar. pgvector also has <-> for Euclidean distance and <#> for negative inner product, the three measures from Chapter 2. The vectors sit in the same row as the title and the text, which matters more than it looks. A search result is just a row, so you can join it to anything else in the database.

The index has one rule that catches people. It is only used when the ORDER BY is the distance operator itself, smallest first, followed by a LIMIT. Sort by a calculated similarity, such as ORDER BY 1 - (embedding <=> ...) DESC, and the HNSW index cannot serve that ordering. PostgreSQL must calculate distances and sort the matching rows instead.

Where the document and the graph live​

Take one paragraph about Virgil from the lab. Its text is in body, its article name is in title, and customer_id and year say which searches may include it. Those columns are metadata, facts about the document that you can filter on. Its embedding is another column in the same row.

The HNSW graph lives in a separate index. In pgvector, a graph element stores vector data, its level, and references back to table rows. Neighbor records hold the links to other graph elements. The article text and customer fields stay in the table; the graph does not need them to measure distance. These are the on-disk structures in pgvector 0.8.7, the version used by this lab.

The table and its indexes are stored on disk in pages, blocks of data that PostgreSQL reads into memory as needed. A pgvector HNSW index does not have to fit entirely in RAM to work, though keeping frequently used pages in memory helps. The graph's vector data also takes space in addition to the table's embedding column. That is why the lab reports sizes before and after adding the vector index.

The graph stores links chosen using distance, but it does not store a distance from every paragraph to every other paragraph. When a question arrives, pgvector computes distances from that question's vector to the vectors it visits. A different question gets different distances, using the same graph. You can see that calculation in pgvector's search code.

Follow a document into the database​

Suppose a customer adds another paragraph about Virgil after the index has been built. Here is the write path, the work between receiving that paragraph and making it available to readers.

  1. The application makes the embedding. It sends the paragraph to the same embedding model used for the other documents. In this lab, the dataset builder has already done that work. pgvector receives the numbers; it does not call an embedding model when you insert a row.
  2. PostgreSQL writes the row and maintains its indexes. The insert supplies the text, metadata, and vector together. PostgreSQL checks the table's constraints and adds entries to its indexes. You do not need to run CREATE INDEX again for each new document.
  3. pgvector finds a place in the graph. For a new vector, HNSW assigns a random level, searches the existing graph for candidate neighbors, selects links, and updates neighbors' links where needed. The ef_construction setting controls the candidate list during that search; m limits connections. Links may be pruned to stay within that limit. This is why an insert has a search cost, even before anybody asks a question.
  4. PostgreSQL records changes for recovery and commits. Table and index pages are changed in memory. WAL records must reach durable storage before those changed pages do. With the lab's default durability settings, commit waits for the transaction's WAL to be flushed. The pages themselves can be written later. A crash can then be recovered using the log.

The graph work is part of maintaining the index during the insert. There is no separate background indexing wait in this pgvector example. With PostgreSQL's default Read Committed isolation, a reader's next query can see the row after the writer commits. A query that started earlier uses its earlier view of the data. Other databases can have different rules for when a write becomes searchable.

These steps follow pgvector's insertion code, PostgreSQL's WAL rules, and its transaction visibility rules. Identical vectors can share a graph element with references to several rows, so one row does not always mean one new graph node.

A committed row is not always in the graph. pgvector does not index NULL embeddings, and cosine indexes also leave out zero vectors. These are documented exceptions, not a delay in indexing.

When the document changes or is deleted​

If the paragraph's text changes, the application must make a new embedding and write it with the new text. PostgreSQL cannot tell that the old embedding now describes the wrong paragraph. Changing only a metadata field, such as year, does not require a new embedding in this example.

An update or delete also has a visibility rule. PostgreSQL keeps row versions that an older reader may still need. A committed delete makes the row unavailable to later queries, but it does not mean all of its storage has already been removed. VACUUM cleans up versions that no reader needs; pgvector also maintains the HNSW graph during index cleanup. Cleanup and rebuilding have a cost, so measure a workload with updates and deletes as well as one that only adds documents. PostgreSQL's vacuuming guide explains why row versions can remain after a transaction ends.

Follow a query back out​

Now ask the lab's question: "What poet wrote a long poem describing Roman religious holidays?" Add WHERE year = 2020 and request ten results. This is the read path when PostgreSQL chooses the HNSW index:

  1. The application embeds the question and sends the query. The query vector must be compatible with the document vectors. A matching number of dimensions alone does not make two embedding models compatible.
  2. PostgreSQL chooses a plan. Its planner estimates the cost of reading the table, using a metadata index, or using HNSW. Having an HNSW index does not force every query to use it. The EXPLAIN output in the lab tells you which plan it chose.
  3. HNSW searches the graph. It starts at an entry point in an upper layer, moves toward the query, and drops through the layers. At the bottom, it keeps candidates to explore, the best candidates found so far, and a record of elements already visited. The next promising candidate leads to more neighbors, whose distances are calculated against the query.
  4. PostgreSQL reads candidate rows and checks them. A row reference leads back to the table, where PostgreSQL checks whether the row is visible to this query and whether year = 2020. Rejected rows do not count toward LIMIT 10.
  5. The query finishes or asks for more. If ten rows pass, the query can return them. If the initial candidates run out, an ordinary scan returns what survived. An enabled iterative scan can resume graph exploration from candidates it kept aside, subject to its limits. We will measure that next.

One distinction matters here. hnsw.ef_search = 40 is the size of the dynamic candidate list for the bottom-layer search, not a promise to compare exactly 40 vectors. The walk may calculate many more distances while finding those candidates. And its stopping rule uses what it has found so far; it does not prove there is no better paragraph elsewhere. That is the approximation from Chapter 5. pgvector's scan implementation connects the graph search to the row references returned to PostgreSQL.

Exact search got slower​

Before any index, PostgreSQL does exactly what Chapter 3 did: score every row and keep the best 10.

PART 2: exact search, no vector index
Plan: Seq Scan on paragraphs
22.0 ms/query, recall@10 1.00 (200 questions)

Seq Scan is PostgreSQL's name for reading the whole table. Recall is perfect, as it should be. The speed is worth a candid look. FAISS's brute force took 0.746 ms on the same vectors in Chapter 4. PostgreSQL took nearly 30 times longer. It reads each row through machinery built to run any query on any table, one row at a time, while FAISS runs one block of math over a tightly packed array. You pay for generality. That is fine, because you would not run exact search at scale in either one.

The HNSW index​

PART 3: HNSW index with pgvector's defaults (m = 16, ef_construction = 64)
PostgreSQL notice: hnsw graph no longer fits into maintenance_work_mem after 16757 tuples
Built in 4.4 s, index size 74 MB
Plan: Index Scan using paragraphs_embedding_idx on paragraphs
ef_search ms/query recall@10
10 1.45 0.82
40 1.72 0.95 (the default)
100 1.94 0.99
200 2.55 1.00

These are the settings from Chapter 5 under SQL names, and the numbers behave the same way. At the default hnsw.ef_search of 40, recall is 0.95. You change it per session or per transaction with SET, so an important query can ask for more recall without touching anyone else's.

Look at the notice, because you will see it in production. PostgreSQL builds the graph inside a memory budget called maintenance_work_mem. The container's default is 64 MB, and the graph outgrew it after 16,757 of the 18,896 paragraphs. pgvector kept going, more slowly. On a real server you would raise that budget for the build, which pgvector's documentation recommends, as long as you leave enough memory for everything else on the machine.

Filters are the hard part​

Every real search has a filter. This customer only. Published after 2020. Only documents this user may read. Here is where approximate indexes and databases collide.

Imagine asking a shoe store clerk for the 40 pairs most like the pair in your hand, and then throwing out every pair that is not in your size. If your size is rare, you walk out with two pairs.

That is what an ordinary pgvector HNSW scan does. The graph search produces candidates, and PostgreSQL then rejects rows that fail the WHERE clause. The candidate list defaults to 40. The lab adds two made-up columns to test this. Each Wikipedia article belongs to one of 20 customers, so each customer owns about 5% of the paragraphs. Each paragraph also gets a random year from 2017 to 2026, so one year is about 10%. The query asks for 10 results:

filter rows back recall@10 ms/query
customer (5% of rows, follows topic) 5.2 0.52 1.50
year 2020 (10% of rows, random) 4.0 0.40 1.70

You asked for 10 rows and got 4. No error, no warning. Just fewer results. The year filter lands almost exactly where pgvector's documentation says it will: 40 candidates, about 10% of them pass, about 4 rows.

The customer row is the more interesting one. It matches half as many rows as the year filter, so you would expect half the results. It returned more. Each question here searches the customer that owns its source paragraph, and that customer's paragraphs are about the same topics as the question. The 40 nearest candidates are full of them. The rule of thumb in the documentation assumes a filter that has nothing to do with the query. Real filters often do. Sometimes that helps, as here, and sometimes it hurts: search for "refund policy" inside a customer whose documents are all engineering notes, and almost none of the 40 nearest candidates will pass.

There are three ways out, and a database can pick between them.

Filter first, then search exactly​

If a filter leaves only a few hundred rows, do not use the vector index at all. Find those rows with an ordinary B-tree index, the kind databases have used since the 1970s, and compute exact distances for just those rows. That is Chapter 3's brute force on a tiny slice.

You do not have to tell PostgreSQL to do this. Its planner, the part that decides how to run a query, estimates how many rows a filter will match and picks the cheapest plan. With a B-tree index on title and a filter for one article:

Plan: Bitmap Heap Scan on paragraphs > Bitmap Index Scan on paragraphs_title_idx
article (0.2% of rows) 10.0 1.00 0.67

The planner skipped the HNSW index entirely. Perfect recall, and faster than the HNSW searches above, because it only scored about 40 paragraphs. A library cannot make that choice for you. It only knows about vectors.

Keep walking until enough rows pass​

For broader filters, pgvector 0.8.0 added iterative index scans. Back in the shoe store, the clerk keeps bringing more pairs until 10 of them are in your size. When too few candidates pass the filter, the index keeps searching the graph for more, up to a limit you can set:

Same filters with hnsw.iterative_scan = relaxed_order:
customer (5% of rows, follows topic) 10.0 0.97 1.98
year 2020 (10% of rows, random) 10.0 0.95 2.00

In this run, ten rows every time, and recall back where an unfiltered search was. The extra graph work costs time. The word relaxed means results may come back slightly out of distance order. The strict_order option keeps them in distance order but can discard candidates that would break that order, and in this lab recall dropped to about 0.9. If I were using pgvector with filters, I would turn on relaxed_order and sort the final 10 myself.

The continuation has a budget. hnsw.max_scan_tuples approximately limits graph elements visited during an iterative scan. hnsw.scan_mem_multiplier sets its memory allowance as a multiple of PostgreSQL's work_mem, the memory budget for query operations. The visit limit does not apply to the initial scan. Exhaust that budget, or run out of candidates, and a query can still return fewer than ten rows. There may also be fewer than ten matching rows in the table. pgvector's iterative scan options describe those limits.

There are two reasons to do extra work, and I would keep them separate. Filtering may require more graph exploration because too few rows pass. Chapter 6's oversampling fetches extra candidates from compressed vectors so full-vector distances can reorder them. A later reranker can also need more candidates than the final result count. Raising LIMIT alone does not increase an ordinary HNSW scan's candidate-list setting. None of these steps can prove that the search found every true nearest neighbor.

Qdrant attacks filtering inside the graph itself. Its indexing documentation describes adding links based on indexed metadata values and applying filters during traversal. Its metadata indexes also help estimate how many points match, so it can choose a search strategy. That is why the position of the filter in our read-path diagram is specific to pgvector's HNSW scan. Filtered-DiskANN, from Chapter 6, builds filter labels into the Vamana graph. pgvector's documentation also suggests partial indexes for a few common filter values, and table partitioning when you have many tenants and want each one isolated.

What a transaction buys you​

Part 5 of the lab shows what the visibility check buys you. Two connections play two users. The writer deletes every paragraph about Virgil inside a transaction and does not commit yet. Both then ask the example question about a Roman poet:

PART 5: one connection deletes an article inside a transaction, another keeps searching
Writer ran DELETE ... WHERE title = 'Virgil' but has not committed.
Writer's top result: 'Alps'
Reader's top result: 'Virgil'
Writer rolled back.
Writer's top result: 'Virgil'

The writer already sees its own change. The reader sees the database as it was, because the change is not finished. After the rollback, the delete never happened. PostgreSQL does this by keeping row versions for readers that still need them, which is called multiversion concurrency control (MVCC). It works like a shared document where your edits stay a private draft until you publish them.

Here is why that matters for search. When a document changes, you usually delete its old chunks and insert new ones with new embeddings. Do that in one transaction and no user ever searches a document that is half old and half new, or briefly missing. With a library, you build that guarantee yourself.

Checking quality in production​

Chapter 3 described two checks. The kitchen check asks whether the index returns what exact search would. Every lab so far ran it against answers computed in numpy. In production there is no numpy copy of the right answers, so you ask the database.

pgvector's documentation suggests a simple way. Inside a transaction, turn index scans off, and the same query becomes exact search:

BEGIN;
SET LOCAL enable_indexscan = off; -- exact search, this transaction only
SELECT id FROM paragraphs ORDER BY embedding <=> $1 LIMIT 10;
COMMIT;

LOCAL means the setting ends with the transaction, so no other query is affected. Run each saved question both ways and count how many of the exact top 10 the index returned. Part 6 of the lab does that for 50 questions:

PART 6: a recall check inside PostgreSQL, as you would run it in production
Plan with index scans off: Seq Scan on paragraphs
recall@10 at ef_search 40, against PostgreSQL's exact search: 0.96
PostgreSQL's exact answers matched numpy's for 50 of 50 questions

There is a trap here that I walked straight into while writing the lab. My first version reported a recall of 1.00, which looked great and was wrong. Only 36 of the 50 "exact" answers matched numpy. The Python driver had prepared the query, because the script ran it thousands of times, and PostgreSQL kept using a plan made while the index was allowed. The setting changed and the plan did not. Asking the driver not to prepare that one query (prepare=False in psycopg) fixed it.

Worse, EXPLAIN did not catch it. Even the broken version printed Seq Scan for the exact query, because EXPLAIN plans the query fresh, while the real query reused the saved plan.

The lesson is broader than one driver. A recall check that stays at 1.00 on this lab's questions deserves investigation. Send the exact query unprepared, or with its own text, so it never shares a saved plan with the normal search. Then test the check with questions you already know lose recall at a smaller candidate list. In Part 3, ef_search = 10 gave about 0.82 on this lab's questions. If a check on those same questions still says 1.00, inspect how it gets its exact answers. An easier set of questions can genuinely get perfect recall, even with a small candidate list.

Here is the routine I would set up:

  • Keep a few hundred real questions from your search logs, with the filters people actually used. Filters are where recall drops, as Part 4 showed, so a check without them is too kind.
  • Run the check on a schedule and after every change that can move recall: a new ef_search, a large batch of new rows, a rebuilt index, a new embedding model.
  • Run it on a read replica if you have one. Exact search is slow by design. At this size it took about 22 ms per question. Its cost grows with the rows it must score, so measure that cost before scheduling checks next to live traffic.
  • Write down the number at launch and alert on a drop. The recall you measured on day one is your baseline. A slow slide usually means the data changed under the index.

That covers the index. The customer check, whether search finds what people actually needed, needs a labeled set instead, and Chapter 8 starts measuring with one.

Does the database check its own answers?​

An iterative scan notices that it needs more rows. It does not know which nearest neighbors it missed. Checking row visibility and filters keeps the returned rows valid for the query; checking recall tells you how closely approximate search agrees with exact search. Those are different jobs.

I would run both versions of a recall check on the same view of the data. If a customer adds documents between the two searches, a difference may come from the write rather than the index. A Repeatable Read transaction lets both searches use one view. The lab's Part 6 has no concurrent writer, so this distinction does not affect its comparison.

What gets sampled?​

Sampling means different things in different parts of this system:

  1. Building an IVF index. pgvector samples stored vectors to learn cluster centers, then assigns the indexed vectors to lists. The training sample does not mean the other vectors are left out of the index. Its IVFFlat build code shows the sampling step. HNSW has no equivalent cluster-training step.
  2. Choosing HNSW levels. The random level assigned on insertion puts fewer vectors in the upper layers. All indexed vectors still have a place in the bottom layer. The randomness decides where the shortcuts are, not which documents are allowed in the results.
  3. Planning a query. The lab runs ANALYZE paragraphs after loading data. For a large table, PostgreSQL samples rows to collect statistics about column values. Those estimates help the planner decide whether a filter leaves a small enough set to search exactly. This ANALYZE command does not test recall or retrain HNSW.
  4. Checking search quality. You select queries to compare against exact answers. Include common searches and rare filters, rather than only questions that are easy for the index. A result on that sample describes the tested workload; it does not guarantee every future query's recall.

Extension or purpose-built?​

This is the question I get most often, and my answer starts with what you already run.

If you already run PostgreSQL, start with pgvector. Your vectors sit next to the data they describe, so a filter is just SQL, a document update is one transaction, and there is one system to secure, back up, and monitor instead of two. You also skip keeping two systems in sync, which is a real source of bugs. Amazon RDS and most other managed PostgreSQL services offer pgvector, so it is usually one CREATE EXTENSION away.

Know its limits before you commit:

  • One machine does the work. pgvector scales up with a bigger server and out with read replicas. Splitting one collection across machines needs another tool on top, such as Citus.
  • Index builds want memory. You saw the notice. At tens of millions of vectors, builds take real time and memory, and pgvector's documentation notes that vacuuming an HNSW index can be slow.
  • Dimension limits. The vector type can be indexed up to 2,000 dimensions. A 3,072-dimension model needs halfvec, the half-precision type from Chapter 6, which indexes up to 4,000.
  • Keyword ranking is not BM25. PostgreSQL's built-in full-text search ranks documents differently from the BM25 scoring most search engines use. Chapter 8 shows why that matters.

When I would look at a purpose-built vector database:

  • The collection outgrows one machine, and you want sharding and replication built in rather than assembled.
  • Search is heavily filtered, and filter-aware graph search makes a measurable difference on your data.
  • Search runs as its own service with its own team anyway, so sharing a database buys you little.
  • You want a fully managed service where you never think about index builds or memory settings.

Either way, measure on your own data the way these labs do: recall against brute force, with your real filters. The chart in a vendor's blog post was not run on your queries.

Hands-on lab: pgvector in Docker​

You will start PostgreSQL with pgvector in a container, load the 18,896 paragraphs, compare exact and HNSW search, measure what filters do to approximate search, and watch a transaction hide an unfinished delete. Then you will insert a document into the existing index and inspect the query that finds it.

Full instructions: download the Vector Databases labs ZIP. If you have not built the shared dataset yet, follow labs/vector-databases/dataset/README.md first. Then open labs/vector-databases/07-library-to-database and follow its README. It starts the container with a single docker run command, which works with podman too.

The output is the tables in this chapter. Timings depend on your machine, and recall can differ by about 0.01 between runs, because pgvector builds the graph with several workers at once.

Part 7 stores the Roman-poet question itself as a temporary document called Lab question. It deliberately stores the saved query vector to test insertion without another model call. A real document should use the document embedding path: the dataset builder uses search_document: for documents and search_query: for questions with Nomic, as its model documentation requires. Searching with the same saved vector gives a distance near zero. That checks whether the new row can be found; it does not test whether the embedding model understands Roman poetry.

Here is an excerpt from the run, including the scan and filter lines from the actual query plan:

PART 7: insert a lab question after the HNSW index exists
Reader sees 0 rows with id 18896 before COMMIT.
Reader sees 1 row with id 18896 after COMMIT.
Filter year = 2026, iterative scan off: 5 of 10 requested rows.
Same filter, iterative scan relaxed_order: 10 of 10 requested rows.
Found id 18896, title 'Lab question', cosine distance 0.000.
-> Index Scan using paragraphs_embedding_idx on paragraphs (cost=1166.68..46111.25 rows=1867 width=35) (actual time=0.333..0.827 rows=10.00 loops=1)
Filter: (year = '2026'::smallint)
Rows Removed by Filter: 103
Index Searches: 1
Buffers: shared hit=2222
Removed the lab document; 18,896 original paragraphs remain.

The script uses EXPLAIN (ANALYZE, BUFFERS), which actually runs the query. This use of ANALYZE is different from ANALYZE paragraphs: it measures an execution rather than collecting table statistics. The plan connects the read path to what happened:

  • Index Scan says PostgreSQL used the existing HNSW index. There was no rebuild after the insert.
  • actual ... rows=10.00 says this scan returned ten rows. rows=1867 in the cost part is the planner's estimate, not a measurement of graph visits.
  • Rows Removed by Filter: 103 says the scan rejected 103 candidate rows for the year filter. The index had to supply more than ten row references to return ten matches.
  • shared hit=2222 counts page accesses satisfied by PostgreSQL's shared buffer cache. The same page can be accessed several times. It is neither 2,222 different pages nor 2,222 graph nodes.

PostgreSQL's EXPLAIN guide explains these counters. The plan does not list every graph hop or distance calculation. For the graph walk itself, use the hand-built search in Chapter 5; here you are seeing how that search serves a database query. Your timings, filter counts, and buffer counts can differ from this run.

Checkpoint​

The year filter matches 10% of rows. Why did a request for 10 results return only about 4?

pgvector's HNSW index collects ef_search candidates, 40 by default, and applies the WHERE clause afterward. About 10% of 40 candidates pass, which leaves about 4 rows. Iterative index scans fix this by searching more of the graph until enough rows pass or a scan limit is reached. The percentage is a rough expectation when the filter is unrelated to the query, not a guarantee for each search.

Your weekly recall check has reported exactly 1.00 for three months, including the week someone lowered ef_search to 10. What would you check first?

Whether the "exact" side of the check is really exact. Check whether it is still using the index, for example because the driver reused a prepared plan. A fresh EXPLAIN can miss that, because it plans the query separately. Send the exact query unprepared, then test the check on questions known to lose recall at ef_search = 10, such as this lab's Part 3 sample. An unchanged 1.00 on your own questions is a reason to check, not proof of a bug: an easy query set can genuinely get perfect recall.

In Part 5, why did the reader still see Virgil after the writer deleted it?

The writer's delete was inside a transaction that had not committed. PostgreSQL keeps the old version visible to this reader, so it does not see the unfinished delete. When the writer rolled back, the delete disappeared entirely.

A filtered query returns ten rows. Can you conclude that the write, the filter, and the nearest-neighbor search all worked correctly?

Ten rows only tells you how many were returned. Check that a committed test document can be found and that every returned row passes the filter. Then compare the approximate ids with exact search on the same view of the data to measure recall. Even a query that returns ten valid rows can miss closer matches. And exact nearest neighbors still need a separate relevance check, as Chapter 3 explained.

Check Your Knowledge​

Click to start the quiz
1. You added an HNSW index, but EXPLAIN still shows a Seq Scan for this query: SELECT id FROM docs ORDER BY 1 - (embedding <=> $1) DESC LIMIT 10. What is wrong?
2. A small customer owns 300 documents in a table of 5 million. Searches filtered to that customer, using the HNSW index, often return zero or one result. Which fix is the most direct?
3. You insert a new paragraph into a table that already has a pgvector HNSW index. What does the index need to keep so later queries can find that paragraph?
4. After a large import, a colleague runs ANALYZE paragraphs and says the database has now checked its vector search quality. What did ANALYZE actually do?

What's next​

You have followed a document through the row, index, and commit, then followed a query through graph search, visibility, and filtering. Before moving on, use Part 7's query plan to explain which index was used and where rows were rejected.

Our search-quality measurements so far ask how close an index gets to the exact nearest neighbors. But remember the warning in Chapter 4. The exact top 10 contained the paragraph each question was written from only 59% of the time. Tuning the index will not reliably beat that number. Chapter 8 raises it, by adding the oldest search method in this track back in: matching the actual words. You will build BM25 keyword search, fuse it with vector search, and see which questions each one gets right.