This resume is also available in English.

9. RAG and tools4 / 6 · All columns

Columns › 9. RAG and tools › Part 62

Using pgvector: Vector Columns, Indexes, Filtering and Pairing It with an LLM

pgvector 怎麼用:向量欄位、索引、篩選與搭配 LLM 的正確做法

Store vectors and run similarity search inside PostgreSQL with pgvector: when to choose it, which types and distances to pick, how HNSW and IVFFlat work and which knobs matter, why filters eat your results, hybrid search in one SQL query, and how to pair it with an LLM safely: permissions, tools, semantic caching and switching models. Every number was measured on a real PostgreSQL.

  • pgvector
  • PostgreSQL
  • RAG
  • Go
In this article
  1. What this article solves
  2. Step 1: When to use pgvector, and when not to
  3. Step 2: Types and distances — choose before you index
  4. Step 3: Table design — more than vectors
  5. Step 4: Exact search, HNSW and IVFFlat
  6. Step 5: Measuring recall — exact search as the reference
  7. Step 6: Filtering — why results get eaten
  8. Step 7: Hybrid search — full text + vector + RRF in one SQL query
  9. Step 8: Pairing it with an LLM — flow, permissions and boundaries
  10. Step 9: Semantic caching, memory for agents and deduplication
  11. Step 10: Switching embedding models — without downtime
  12. Step 11: Capacity, quantisation and day-to-day operations
  13. Common pitfalls
  14. Key takeaways
  15. References
  16. Next

The previous article, “Evaluating RAG, Hallucinations and Common Failures: How to Know It Answers Right”, set up a way to measure: recall@k, faithfulness, refusals, and monitoring once it is live. Before that, “Where RAG Quality Comes From: Chunking, Embeddings, Vector Databases and Hybrid Search” covered “what to watch” with a vector database, but only in one section. This article walks through the most common choice, PostgreSQL’s pgvector extension, from columns and indexes to how to pair it with an LLM, and for every recommendation says which scenario it fits, why it is needed and when not to use it.

What this article solves

The shop already runs on PostgreSQL, and three new requirements are all about “similar meaning”:

  • Support Q&A: on-call staff ask questions about runbooks and the FAQ in plain language, such as “payment keeps spinning, what do I do?”, and should land on the “Payment timeout” section. The payment service’s internal runbooks are visible only to the payment-oncall role.
  • Product search: a customer types “an insulated mug that makes a good gift for grandparents”, or looks at “similar products” on a product page, and results must be filtered by category and stock.
  • Order assistant: a customer asks “where is my order?”. What needs looking up is order data, not documents; vector search does not help here and easily causes harm.

The team’s first version was straightforward: add an embedding column, build an HNSW index, ORDER BY embedding <=> $1 LIMIT 10. After launch they ran into one thing after another: payment on-call staff often got only two or three results; switching embedding models meant taking the table offline to rebuild; and someone suggested “letting the LLM write SQL against the vector table itself”. This article deals with them in order:

  1. When to use pgvector, and when to move to a dedicated vector database.
  2. How to choose a type (vector, halfvec, sparsevec, bit) and a distance operator.
  3. Which columns the table should hold, and writing to it from Go.
  4. Exact search, HNSW and IVFFlat: how they work, their parameters and measurements.
  5. Measuring recall with exact search as the reference.
  6. Why filters eat your results, and where iterative scans, B-trees, partial indexes and partitioning each fit.
  7. Full-text plus vector hybrid search in one SQL query, and the limits with Chinese text.
  8. Pairing it with an LLM: the flow, permissions, what may go into the prompt, and why the model must not write SQL.
  9. Semantic caching, memory for agents, and deduplication.
  10. Switching embedding models without downtime.
  11. Capacity, quantisation and day-to-day operations.

The numbers in this article come from a Docker container on a development machine: PostgreSQL 17.12, pgvector 0.8.7, 50,000 synthetic 384-dimensional vectors (not produced by a real model) and 100 queries. Latencies are only for comparing settings with each other, and recall changes a lot with the data distribution; below you will see how differently the same parameters behave on two datasets. Measure again on your own data.

Step 1: When to use pgvector, and when not to

pgvector is a PostgreSQL extension that adds vector types, distance operators and two kinds of approximate index. Its main value is not “fastest” but that vectors live in the same database, in the same transaction, as everything else.

AspectpgvectorDedicated vector database (Qdrant, Milvus and so on)
ConsistencyDocuments, permissions and vectors update in one transaction; no “document deleted, vector still there”A second system next to the main database that you must keep in sync (for example with the outbox from “Distributed Transactions: Sagas and the Outbox Pattern”)
Filtering and joinsPermissions, category and stock go straight into WHERE; you can JOINFilter fields must be copied into the vector database’s payload and kept in sync
OperationsReuses existing backups, replication, monitoring and access controlOne more system to deploy, back up, upgrade and monitor
ScalingMore memory and CPU, read replicas; sharding needs something extra (such as Citus)Usually designed to scale out from the start
Resource contentionVector queries compete with order transactions for CPU, memory and I/OVector load is isolated
Suitable sizeThe index roughly fits in one machine’s memoryMore vectors or queries than one machine can handle

When pgvector fits: you already use PostgreSQL; the number of vectors fits in a single machine’s memory; queries need filtering together with business data (permissions, tenants, stock); and you want documents and vectors committed together. The shop’s support Q&A and product search both fall into this group.

When it does not: vector search is the product’s main workload and query volume is high enough to slow down order transactions; there are so many vectors that the index is far larger than one machine’s memory; or you need features only a dedicated database has. Even then, a common route is “launch on pgvector, move once you measure a bottleneck”, because the cost of moving is mostly rewriting the data, and if the query interface sits behind a repository it is not hard to swap.

Tip: if the only worry is contention with OLTP, try routing vector queries to a read replica first (Step 11); you may not need another database.

Step 2: Types and distances — choose before you index

pgvector offers four types. Sizes and limits come from the official README; the byte counts in brackets are pg_column_size measured at 384 dimensions:

TypeSize per valueColumn limitIndexable up toFits
vector4 × dimensions + 8 (1,544 B)16,000 dimensions2,000 dimensions (HNSW, IVFFlat)The default choice, single-precision floats
halfvec2 × dimensions + 8 (776 B)16,000 dimensions4,000 dimensionsSaving half the space, or models with more than 2,000 dimensions
bitdimensions / 8 + 8Built-in PostgreSQL type64,000 dimensionsBinary vectors, coarse search after binary quantisation (Step 11)
sparsevec8 × non-zero elements + 1616,000 non-zero elements1,000 non-zero elements (HNSW only)Sparse vectors, such as sparse models that output “term → weight”

The dimension is part of the column. A 768-dimensional vector does not fit in vector(1024); it fails straight away (expected 1024 dimensions, not 768). That is a good thing: if queries and documents accidentally use different models, at least a dimension mismatch fails immediately. Different models with the same dimension do not fail, which is why Step 3 also records the model name.

