Skip to content
postgres

The pgvector Index That Never Gets Used

·6 min read

Semantic search on a production table was taking five seconds. The HNSW index was there, 667 MB of it, correctly built and correctly named. pg_stat_user_indexes said idx_scan = 0. A plain btree on (item_id, chunk_index) had millions of scans.

Every instinct says the query shape is wrong. Every instinct was wrong, at least at first.

Substitute your own names before you run any of this. embeddings is the vector table, items is the parent table, $1 is the query vector and $2 to $4 are your filter parameters. The numbers below come from one real table and one real incident, not from a benchmark, so expect your ratios to differ.

Run ANALYZE before you touch the query

After a physical clone, a bulk load, or a large backfill, the planner can be holding row estimates that make a nested loop look cheaper than an approximate nearest neighbour scan. It will then avoid the index and scan the table, and it will do that on every call.

Measured on a table of about 167,000 rows with a 667 MB index:

  • before: idx_scan = 0, statement mean 5,326 ms
  • after VACUUM (ANALYZE) embeddings: idx_scan rising, same statement 2.5 ms on a custom plan and 6.9 ms on a forced generic plan, both using the HNSW index

The query was never changed. One statement was never changed. The fix was one command:

select relname, last_analyze, last_vacuum, n_dead_tup, n_mod_since_analyze
from pg_stat_user_tables where relname in ('items','embeddings');

VACUUM (ANALYZE) embeddings;

Run it, re-run the query, and check idx_scan again. If it is moving and the statement is fast, stop. Do not rewrite anything.

One detail that sends people hunting: VACUUM (ANALYZE) sets last_vacuum and last_analyze, never last_autovacuum. Seeing last_autovacuum = NEVER right after a manual vacuum is expected, not a sign the command failed.

If statistics do not fix it, prove the index works

Now the query really is the suspect. But before you rewrite it, prove the index is healthy on its own, with no joins and no filters:

EXPLAIN (ANALYZE, BUFFERS, COSTS OFF)
SELECT item_id, embedding <=> (SELECT embedding FROM embeddings LIMIT 1) AS d
FROM embeddings ORDER BY d LIMIT 50;

An Index Scan using ..._hnsw at tens of milliseconds means the index is fine and the problem is downstream of it. Also confirm the index is dead weight rather than merely idle:

select indexrelname, idx_scan, idx_tup_read,
       pg_size_pretty(pg_relation_size(indexrelid))
from pg_stat_user_indexes where relname = 'embeddings' order by idx_scan desc;

The shape that blocks the index

The common failure is an ANN step that also joins the parent table and applies selective filters in the same SELECT:

WITH semantic_candidates AS MATERIALIZED (
  SELECT e.item_id, e.chunk_text, e.embedding <=> $1 AS distance
  FROM embeddings e
  JOIN items i ON e.item_id = i.id
  WHERE i.tenant_id = $2 AND i.status = $3
  ORDER BY e.embedding <=> $1
  LIMIT $4
)

The join invites the planner to start from items, filter, then probe embeddings per row. That plan is exact and it is slow, and once the row estimate says the filtered set is small it will look attractive forever.

Two things to test before you decide, because a literal test is not the same as production:

SET plan_cache_mode = force_generic_plan;
EXPLAIN (ANALYZE, COSTS OFF) EXECUTE your_prepared_stmt(:'q');

Production binds the vector as a parameter. A literal-only test can show you a good plan that production never gets, or hide a bad one that it always gets.

And check the row count before you trust the timing. A plan that runs in two milliseconds and returns zero rows measured the filter, not the search. Both shapes must return the same number of rows before either number means anything.

The shape that can never use the index

Some queries are not ANN queries at all. A per-row aggregate similarity is the classic:

SELECT i.id, 1 - (AVG(e.embedding) <=> (SELECT vec FROM centroid)) AS similarity
FROM embeddings e JOIN items i ON e.item_id = i.id
WHERE i.status = 'ready'
GROUP BY i.id ORDER BY similarity DESC LIMIT 8;

To average each group’s embedding it must read every row. There is no ORDER BY <distance> LIMIT for the planner to push into the index, so it becomes a full scan feeding a GroupAggregate with Batches > 1, spilling to disk. Measured on about 170,000 rows of 1,536 dimensions it took 3.4 seconds with a trivial centroid, and passed a 30 second statement timeout with a real one. That surfaced as worker job failures, not as a slow page.

Recognise it from the plan: Seq Scan on embeddings into an aggregate, with no index order. The fix is to rewrite it as a single vector search and average inside the returned candidates. Raising statement_timeout is not a fix, because the cost grows with the corpus and the timeout only moves the wall.

If you do rewrite it, know what it costs

The usual rewrite separates the ANN step from the filtering step:

WITH ann AS MATERIALIZED (
  SELECT item_id, chunk_index, chunk_text, embedding <=> $1 AS distance
  FROM embeddings
  WHERE tenant_id = $2
  ORDER BY embedding <=> $1
  LIMIT $3
)
SELECT ... FROM ann JOIN items i ON i.id = ann.item_id
WHERE i.status = $4

This under-returns when the post-filter is selective. On an unfiltered call where 97.5 percent of rows are eligible, it is safe. On a call scoped to a single tag that matches 100 rows out of 41,000, the candidate pool can contain zero eligible rows and the result goes empty where it used to return 50. Measure the eligibility ratio before choosing this shape, and prefer the statistics fix when it works.

pgvector 0.8 can mitigate with iterative scan, but not every build exposes the setting. Check before relying on it:

show hnsw.iterative_scan;   -- errors if the build lacks it

Measure the fix correctly

Judge the change by idx_scan moving and by the cost of new calls. Do not judge it by mean_exec_time:

select calls, round((total_exec_time/calls)::numeric,0) mean_ms
from pg_stat_statements where query like '%semantic_candidates%';

That mean is cumulative. It averages every call since the statistics were last reset, so a statement that ran slowly five hundred times still reads slow after it becomes fast. If you report the fix with this number and it has not dropped, the next person concludes nothing changed and keeps digging.

Two smaller traps worth knowing. A like '%name%' filter on pg_stat_statements often matches several normalised statements and produces a misleading average, so compare one statement, not a group. And after a physical clone, n_live_tup restarts near zero, so it is not your row count. Use count(*) or pg_class.reltuples.

The order that saves time

Statistics first, always. Then prove the index in isolation. Then test the generic plan. Then, only if all three say the query is the problem, rewrite it and measure the correctness cost before you ship it.

Five seconds to two and a half milliseconds is a good afternoon. The temptation is to spend it rewriting a query that was never the problem.

The same discipline applies to the copy of the database you would restore from, which reports healthy far more often than it should: your Postgres backup is a hypothesis until you restore it.

Related Articles

Want a second read on your setup?

Paste one Dockerfile, Compose file, or CI pipeline. We read it and send back one page: the three biggest risks and the first fix. Written by an engineer, not a bot.

Get the free triage