Home › RAG & vector DBs › pgvector rules
pgvector rules
Cursor rules for vector search in PostgreSQL with pgvector: column types, HNSW indexes, filtering, and hybrid queries.
CursorRAG & vector DBs
How to use
Save this as .cursor/rules/pgvector.mdc in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.
.cursor/rules/pgvector.mdcDownload ---
description: pgvector conventions
globs: ["**/*.sql","**/*.{ts,py}"]
alwaysApply: false
---
# pgvector
- Enable with a migration: `CREATE EXTENSION IF NOT EXISTS vector;`. Columns use the exact dimension of the embedding model: `embedding vector(1536)`. Store `embedding_model text` next to it.
- Consider `halfvec(n)` to halve storage for large tables; quantization trades a little recall.
- Index with HNSW using the operator class matching your distance: `CREATE INDEX CONCURRENTLY ON chunks USING hnsw (embedding vector_cosine_ops);`. Use `vector_ip_ops` for normalized embeddings with inner product, `vector_l2_ops` for L2.
- Query with the matching operator and `ORDER BY ... LIMIT`: `SELECT id, content FROM chunks WHERE tenant_id = $1 ORDER BY embedding <=> $2 LIMIT 20;` (`<=>` cosine distance, `<#>` negative inner product, `<->` L2). The index is only used with `ORDER BY distance LIMIT`.
- Filtering: selective filters can starve results; enable iterative scans (`SET hnsw.iterative_scan = relaxed_order;`) or partition/partial-index by tenant.
- Tune recall with `SET hnsw.ef_search = 100;` per query/session; measure recall against exact search on a sample.
- Hybrid search: combine with full-text (`tsvector` + `ts_rank`) using reciprocal rank fusion in SQL or app code.
- Pass embeddings as parameters (the driver's pgvector type helper), never string-formatted SQL.
- Batch inserts with `COPY` or multi-row inserts; build the HNSW index after bulk loads when possible.
## Done when
`EXPLAIN ANALYZE` shows an index scan on the HNSW index for the main query, and retrieval tests pass.