Distance operators and index operator classes come in pairs:

OperatorMeaningOperator class for vectorHNSWIVFFlatWhen to use
<=>Cosine distance (1 − cosine similarity)vector_cosine_opsYesYesThe default for most text embedding models
<#>Negative inner productvector_ip_opsYesYesWhen vectors are normalised (length 1): same order as cosine, cheaper to compute
<->Euclidean (L2) distancevector_l2_opsYesYesWhen the model’s documentation says L2, or for non-text features such as images
<+>Manhattan (L1) distancevector_l1_opsYesNoSpecified by a few models or hand-built features
<~>Hamming distance (bit)bit_hamming_opsYesYesBinary vectors, binary quantisation
<%>Jaccard distance (bit)bit_jaccard_opsYesNoSet similarity

For halfvec and sparsevec, swap the prefix (halfvec_cosine_ops, sparsevec_cosine_ops); the Yes/No columns come from querying pg_opclass in the container.

Three practical points:

  • Pick the distance the model’s documentation names. If it says cosine, use <=>. If the model already outputs normalised vectors, <#> and <=> give exactly the same order (measured: the same top 10 for the same queries), and the README recommends inner product for better performance in that case. If you are not sure whether they are normalised, use cosine; it is never wrong.
  • ORDER BY must be the distance operator itself, ascending. ORDER BY embedding <=> $1 uses the index; ORDER BY 1 - (embedding <=> $1) DESC returns the same rows but the plan becomes a sequential scan plus a sort. If you want to show similarity, compute it in the SELECT list.
  • One index serves one distance. An index built with vector_cosine_ops is not used by a query written with <->.
-- ORDER BY embedding <=> $1 LIMIT 10
Limit
  ->  Index Scan using items_hnsw on items
        Order By: (embedding <=> '[...]'::vector)

-- ORDER BY 1 - (embedding <=> $1) DESC LIMIT 10
Limit
  ->  Sort
        Sort Key: (('1'::double precision - (embedding <=> '[...]'::vector))) DESC
        ->  Seq Scan on items

Step 3: Table design — more than vectors

A vector means nothing on its own: answers need to quote the original text, filters need metadata, and rebuilds need hashes and the model version. The chunk table for support Q&A:

-- migrations/010_doc_chunks.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE doc_chunks (
    id            bigserial    PRIMARY KEY,
    source        text         NOT NULL,            -- runbooks/payment-timeout.md
    chunk_no      int          NOT NULL,            -- position of the chunk in the file
    heading       text         NOT NULL,            -- heading path, shown in citations
    content       text         NOT NULL,            -- original text, for the prompt and for people
    content_seg   text         NOT NULL,            -- segmented by the app, space-separated, for full-text search
    content_hash  bytea        NOT NULL,            -- sha256(content); unchanged means no re-embedding
    allowed_roles text[]       NOT NULL,            -- who may read it: {support}, {payment-oncall}
    embed_model   text         NOT NULL,            -- model and version that produced the vector
    embedding     vector(1024) NOT NULL,
    tsv           tsvector     GENERATED ALWAYS AS (to_tsvector('simple', content_seg)) STORED,
    updated_at    timestamptz  NOT NULL DEFAULT now(),
    UNIQUE (source, chunk_no)
);

CREATE INDEX doc_chunks_embedding ON doc_chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX doc_chunks_tsv       ON doc_chunks USING gin (tsv);
CREATE INDEX doc_chunks_roles     ON doc_chunks USING gin (allowed_roles);

Every column has a job:

  • content and heading: the LLM reads the original text, and citations show the heading and source, not the vector.
  • content_seg: the segmented text for full-text search; Step 7 explains why Chinese needs it.
  • content_hash: when a document is re-imported, chunks whose hash has not changed do not need paying to embed again.
  • allowed_roles: permissions live in the database and are applied during the search. The GIN index lets && (arrays overlap) use an index too.
  • embed_model: records the model name and version, such as emb-a-1024@2026-06. Queries and documents must use the same model; some models also expect different prefixes for queries and documents (for example query: and passage: for the E5 family). Follow the model’s instructions and keep them in one setting, so the two sides cannot drift apart.
  • Build the vector index after loading the data; it is faster. You can create HNSW on an empty table (it needs no training), but bulk loading into it is much slower.

In Go, use pgx with pgvector-go: register the types on every connection, and you can pass a pgvector.Vector directly, sent in binary format; bulk writes use COPY.

// internal/vectorstore/store.go
package vectorstore

import (
	"context"
	"sort"
	"strconv"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/pgvector/pgvector-go"
	pgxvec "github.com/pgvector/pgvector-go/pgx"
)

// Open creates a pool and registers the pgvector types on every new connection.
// A migration must create the extension first, or RegisterTypes cannot find the types and fails.
func Open(ctx context.Context, url string) (*pgxpool.Pool, error) {
	cfg, err := pgxpool.ParseConfig(url)
	if err != nil {
		return nil, err
	}
	cfg.AfterConnect = func(ctx context.Context, conn *pgx.Conn) error {
		return pgxvec.RegisterTypes(ctx, conn)
	}
	return pgxpool.NewWithConfig(ctx, cfg)
}

// Chunk is one piece of a document to be written to doc_chunks.
type Chunk struct {
	Source       string
	ChunkNo      int
	Heading      string
	Content      string
	ContentSeg   string
	ContentHash  []byte
	AllowedRoles []string
	Embedding    []float32
}

// Store offers a few fixed queries only; callers (LLM tools included) cannot build their own SQL.
type Store struct {
	DB       *pgxpool.Pool
	Model    string // embedding model of this version, e.g. "emb-a-1024@2026-06"
	EfSearch int    // hnsw.ef_search; 0 means the default of 40
}

// Load bulk-writes with COPY; much faster than row-by-row INSERT, for the first load or a full rebuild.
func (s *Store) Load(ctx context.Context, chunks []Chunk) (int64, error) {
	return s.DB.CopyFrom(ctx, pgx.Identifier{"doc_chunks"},
		[]string{"source", "chunk_no", "heading", "content", "content_seg",
			"content_hash", "allowed_roles", "embed_model", "embedding"},
		pgx.CopyFromSlice(len(chunks), func(i int) ([]any, error) {
			c := chunks[i]
			return []any{c.Source, c.ChunkNo, c.Heading, c.Content, c.ContentSeg,
				c.ContentHash, c.AllowedRoles, s.Model, pgvector.NewVector(c.Embedding)}, nil
		}))
}

// Caller is decided by the server from the authenticated identity, never filled in by the model or the user.
type Caller struct {
	Roles []string
}

// Hit is one search result; Distance is the cosine distance, 0 being nearest.
type Hit struct {
	ID       int64
	Source   string
	Heading  string
	Content  string
	Distance float64
}

