跳到正文
DEV Community· Daniel Basseda·· 1 小時前AI 評分65

pgvector 實戰:使用 cosine 距離與 HNSW 索引檢查召回率

pgvector in practice: cosine distance, an HNSW index, and checking recall

AI 導讀

Daniel Basseda 示範如何在 PostgreSQL 的 pgvector 文件問答系統中設定 cosine 距離與 HNSW 索引,並以精確搜尋作為參照測量索引召回率。

正文

You add an HNSW index to your embeddings table, run a few questions, and the results look the same as before. Good news, right? Maybe. It can also mean the index never ran, or that your test was quietly comparing exact search against exact search.

I ran into both of those while writing the PostgreSQL chapter of my book, on a small experiment table. This post walks through how I set up vector search with pgvector for a document Q&A system, why I keep exact search as the reference, and how I check recall without fooling myself.

Pick the distance first, then the index

The schema is simple. Each chunk row stores its text, its page, and a 1,536-number embedding (that's what text-embedding-3-small returns):

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS chunks (
    id           bigserial PRIMARY KEY,
    document_id  integer NOT NULL
                 REFERENCES documents(id) ON DELETE CASCADE,
    page_number  integer NOT NULL,
    chunk_index  integer NOT NULL,
    chunk_text   text NOT NULL,
    embedding    vector(1536) NOT NULL,
    UNIQUE (document_id, page_number, chunk_index)
);

pgvector gives you several distance operators. Two matter here: <-> is L2 (Euclidean) distance and <=> is cosine distance. An index is built for one of them through its operator class, and it only helps queries that use the matching operator.

This isn't a theoretical mistake. The real project the book is based on orders its vector search by embedding <-> question_embedding, while its migration declares an IVFFlat index with vector_cosine_ops. That index is built for <=>, so it shouldn't be expected to speed up the <-> query at all. Nothing errors. The query just doesn't use the index.

In the book's teaching version I made the query and the index agree:

SELECT id FROM chunks
ORDER BY embedding <=> $1::vector
LIMIT 30;

and the score that goes into hybrid ranking follows the same choice:

1 - (embedding <=> $1::vector) AS vec   -- cosine similarity

If you take one thing from this post, check that line up against your index definition. It takes a minute.

Start with exact search

Without a vector index, ORDER BY embedding <=> query LIMIT 10 compares the question with every chunk. That's exact search. It always returns the true nearest chunks, and for a small data set it's what I'd keep. It's also your reference for everything that follows.

When the table grows, an approximate index can help. The teaching example uses HNSW with the cosine operator class:

CREATE INDEX chunks_embedding_hnsw
    ON chunks USING hnsw (embedding vector_cosine_ops);

That's pgvector's default build parameters. At query time, hnsw.ef_search (40 by default) controls how many candidates the index explores. Higher values get you closer to exact search and cost more time.

The word "approximate" is the whole point. The index can return a different top 10 than exact search, and you won't notice by reading a few answers.

Measure recall, not just speed

Recall here means the share of the exact top results that the index also returns. If exact search gives you 10 chunk IDs and the index returns 7 of them, recall for that question is 0.7.

The method in the book is plain:

  1. For each test question, run the query with index scans disabled (SET LOCAL enable_indexscan = off), which gives exact search.
  2. Run it again with the index.
  3. Compare the two top-10 lists.
  4. Check the plan of every run with EXPLAIN, so you know which method actually ran.

Here's a sketch of that comparison in Python with psycopg 3. It's a simplified illustration of the method, not the experiment script that ships in the code bundle:

import psycopg

SQL = "SELECT id FROM chunks ORDER BY embedding <=> %s::vector LIMIT 10"

def top10(conn, qv, exact, ef_search=40):
    with conn.transaction():
        if exact:
            conn.execute("SET LOCAL enable_indexscan = off")
        else:
            conn.execute("SET LOCAL enable_seqscan = off")
            conn.execute(f"SET LOCAL hnsw.ef_search = {int(ef_search)}")
        plan = "\n".join(
            r[0] for r in conn.execute("EXPLAIN " + SQL, (qv,))
        )
        uses_index = "chunks_embedding_hnsw" in plan
        assert uses_index != exact, plan
        return [r[0] for r in conn.execute(SQL, (qv,))]

def recall(conn, question_vectors, ef_search=40):
    scores = []
    for qv in question_vectors:
        truth = set(top10(conn, qv, exact=True))
        approx = set(top10(conn, qv, exact=False, ef_search=ef_search))
        scores.append(len(truth & approx) / len(truth))
    return sum(scores) / len(scores)

# prepare_threshold=None: don't let psycopg reuse a prepared plan
conn = psycopg.connect(DATABASE_URL, prepare_threshold=None)

question_vectors are your question embeddings in pgvector's [x,y,...] text format. The two odd-looking details, prepare_threshold=None and the assert on the plan, are there because of the two traps below.

Trap 1: the prepared plan that made recall perfect

psycopg 3 prepares a query automatically after it has run a few times, then reuses that plan. In the first version of the experiment, the plan prepared during the exact runs got reused for the indexed runs. Both "methods" returned identical results and recall looked perfect.

It wasn't perfect. It was the same query plan twice.

Turning off automatic preparation with prepare_threshold=None removes that effect. On its own, though, it still doesn't prove which method ran. That's what the plan check is for.

Trap 2: the planner ignored the index

On the small experiment table, the planner preferred a sequential scan even with the HNSW index in place. A sequential scan with a sort is exact search, so once again I'd have been comparing exact against exact. Only the plan check showed it.

The fix in the script is to disable sequential scans for the indexed runs and assert that every plan uses the index. I don't love enable_seqscan = off in general. It's a diagnostic tool, useful to see whether an index can be used, and it belongs inside a transaction (SET LOCAL) in a measurement script, not in your application config.

The planner wasn't wrong, by the way. On a small table, reading everything is often cheaper than walking an index. It's just not what you're trying to measure.

What the numbers looked like (and why they don't transfer)

On 5,000 random vectors with default settings (ef_search 40), the index returned about a third of the exact top 10. Raising ef_search to 400 brought it to about 0.95.

I want to be careful with those numbers. Random vectors have no structure, and real embeddings do, so this doesn't predict what you'll see on your documents. What it does show is that default settings and "the results look fine" are not the same thing as good recall, and that ef_search is a real knob with a real effect.

Limitations

  • This checks the vector index against exact vector search. It doesn't tell you whether the exact top 10 is the right answer for the question. That's a separate evaluation, with real questions and expected pages.
  • Recall and speed trade off. Measure both on the same runs, and repeat timings, because the first run often reads from disk and later ones read from cache.
  • The book's teaching code uses HNSW as an option. The real project declares IVFFlat. I didn't benchmark one against the other, so I'm not going to claim one is better.
  • When you write a measurement down, write the conditions with it: number of chunks, PostgreSQL and pgvector versions, hardware and memory, which indexes existed and their parameters, session settings, warm or cold cache. A timing without those can't be compared or repeated.

Practical lessons

  • Make the operator in your query match the operator class of your index. <=> goes with vector_cosine_ops.
  • Keep exact search as the reference. On a small table, you may not need an index at all.
  • Measure recall with the same questions against exact and indexed runs, and compare top-k lists.
  • Check EXPLAIN for every run. If you can't show which method ran, the number means nothing.
  • Watch out for prepared statements in drivers like psycopg 3 when you change session settings between runs.
  • Tune hnsw.ef_search against your own data and real questions before you decide on the index or its parameters.

I'm Daniel Basseda. I work in database administration and technical support. This post comes from my book RAG on Postgres: Building a Document Q&A System That Survives Real-World PDFs, which builds a small document Q&A system on PostgreSQL: OCR for scanned PDFs, pgvector, full-text and trigram search, hybrid retrieval and cited answers. There's also an e-book + code bundle with the ready-to-run project and its tests.

來源:DEV Community · dev.to