const searchSQL = `
SELECT id, source, heading, content, embedding <=> $1 AS distance
FROM doc_chunks
WHERE allowed_roles && $2
ORDER BY embedding <=> $1
LIMIT $3`

// Search finds the k nearest chunks among those the caller may see.
// The permission filter is in the SQL, applied during the search, not after it by asking the model to keep quiet.
func (s *Store) Search(ctx context.Context, c Caller, q []float32, k int) ([]Hit, error) {
	ef := s.EfSearch
	if ef <= 0 {
		ef = 40
	}
	var hits []Hit
	err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
		// set_config(..., true) is SET LOCAL: it lasts for this transaction only and accepts parameters.
		// relaxed_order: when the filter removes candidates, keep scanning until k rows are found.
		if _, err := tx.Exec(ctx, `SELECT set_config('hnsw.ef_search', $1, true),
		                                  set_config('hnsw.iterative_scan', 'relaxed_order', true)`,
			strconv.Itoa(ef)); err != nil {
			return err
		}
		rows, err := tx.Query(ctx, searchSQL, pgvector.NewVector(q), c.Roles, k)
		if err != nil {
			return err
		}
		hits, err = pgx.CollectRows(rows, pgx.RowToStructByPos[Hit])
		return err
	})
	if err != nil {
		return nil, err
	}
	// relaxed_order results may be slightly out of order, so sort by distance before returning.
	sort.SliceStable(hits, func(i, j int) bool { return hits[i].Distance < hits[j].Distance })
	return hits, nil
}

The design of Store is deliberate: it offers only a few fixed queries, and the only parameters are the vector, k and a Caller decided by the server. Step 8 shows why this is exactly what lets an LLM use it safely.

Step 4: Exact search, HNSW and IVFFlat

Without an index, pgvector does exact search: it computes the distance for every row, sorts and takes the top k, so recall is always 100%. After you add an approximate index, queries get faster but results may differ, which is the first thing the README warns about.

Exact search HNSW IVFFlat Layer 2 Layer 1 Layer 0 Every row, 100% recall Walk the graph, ef_search Nearest lists, probes

Figure: exact search compares every row; HNSW walks a multi-layer neighbour graph from an entry point towards the query; IVFFlat splits vectors into lists and at query time only looks at the few lists nearest the query.

  • HNSW builds a multi-layer graph in which each point links to nearby points. A query starts at the entry point on the top layer, moves to neighbours closer to the query on each layer, and on the bottom layer keeps a candidate list of size ef_search. Its speed–recall trade-off is better than IVFFlat’s and it can be created on an empty table; the cost is slower builds and more memory.
    • Build parameters: m (maximum connections per layer, default 16) and ef_construction (candidate list size while building, default 64). The README recommends the defaults until you see low recall.
    • Query parameter: hnsw.ef_search (default 40). Higher is more accurate and slower. A LIMIT larger than ef_search does not return that many rows: measured, LIMIT 100 with ef_search = 40 returned only 40 rows (unless the iterative scans from Step 6 are on).
  • IVFFlat uses k-means to split the vectors into lists lists and at query time scans only the nearest ivfflat.probes lists (default 1). It builds fast and the index is small, but the clusters are computed from the data present at build time, so build it only after the table has data, and rebuild it after the distribution changes a lot. The README’s starting point is lists ≈ rows / 1000 (up to a million rows) and probes ≈ sqrt(lists).

Measurements (50,000 rows, 384 dimensions, m = 16, ef_construction = 64, IVFFlat lists = 50). Dataset A has 200 tighter clusters; dataset B has 2,000 looser clusters, closer to the hard case where every vector is about equally far away:

SettingA: recall@10A: mean latencyB: recall@10B: mean latency
Exact (sequential scan)1.00018.0 ms1.00017.3 ms
HNSW ef_search = 100.7400.54 ms0.6550.67 ms
HNSW ef_search = 200.8210.53 ms0.8470.78 ms
HNSW ef_search = 40 (default)0.9290.71 ms0.9191.25 ms
HNSW ef_search = 1001.0000.80 ms0.9372.12 ms
HNSW ef_search = 2001.0000.91 ms0.9593.54 ms
IVFFlat probes = 10.9900.82 ms0.1280.72 ms
IVFFlat probes = 71.0003.01 ms0.4172.65 ms
IVFFlat probes = 201.0007.73 ms0.7077.01 ms
0.6 0.7 0.8 0.9 1.0 10 20 40 100 200 hnsw.ef_search recall@10 0.740 0.655 0.929 0.919 1.000 0.959 Dataset A: 200 tighter clusters Dataset B: 2,000 looser clusters

Figure: with the same HNSW parameters, the tighter dataset A reaches 1.0 at ef_search = 100, while the looser dataset B is still at 0.96 at 200.

Three things to read from this table:

  1. Approximate indexes are more than ten times faster, paid for in recall; the default ef_search = 40 missed about 7–8% of the correct answers on both datasets.
  2. The same parameters behave very differently on different data. IVFFlat with the README’s starting point is nearly perfect on A and only 0.13 on B. Changing embedding model or document types means measuring again.
  3. Build costs differ. Building HNSW took 4.9 s on A and 11.3 s on B, IVFFlat under a second; the HNSW index is 98 MB, IVFFlat 78 MB, and the table itself 79 MB.

How to choose:

ScenarioRecommendationWhy
A few thousand to tens of thousands of rows, relaxed latencyNo vector index, exact search100% recall, nothing to tune; measured, 50,000 rows take about 18 ms
The filter itself is narrow (a few hundred rows per query)B-tree on the filter column, exact sortMeasured in Step 6: more accurate and faster than HNSW
Typical RAG and product search, data written continuouslyHNSWBest speed–recall trade-off; new rows are searchable as soon as written
Large data, tight build time or memory, loaded in one goIVFFlat (built after the data is in)Fast builds, little memory; but measure recall and rebuild when the distribution shifts

Build time and memory: HNSW builds much faster when the graph fits in maintenance_work_mem; when it does not, you get a hnsw graph no longer fits into maintenance_work_mem notice and the build slows down markedly. HNSW (since 0.6.0) and IVFFlat both support parallel builds, controlled by max_parallel_maintenance_workers (default 2). Parallel builds use shared memory: measured, building HNSW under Docker’s default /dev/shm failed outright with could not resize shared memory segment ... No space left on device, and succeeded only after raising the container’s --shm-size.

-- Raise these for this session during a maintenance window; do not make them global and exhaust the server's memory
SET maintenance_work_mem = '2GB';
SET max_parallel_maintenance_workers = 4;
CREATE INDEX CONCURRENTLY doc_chunks_embedding
    ON doc_chunks USING hnsw (embedding vector_cosine_ops)
    WITH (m = 16, ef_construction = 64);

-- Progress, from another session
SELECT phase, round(100.0 * blocks_done / nullif(blocks_total, 0), 1) AS "%"
FROM pg_stat_progress_create_index;

CONCURRENTLY keeps the build from blocking writes and is a must in production; see “Adding Indexes Safely: Indexing Large Tables Without an Outage” for how it works and what to watch.

Step 5: Measuring recall — exact search as the reference

Tuning ef_search or probes, or changing quantisation, always comes back to one question: what fraction of the exact answers did the approximate search find? This differs from the recall@k in the previous article: there we compared against “passages a human labelled as correct”; here we compare against “the exact top k for the same vector”. It measures only the loss caused by the index, needs no human labels, and can run automatically every day.

The README’s approach is to turn off index scans inside a transaction so the same query becomes an exact search. The code below takes query vectors from real questions and runs the real Search and an exact search for each:

// internal/vectorstore/recall.go
package vectorstore

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/pgvector/pgvector-go"
)

// Same result as searchSQL, but deliberately different SQL text:
// pgx caches prepared statements, and with shared text a plan built while index scans
// were off can be reused by the real query, making both sides always identical.
const exactSQL = `
SELECT id FROM doc_chunks /* exact */
WHERE allowed_roles && $2
ORDER BY embedding <=> $1
LIMIT $3`

// RecallAtK: the fraction of the exact top k that the approximate search found.
func RecallAtK(approx, exact []int64) float64 {
	if len(exact) == 0 {
		return 1
	}
	want := make(map[int64]bool, len(exact))
	for _, id := range exact {
		want[id] = true
	}
	found := 0
	for _, id := range approx {
		if want[id] {
			found++
		}
	}
	return float64(found) / float64(len(exact))
}

func (s *Store) exact(ctx context.Context, c Caller, q []float32, k int) ([]int64, error) {
	var ids []int64
	err := pgx.BeginFunc(ctx, s.DB, func(tx pgx.Tx) error {
		if _, err := tx.Exec(ctx, `SET LOCAL enable_indexscan = off`); err != nil {
			return err
		}
		rows, err := tx.Query(ctx, exactSQL, pgvector.NewVector(q), c.Roles, k)
		if err != nil {
			return err
		}
		ids, err = pgx.CollectRows(rows, pgx.RowTo[int64])
		return err
	})
	return ids, err
}

// MeasureRecall runs the real Search and an exact search for each query vector
// (for example, vectors of last week's real questions) and returns the mean recall@k.
func (s *Store) MeasureRecall(ctx context.Context, c Caller, queries [][]float32, k int) (float64, error) {
	if len(queries) == 0 {
		return 0, errors.New("no queries")
	}
	var sum float64
	for _, q := range queries {
		hits, err := s.Search(ctx, c, q, k)
		if err != nil {
			return 0, err
		}
		approx := make([]int64, len(hits))
		for i, h := range hits {
			approx[i] = h.ID
		}
		exact, err := s.exact(ctx, c, q, k)
		if err != nil {
			return 0, err
		}
		sum += RecallAtK(approx, exact)
	}
	return sum / float64(len(queries)), nil
}

Why does the exact query use different SQL text? This is a trap hit while measuring. pgx caches prepared statements by default, and after a prepared statement has run a few times PostgreSQL may switch to one generic plan and reuse it. If that plan was built inside a transaction with enable_indexscan = off, the “approximate” query keeps using a sequential scan as well; both sides are always identical and recall is always 1. With different SQL text they are different prepared statements, each with its own plan.

In the tests, the same queries measured 0.967 at ef_search = 10 and 1.000 at ef_search = 200. In practice:

  • Measure with vectors from real queries, not random vectors; take the last week of questions from the logs and embed them again.
  • Measure with the filters included (for example, as the payment-oncall role); Step 6 shows that filters have the biggest effect on recall.
  • Set a floor and alert on it, for example recall@10 below 0.9. With constant inserts and deletes, HNSW quality drifts slowly, and IVFFlat clusters go stale.

Step 6: Filtering — why results get eaten

Payment on-call staff can see only 1% of the chunks. The query WHERE allowed_roles && '{payment-oncall}' ORDER BY embedding <=> $1 LIMIT 10 looks fine, yet often returns only two or three rows. The reason is that with an approximate index, the filter is applied after the index scan: HNSW first finds the ef_search (40) nearest candidates, then WHERE filters them; with a 1% condition, an average of 0.4 of those 40 candidates survive.

HNSW, nothing else Take 40 nearest hnsw.ef_search = 40 Apply WHERE matches 1% of rows 0.4 rows on average LIMIT 10 not filled HNSW + iterative scan Take 40 candidates apply the filter Not enough? Scan on up to max_scan_tuples 10 rows filled recall may stay low B-tree on the filter column B-tree filters first about 500 rows Distance for each exact sort 10 rows, 100% recall fastest when narrow The narrower the condition, the more an ordinary index should filter first

Figure: HNSW finds 40 candidates and then applies the condition, so with a 1% condition almost all are filtered out; an iterative scan keeps going until it has enough; a B-tree finds that 1% first and sorts it exactly.

EXPLAIN ANALYZE shows it plainly: 38 of 40 candidates removed, 2 rows returned:

Limit (actual time=0.458..0.463 rows=2 loops=1)
  ->  Index Scan using items_hnsw on items (actual time=0.457..0.462 rows=2 loops=1)
        Order By: (embedding <=> (InitPlan 1).col1)
        Filter: (category = 3)
        Rows Removed by Filter: 38

Measured on the same 50,000 rows, with a condition matching 1% of rows and LIMIT 10:

ApproachA: mean rows returnedA: recall@10A: latencyB: recall@10B: latency
HNSW, nothing else0.460.0450.84 ms0.0391.41 ms
HNSW + hnsw.iterative_scan = strict_order100.52511.2 ms0.32517.1 ms
HNSW + hnsw.iterative_scan = relaxed_order100.7679.4 ms0.72115.9 ms
B-tree on the filter column, planner chooses101.0001.26 ms1.0001.37 ms

Recall here is against “the exact top 10 under the same filter”. Where each approach fits:

1. Iterative index scans (pgvector 0.8.0 and later). Once enabled, an index scan that does not have enough results automatically scans further, until it has enough or hits a limit. strict_order guarantees results in exact distance order; relaxed_order allows slight disorder and gives better recall, and when you need strict order you sort again outside (as Search above does). The limits are hnsw.max_scan_tuples (default 20,000) and hnsw.scan_mem_multiplier (default 1, a multiple of work_mem); for IVFFlat the equivalents are ivfflat.iterative_scan (which accepts only off and relaxed_order) and ivfflat.max_probes.

  • Fits: conditions matching a moderate share of rows (say 10% or more), or too many combinations of conditions to index each one.
  • What not to expect: it solves “not enough rows”, not “the right rows”. In the table above, with a 1% condition, the row count is filled but recall is only 0.3–0.77. Lowering max_scan_tuples to 1,000 dropped recall on dataset B to 0.16, and on average it could no longer fill 10 rows.

2. An ordinary index on the filter column. The README’s starting point. When the condition is narrow, the planner uses the B-tree (or GIN) to find those few hundred rows and then sorts them exactly: 100% recall, and faster than HNSW. Fits: conditions matching few rows, such as one customer’s own data or a small category. Does not fit: conditions matching most rows; there the approximate index is still faster.

3. Partial indexes. When the condition takes only a few fixed values, build an HNSW index holding only the rows for the common value. Product search almost always includes “in stock”:

CREATE INDEX products_category ON products (category_id);
-- Vector index over in-stock products only; the planner uses it when the query says WHERE in_stock
CREATE INDEX products_embedding_in_stock ON products
    USING hnsw (embedding vector_cosine_ops)
    WHERE in_stock;

Measured, WHERE in_stock ORDER BY embedding <=> $1 LIMIT 10 used products_embedding_in_stock; adding a narrow category_id = 7 made the planner switch to the products_category B-tree to find that category and sort it exactly. Fits: only a few values, and almost every query carries the same condition. Watch out: the value in the condition must be an SQL constant. Measured, with a prepared statement taking it as a parameter, once PostgreSQL switched to a generic plan the partial index was no longer used and it fell back to a sequential scan.

4. Partitioning. Many values, for example if the shop one day becomes a platform with thousands of merchants and each may only search its own products. PARTITION BY LIST (merchant_id) gives each partition its own index. The README singles out multi-tenancy: with one shared approximate index, one tenant’s vectors affect the recall and speed of the others. Does not fit: only two or three values, where partial indexes are enough; or so many partitions that they become unmanageable.

The shop’s choice: support Q&A has a GIN index on allowed_roles. Measured, querying as payment-oncall (1%), the planner used GIN to find those few dozen rows and sorted them exactly; querying as support (99%), it used HNSW, with the iterative scan making up for the few rows filtered out. Product search uses a partial index for “in stock” and a B-tree for category, and lets the planner choose according to how narrow the condition is. The order assistant’s conversation memory is filtered by customer_id; each customer has only a few dozen rows, so a B-tree plus an exact sort is enough, with no need for HNSW at all.

Step 7: Hybrid search — full text + vector + RRF in one SQL query

“Where RAG Quality Comes From: Chunking, Embeddings, Vector Databases and Hybrid Search” explained why hybrid search matters and how RRF works, and merged two rankings in memory in Go. When all the data is in PostgreSQL, you can do it in one SQL query, with the permission condition in one place:

vec CTE embedding <=> $1 permission filter, top 40 kw CTE tsv @@ plainto_tsquery permission filter, top 40 fused sum(1 / (60 + rank)) ranks only, not scores JOIN doc_chunks text and source top k by score The permission condition appears in both CTEs, so neither side can fetch hidden chunks

Figure: the vector and full-text CTEs each take their top 40 with the same permission condition, ranks become RRF scores that are added up, and the result is joined back to the text for the top k.

// internal/vectorstore/hybrid.go
package vectorstore

import (
	"context"

	"github.com/jackc/pgx/v5"
	"github.com/pgvector/pgvector-go"
)

// Take the top 40 from the vector side and the full-text side, fuse them by rank only
// with RRF (k = 60), and return the top $4. Both sides carry the same permission filter.
const hybridSQL = `
WITH vec AS (
    SELECT id, row_number() OVER (ORDER BY distance) AS rank
    FROM (
        SELECT id, embedding <=> $1 AS distance
        FROM doc_chunks
        WHERE allowed_roles && $3
        ORDER BY embedding <=> $1
        LIMIT 40
    ) v
),
kw AS (
    SELECT id, row_number() OVER (ORDER BY ts_rank_cd(tsv, q) DESC) AS rank
    FROM doc_chunks, plainto_tsquery('simple', $2) AS q
    WHERE tsv @@ q AND allowed_roles && $3
    ORDER BY ts_rank_cd(tsv, q) DESC
    LIMIT 40
),
fused AS (
    SELECT id, sum(1.0 / (60 + rank)) AS score
    FROM (SELECT * FROM vec UNION ALL SELECT * FROM kw) both_lists
    GROUP BY id
)
SELECT c.id, c.source, c.heading, c.content, f.score
FROM fused f JOIN doc_chunks c USING (id)
ORDER BY f.score DESC, c.id
LIMIT $4`

// Fused is one hybrid search result; Score is the RRF score, higher ranks first.
type Fused struct {
	ID      int64
	Source  string
	Heading string
	Content string
	Score   float64
}

// Hybrid expects querySeg to be segmented by the same segmenter as content_seg (words separated by spaces).
func (s *Store) Hybrid(ctx context.Context, c Caller, q []float32, querySeg string, k int) ([]Fused, error) {
	rows, err := s.DB.Query(ctx, hybridSQL, pgvector.NewVector(q), querySeg, c.Roles, k)
	if err != nil {
		return nil, err
	}
	return pgx.CollectRows(rows, pgx.RowToStructByPos[Fused])
}

In the tests, with a query vector close to “Payment timeout” and the segmented query “付款 逾時” (payment, timeout), the chunk that ranked first on both sides came out on top with an RRF score of 0.0328 (about 2 / 61); a chunk on the same topic visible only to payment on-call never appeared for the support role on either side.

Limits of full-text search for Chinese. PostgreSQL’s built-in text parser does not split Chinese. Measured, to_tsvector('simple', …) on an unspaced Chinese sentence about refunding a timed-out payment produced the whole sentence as one token, so searching for the word for “timeout” found nothing; the same sentence first split into space-separated words matched. That is why the table has content_seg: the application segments the text and joins words with spaces, and queries go through the same segmenter. The options:

ApproachFitsLimits
Segment in the application, store in content_seg (this article)No extra extension; managed cloud databasesPin the segmenter version and keep queries and documents consistent; changing it means rebuilding the column
A Chinese segmentation extension in the databaseSelf-managed PostgreSQL where you can install extensionsManaged services may not support it; upgrades must take it into account
pg_trgm trigramsError codes, commands, mixed alphanumeric stringsPoor for short Chinese terms (see below)

pg_trgm is often recommended as the “no segmentation needed” answer, but be careful with short Chinese terms. Measured against that same ten-character sentence, word_similarity was 0 for the two-character word for “timeout”, 0.4 for the four-character “payment timeout”, and 0.33 for the two-character “refund” only because it happened to sit at the end of the sentence; the default pg_trgm.word_similarity_threshold is 0.6, so <% matched none of these queries. The reason is that trigrams work on “words”, and a Chinese sentence without spaces counts as one very long word; a two-character query produces trigrams padded with word-boundary spaces, which do not occur in the middle of the sentence. Before using trigrams for Chinese, measure them on your own question set.

When you do not need hybrid search: if queries are almost all natural language with no error codes or IDs, and evaluation shows vector-only recall is already good enough, an extra CTE is just extra cost.

Step 8: Pairing it with an LLM — flow, permissions and boundaries

So far, the database’s job is “find chunks that may be relevant and that this person may see”. With an LLM attached, the whole flow is:

Question + auth token Server decides Caller (roles) Embed same model, prefix SQL retrieval roles in WHERE Build prompt IDs, source, text LLM sees filtered text Check citations IDs must be in hits Answer with sources chunks that passed Outside the trust boundary: no permission columns, no SQL tool search_runbooks(query) identity and SQL set by server All the model decides is whether to search and what text to search for

Figure: the server decides the identity and writes it into the SQL condition; the model receives only the text and IDs of chunks that passed the permission filter, and code checks the citations after it answers; the only thing the model can do is call tools with fixed parameters.

  1. A question arrives, and the server decides the identity first. Role and customer ID come from the authenticated token, not from the conversation.
  2. Embed the question with the same model and the same prefix rules as the documents.
  3. Retrieve, with the permission condition in the SQL. Use Search or Hybrid; if even the nearest distance is above a threshold, answer “not found” without calling the model (the relevance threshold from the previous article).
  4. (Optional) Rerank. Add it only when the right chunks are often “retrieved but ranked low”; see “Where RAG Quality Comes From: Chunking, Embeddings, Vector Databases and Hybrid Search”.
  5. Build the prompt. Each chunk carries its ID, source and heading, sits between clear markers, and the prompt states that chunks are data, not instructions.
  6. Call the LLM and check the citations. Every ID the answer cites must be in this retrieval’s results.

What may go into the prompt and what may not:

SendDo not sendWhy
Text, IDs, sources and headings of chunks that passed the permission filterChunks the person may not see (even with “please don’t mention this”)Anything in the prompt can end up in the answer; the only reliable control is not to send it
The question itselfVector values, distance scoresUseless to the model and costs tokens; scores belong in code for thresholds and logging
Fields returned by tools that this person may already seeallowed_roles, internal ID schemes, anything about other customersThe model does not need to know how permissions are designed; less information means fewer things it can be tricked into revealing

Why not let the LLM write SQL against the vector table. “Give the model a tool that runs SQL and let it query whatever it likes” looks flexible, but has four problems:

  • Permissions disappear. Permission is the line WHERE allowed_roles && $2; if the model’s SQL leaves it out, data leaks. One injected sentence in a document is enough to make it “forget”.
  • Cost is uncontrolled. A missing LIMIT, or an ORDER BY written as an expression (Step 2), means a full sequential scan, possibly on every question.
  • Vectors are not something the model can write. The model cannot type the query vector into SQL; code has to produce it anyway, so code should build the whole query.
  • It cannot be tested or evaluated. Every query is different, so neither the recall monitoring from Step 5 nor the previous article’s regression tests are possible.

The right approach is tool calling with tools whose parameters are fixed: the model only decides “whether to search” and “what text to search for”; the SQL, the permissions and the cap on k stay on the server.

// fragment: internal/assistant/tools.go
// The model only supplies query; the identity comes from the request, k is capped, and the SQL is one of Store's fixed queries.
func (a *Assistant) searchRunbooks(ctx context.Context, caller vectorstore.Caller, input struct {
	Query string `json:"query"`
}) ([]vectorstore.Fused, error) {
	q := strings.TrimSpace(input.Query)
	if q == "" || utf8.RuneCountInString(q) > 500 {
		return nil, errors.New("query must be 1-500 characters")
	}
	vec, err := a.embedder.EmbedQuery(ctx, q) // same model and prefix rules as the documents
	if err != nil {
		return nil, err
	}
	return a.store.Hybrid(ctx, caller, vec, a.segmenter.Segment(q), 6)
}

The order assistant is simpler still: “where is my order?” needs the order status, so provide a get_order_status(order_id) tool; the order service authorises it against the customer’s identity and returns the status, times and tracking number, with no vectors involved. Do not embed structured data such as orders and payments and let the model “search” it: they have exact primary keys and permission rules, and SQL lookups are what make them accurate; embedding them only brings mistakes like “found one that looks very similar, but it is someone else’s order”. The full tool use loop, prompt injection defences and tests are implemented in the next article.

Step 9: Semantic caching, memory for agents and deduplication

Besides RAG retrieval, vector search has three other common uses, and all of them can live in the same PostgreSQL.

Semantic caching: if a question is similar enough, return the earlier answer. Calling an LLM is slow and expensive, and if “how many days do I have to return an item?” and “within how many days can I return something?” are asked hundreds of times a day, caching the answer is tempting. Unlike an ordinary cache, the key is the question’s vector and a hit means the distance is below a threshold.

Question embed Look up answer_cache same scope, corpus_version within 7 days, ≤ threshold Return earlier answer no LLM call hit Full RAG retrieve, LLM, check miss Write back if checked public FAQ scope only Questions with IDs, amounts or dates skip the cache; bump the version on reindex

Figure: a hit requires the same scope, the same corpus version and a distance within the threshold; otherwise the full RAG flow runs, and the answer is written back to the cache only after it passes the citation check.

-- migrations/011_answer_cache.sql
CREATE TABLE answer_cache (
    id             bigserial    PRIMARY KEY,
    scope          text         NOT NULL,   -- e.g. 'public-faq'; answers are never shared across permissions
    corpus_version bigint       NOT NULL,   -- bumped on every reindex, so old answers expire
    question       text         NOT NULL,
    q_embedding    vector(1024) NOT NULL,
    answer         text         NOT NULL,
    created_at     timestamptz  NOT NULL DEFAULT now()
);
CREATE INDEX answer_cache_q ON answer_cache USING hnsw (q_embedding vector_cosine_ops);
// internal/vectorstore/cache.go
package vectorstore

import (
	"context"
	"errors"

	"github.com/jackc/pgx/v5"
	"github.com/jackc/pgx/v5/pgxpool"
	"github.com/pgvector/pgvector-go"
)

// AnswerCache only caches answers that do not depend on who asks, such as the public returns FAQ.
type AnswerCache struct {
	DB          *pgxpool.Pool
	MaxDistance float64 // cosine distance threshold; tune it on real question pairs, not by feel
}

// The distance condition sits outside the MATERIALIZED CTE; inside is only ORDER BY ... LIMIT, so the index is used.
const cacheLookupSQL = `
WITH nearest AS MATERIALIZED (
    SELECT answer, q_embedding <=> $1 AS distance
    FROM answer_cache
    WHERE scope = $2 AND corpus_version = $3
      AND created_at > now() - interval '7 days'
    ORDER BY q_embedding <=> $1
    LIMIT 1
)
SELECT answer, distance FROM nearest WHERE distance <= $4`

// Lookup finds an earlier answer that is semantically close, in the same scope and for the same corpus version.
func (c *AnswerCache) Lookup(ctx context.Context, scope string, corpusVersion int64, q []float32) (string, bool, error) {
	var answer string
	var dist float64
	err := c.DB.QueryRow(ctx, cacheLookupSQL,
		pgvector.NewVector(q), scope, corpusVersion, c.MaxDistance).Scan(&answer, &dist)
	if errors.Is(err, pgx.ErrNoRows) {
		return "", false, nil
	}
	if err != nil {
		return "", false, err
	}
	return answer, true, nil
}

// Call Put only after the answer has passed the citation check.
func (c *AnswerCache) Put(ctx context.Context, scope string, corpusVersion int64, question string, q []float32, answer string) error {
	_, err := c.DB.Exec(ctx, `
INSERT INTO answer_cache (scope, corpus_version, question, q_embedding, answer)
VALUES ($1, $2, $3, $4, $5)`, scope, corpusVersion, question, pgvector.NewVector(q), answer)
	return err
}

The query follows the README’s advice: the distance condition sits outside a MATERIALIZED CTE, and inside there is only ORDER BY ... LIMIT, so the index is used.

The risks are bigger than with an ordinary cache, because “similar” is not “the same”:

  • Questions with opposite meanings have nearby vectors. “Can I get a refund?” and “When can I not get a refund?” use almost the same words; “order A-1001” and “order A-1002” differ by one character. With a loose threshold you answer one question with another’s answer. Questions containing IDs, amounts or dates should skip the cache entirely.
  • Permissions. The same question should get different answers for payment on-call and for general support. scope must include every identity factor that changes the answer; in practice, cache only public FAQ answers that are the same for everyone.
  • Staleness. When documents change, the cache keeps answering with the old rules. Use corpus_version so that every reindex expires old answers automatically, plus a time to live.
  • Mistakes are amplified. A wrong answer, once cached, is sent hundreds of times. Cache only answers that passed the citation check, and offer “report a mistake” to invalidate an entry.

Fits: large volumes of repeated public questions whose answers do not depend on who asks. Does not fit: personal questions (orders, accounts), questions whose answers change over time, and low-volume systems, where the risk outweighs the money saved. The next article takes the same position in its operations section: by default, do not cache final answers. Tune the threshold on real questions: put pairs that should hit and pairs that should not into the evaluation set.

Memory for agents. For an assistant to remember that “this customer said last time they prefer convenience-store pickup”, store each memory as a row (customer ID, text, vector, created at) and next time find relevant memories with the current question’s vector. The key is always filtering by customer_id; each customer has only a few dozen memories, so a B-tree plus an exact sort is enough (Step 6). Memories are text written by users; in the prompt they are data, not instructions, just like retrieved documents, and users must be able to see and delete them.

Deduplication. The same FAQ paragraph is copied into three runbooks, and three of the top five results are identical. After an import, find chunk pairs whose nearest-neighbour distance is very small and hand them to the document owners to merge:

-- For each chunk, find its nearest other chunk; the LATERAL subquery uses the HNSW index
SELECT a.id, b.id AS near_id, a.embedding <=> b.embedding AS distance
FROM doc_chunks a
CROSS JOIN LATERAL (
    SELECT id, embedding
    FROM doc_chunks b
    WHERE b.id <> a.id
    ORDER BY b.embedding <=> a.embedding
    LIMIT 1
) b
WHERE a.embedding <=> b.embedding < 0.02
ORDER BY distance;

This is an offline batch job; keep it off the request path. Chunks with exactly the same content are found by content_hash, no vectors needed.

Step 10: Switching embedding models — without downtime

Vectors from a new model are not in the same space as the old ones, so they must never be queried together, and the dimension often differs. Updating the whole table in place and then rebuilding the index leaves queries either broken or slow in the meantime. The approach is the same “expand, switch, contract” used for database schema changes:

You can go back at any point here: reads still use the old column 1 Add column embedding_v2 2 Dual-write + backfill 3 Build index CONCURRENTLY 4 Evaluate golden set 5 Switch reads config value 6 Drop old after a while One setting decides the read column and the query model, so they switch together Bump the semantic cache corpus_version at the same time

Figure: add a column, dual-write and backfill, build the index, evaluate, switch reads, and drop the old column after a while; until the switch you can always go back.

-- 1. New column, NULL allowed for now (NULLs are not indexed)
ALTER TABLE doc_chunks ADD COLUMN embedding_v2 vector(768);

-- 2. New chunks are written to both columns; a background job backfills old rows in batches
UPDATE doc_chunks SET embedding_v2 = $2 WHERE id = $1;

-- 3. Build the index after the backfill, without blocking writes
CREATE INDEX CONCURRENTLY doc_chunks_embedding_v2
    ON doc_chunks USING hnsw (embedding_v2 vector_cosine_ops);

-- 4. After evaluation passes, reads move to embedding_v2 and have been watched for a while
DROP INDEX CONCURRENTLY doc_chunks_embedding;
ALTER TABLE doc_chunks DROP COLUMN embedding;

A few points:

  • Rate-limit the backfill. Embedding APIs have rate and cost limits: batches of a few hundred, interruptible, resumable from the last id.
  • The switch is application configuration, not a migration. Which column reads use and which model embeds queries are decided by one setting, so they always switch together; if something goes wrong, change the setting back.
  • Run the evaluation before switching. Compare the old and new columns with the previous article’s golden question set and switch only if the new one is better.
  • Expire the cache too. The semantic cache’s vectors came from the old model as well; bump corpus_version.

Three ways to lay it out:

ApproachFitsCosts and caveats
A new column (this article)Changing model occasionally, one or two versions at onceThe table is wider during the transition, and two indexes take space at the same time
One row per model: a vector column without a dimension plus one partial expression index per modelEvaluating several models side by side oftenQueries must write embedding::vector(768); the model name must be an SQL constant, because with a parameter a generic plan does not use the partial index (measured)
A new table, switched by renaming or through a viewChunking rules change too, so every chunk boundary movesPermissions and other columns have to move as well; writes at the moment of the switch need handling

Step 11: Capacity, quantisation and day-to-day operations

Work out capacity first. With 1024 dimensions and a million chunks: vector takes 4,104 bytes each, about 4.1 GB for the vectors alone; halfvec about 2.1 GB. HNSW also stores each point’s neighbours; measured at 384 dimensions and 50,000 rows, the vectors themselves were about 77 MB and the HNSW index 98 MB. The index does not have to fit in memory, but performance is much better if it does (README). One easily missed detail: the vector type’s storage is EXTERNAL, so values over about 2 KB are stored out of line in TOAST, and 1024 dimensions is over that. The README recommends STORAGE PLAIN to keep vectors inline, but a whole row must fit in an 8 KB page; measured, a 2,500-dimension PLAIN column could not be written.

Quantisation: search coarsely with a smaller representation, then rerank with the original vectors.

Query vector bit HNSW index Hamming distance <~> 100 candidates Rerank originals cosine distance <=> only 100 rows Top 10 vector HNSW 98 MB halfvec HNSW 56 MB bit HNSW 17 MB Index sizes at 50,000 rows, 384 dimensions (measured)

Figure: a bit HNSW index first returns 100 candidates, then cosine distance on the original vectors picks the top 10; the index shrinks from 98 MB to 17 MB, and recall has to be measured.

-- halfvec expression index: the table still holds vector, the index uses half precision
CREATE INDEX ON items USING hnsw ((embedding::halfvec(384)) halfvec_cosine_ops);
SELECT id FROM items ORDER BY embedding::halfvec(384) <=> $1::halfvec(384) LIMIT 10;

-- Binary quantisation: keep only the sign of each dimension, then rerank with the original vectors
CREATE INDEX ON items USING hnsw ((binary_quantize(embedding)::bit(384)) bit_hamming_ops);
SELECT id FROM (
    SELECT id, embedding FROM items
    ORDER BY binary_quantize(embedding)::bit(384) <~> binary_quantize($1::vector)
    LIMIT 100
) candidates
ORDER BY embedding <=> $1
LIMIT 10;

Measured (the same two datasets, default HNSW parameters):

ApproachIndex sizeA: recall@10B: recall@10
vector HNSW98 MB0.9290.919
halfvec expression index56 MB0.9680.908
bit index, top 10 directly17 MB0.2990.330
bit index for 40, reranked with original vectors17 MB0.6010.524
bit index for 100 (ef_search = 100), reranked17 MB0.8840.696

halfvec loses almost no recall and the index is about 40% smaller, so it is the best-value first step; for models with more than 2,000 dimensions it is also one way to be able to index at all. Binary quantisation lost a lot on this synthetic data, and needs many more rerank candidates to recover; its effect depends heavily on the model and the data, so consider it only when the index does not fit in memory, and always measure.

Day-to-day operations:

  • Deletes and VACUUM. Deleted or updated rows still occupy places in the index until VACUUM, and the README notes that dead tuples can also mean fewer results. VACUUM on HNSW can take a long time; the README suggests REINDEX INDEX CONCURRENTLY first, then VACUUM. For large document rebuilds, the new-column approach from Step 10 is better than mass in-place updates.
  • Index builds must not block writes. In production always use CREATE INDEX CONCURRENTLY; a failed build leaves an invalid index behind that you must drop and recreate.
  • Read replicas share the query load. pgvector data goes through the WAL and replicates normally. Vector queries are CPU-heavy, and routing them to a replica protects order transactions on the primary; watch replication lag, because freshly imported documents may not be visible yet. See “PostgreSQL Read/Write Splitting: Replication Lag, Routing and What to Watch For”.
  • Monitor four things: query latency (p95 per query from pg_stat_statements); recall, measured daily as in Step 5; an application counter for “fewer than k rows returned”, the most direct signal of the post-filter problem; and index size plus dead rows (pg_stat_user_tables.n_dead_tup).
  • Set parameters inside the transaction. Use SET LOCAL or set_config(..., true) for ef_search and iterative_scan; do not SET them on a pooled connection and forget, because the next request that borrows that connection inherits them.

Common pitfalls

Ordering by similarity, descending. ORDER BY 1 - (embedding <=> $1) DESC gives correct results but does not use the index; with more data it becomes a full table scan. Order by the distance operator ascending, and put similarity in the SELECT list.

The index’s operator class does not match the query’s operator. Build with vector_cosine_ops, query with <->, and the index is never used.

Fewer results after adding HNSW. LIMIT exceeds hnsw.ef_search, or the filter removed the candidates. Tune ef_search, enable iterative scans, or switch to a B-tree or a partial index.

Assuming iterative scans fix every filtering problem. They fill the row count, but with a very narrow condition recall can still be around 30%; there, use an ordinary index plus an exact sort.

Passing a partial index’s condition as a parameter. A generic plan cannot prove the parameter matches the index condition and falls back to a sequential scan. Write the value as a constant.

Building IVFFlat on an empty or nearly empty table. The clusters come from the data present at the time, later data is clustered badly, and recall is poor. Build it after the data is in, and rebuild when the distribution changes.

Different models or prefixes for queries and documents. With the same dimension nothing fails, and results look random. Record the model version on every row, and keep query and document settings in one place.

Handling permissions after retrieval. Retrieving everything and asking the model not to mention some of it, or letting the model decide, is no permission at all. Put the condition in the SQL.

Letting the LLM run arbitrary SQL. Permissions, cost control and testability all go. Use tools with fixed parameters.

A semantic cache without scopes. If different roles and different document versions share one cache, or questions with IDs also hit it, you answer with someone else’s answer.

Measuring recall with the real and exact queries sharing the same SQL text. A cached plan can make both sides identical, producing a fake recall of 1.

Parallel HNSW builds failing inside a container. With a small /dev/shm you get could not resize shared memory segment; raise the shared memory, or lower max_parallel_maintenance_workers.

Key takeaways

  • pgvector’s value is that vectors share a transaction, permissions and operations with business data; consider a dedicated vector database when vector queries become the main workload or the index far exceeds one machine’s memory.
  • Default to vector with cosine distance; use inner product when vectors are normalised; halfvec halves the space and can be indexed up to 4,000 dimensions. Write ORDER BY as the distance operator ascending, matching the index’s operator class.
  • Store the text, source, hash, permissions and model version, not just vectors; bulk-load with COPY and build the index after loading.
  • Up to tens of thousands of rows, or with narrow conditions, exact search is enough; otherwise use HNSW; build IVFFlat only after the data is in. Measure parameters such as ef_search against exact search; different data behaves very differently.
  • Approximate indexes post-filter, so narrow conditions return fewer rows. Use iterative scans for moderate shares, a B-tree for very narrow ones, partial indexes for a few fixed values, and partitioning for multi-tenancy.
  • Hybrid search fits in one SQL query; Chinese must be segmented first, and pg_trgm is poor for short Chinese terms.
  • With an LLM: the server decides the identity and permissions go in the SQL; send only text that passed the filter; the model may only call tools with fixed parameters and never writes SQL; look up structured data such as orders with tools rather than embedding it.
  • A semantic cache suits only public questions whose answers do not depend on who asks, and needs a scope, a corpus version, a time to live and a conservative threshold.
  • Switch models with a new column, dual writes, a backfill, a CONCURRENTLY index build and an evaluation before switching; for quantisation, try halfvec first and always measure binary quantisation; monitor latency, recall, short result counts and dead rows.

References

Next

The columns, indexes, filters and boundaries with an LLM are now clear; next, they go into a complete program. The next article, “Building a RAG Pipeline in Go: Chunking, Vector Search and Tool Calling”, goes from chunking and embedding through the PostgreSQL + pgvector table and hybrid search to Claude’s tool use, citation checks, tests and evaluation, putting this article’s approach into a full Go pipeline.