Enabling pgvector and Core Setup Commands
The pgvector extension adds a native vector data type and similarity operators to PostgreSQL. On a self-hosted instance running Postgres 15 or 16, install it via your package manager or compile from source using make install from the pgvector repository at tag v0.7.4. Once installed, connect with psql and run:
CREATE EXTENSION IF NOT EXISTS vector;
This command registers the extension and makes the vector type, the operators <-> (L2 distance), <=> (cosine distance), and <#> (negative inner product) available. Verify with \dx in psql. For Docker-based development the official Postgres image can be extended with apt-get install -y postgresql-16-pgvector in a Dockerfile.
Production managed services such as Supabase, Neon, and AWS RDS (with custom extensions) already include recent pgvector builds. The extension stores each vector as a fixed-width array of 32-bit floats, so a 1536-dimensional OpenAI text-embedding-3-small vector consumes 6 KiB per row before indexing overhead.
Table Design for Vector Storage
Effective schema design balances query speed, storage cost, and filtering needs. A minimal documents table looks like this:
CREATE TABLE document_chunks (
id BIGSERIAL PRIMARY KEY,
document_id UUID NOT NULL,
chunk_index INTEGER NOT NULL,
content TEXT NOT NULL,
metadata JSONB,
embedding VECTOR(1536) NOT NULL,
created_at TIMESTAMPTZ DEFAULT NOW()
);
CREATE INDEX idx_document_chunks_doc_id ON document_chunks(document_id);
The embedding column uses the exact dimensionality of your embedding model. Storing 1536 dimensions is common for OpenAI models; sentence-transformers/all-MiniLM-L6-v2 uses 384. Adding a metadata JSONB column allows tenant isolation, source tracking, or content-type filters without changing the table structure later.
Always pair the vector column with an indexed foreign-key-like column such as document_id so you can efficiently delete all chunks belonging to one document when the source changes. Vacuum and autovacuum settings should be tuned higher than default on large tables because vector columns increase tuple size significantly.
Generating and Inserting Embeddings from Node.js
Embeddings must be generated consistently with the same model used at query time. The following TypeScript snippet uses the OpenAI SDK to embed chunks and store them via postgres.js:
import { postgres } from '@vercel/postgres';
import OpenAI from 'openai';
const openai = new OpenAI();
const sql = postgres(process.env.POSTGRES_URL!);
async function storeChunk(documentId: string, content: string, metadata: any) {
const embeddingResponse = await openai.embeddings.create({
model: 'text-embedding-3-small',
input: content,
dimensions: 1536
});
const embedding = embeddingResponse.data[0].embedding;
await sql`
INSERT INTO document_chunks (
document_id, chunk_index, content, metadata, embedding
) VALUES (
${documentId},
0,
${content},
${metadata},
${JSON.stringify(embedding)}::vector
)
`;
}
Note the cast ::vector — the driver sends the array as JSON and Postgres converts it. For batches larger than a few hundred rows, use the copy protocol or unnest an array of records to reduce round-trips. Batch size of 50–100 embeddings balances memory usage on the Postgres side with acceptable latency.
Basic Similarity Search Operators and Queries
Three distance operators are available. Cosine distance (<=>) is most common for normalized embeddings:
SELECT
content,
1 - (embedding <=> ${queryEmbedding}::vector) AS similarity
FROM document_chunks
ORDER BY embedding <=> ${queryEmbedding}::vector
LIMIT 5;
The expression 1 - (embedding <=> ...) converts distance to a similarity score between 0 and 1. For inner-product distance on already normalized vectors, - (embedding <#> query) yields the same ordering. L2 distance works best when vector magnitude carries meaning.
Without an index these queries perform a sequential scan, computing distance for every row. On a table of 100,000 chunks this becomes impractical; an index is required for production use.
IVFFlat Index Mechanics and Creation
IVFFlat (Inverted File Flat) is an approximate nearest neighbor method that partitions vectors into clusters. Create it with:
CREATE INDEX idx_chunks_ivfflat
ON document_chunks
USING ivfflat (embedding vector_cosine_ops)
WITH (lists = 200);
The lists parameter should be roughly rows / 1000 for tables up to a few million rows. During query time Postgres probes a subset of these lists. The vector_cosine_ops specifies the distance function and must match the query operator. Probe count can be increased at query time with:
SET ivfflat.probes = 10;
Higher probe values improve recall at the cost of latency. IVFFlat index build time is fast and memory overhead is moderate, making it suitable for rapidly changing datasets where re-indexing occurs often.
HNSW Index: Parameters, Build Process and Query Tuning
Hierarchical Navigable Small World graphs deliver higher recall and lower query latency than IVFFlat on most workloads once built. The creation syntax is:
CREATE INDEX idx_chunks_hnsw
ON document_chunks
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
m controls the number of connections per node (typical values 8–64); higher values improve recall but increase index size. ef_construction determines how thoroughly the graph is built during INSERT or REINDEX — values of 64–400 are common. Build time for HNSW is noticeably longer than IVFFlat; on a 500k row table with 1536 dimensions expect 10–30 minutes on a 4-vCPU instance.
At query time, control search depth with:
SET hnsw.ef_search = 40;
The default is 40. Values above 100 deliver diminishing returns for most embedding spaces while increasing CPU. Monitor index size with pg_relation_size; HNSW indexes are typically 2–4× larger than the underlying table for 1536-dimensional vectors.
Index Selection Trade-offs
IVFFlat offers faster index creation and lower storage overhead, making it preferable during heavy write phases or when recall of 85–90 % is acceptable. HNSW provides superior recall (often >98 %) and sub-millisecond query times after the initial build cost. Rebuilding an HNSW index blocks writes unless you use CONCURRENTLY (available in Postgres 14+ for some index types, though pgvector support varies by version).
Memory usage during query is higher for HNSW because the graph must be loaded into shared_buffers. On instances with constrained RAM, keep the number of concurrent complex vector queries limited or increase shared_buffers to hold the index.
Hybrid Search: Combining Full-Text and Vector Ranking
Pure vector search can return semantically related but off-topic results. Hybrid search merges BM25 ranking with vector distance. A practical implementation normalizes both scores and combines them with weights:
SELECT
content,
(ts_rank_cd(to_tsvector('english', content), query) * 0.4 +
(1 - (embedding <=> ${embedding}::vector)) * 0.6) AS rank
FROM document_chunks,
plainto_tsquery('english', ${searchTerm}) query
WHERE to_tsvector('english', content) @@ query
ORDER BY rank DESC
LIMIT 10;
The weights 0.4/0.6 are tunable per domain. For more precise control, materialize both scores separately, normalize them against min/max values observed in a calibration set, then combine. Postgres 16’s new ts_rank improvements and the ability to create expression indexes on to_tsvector further speed up the text component.
A GIN index on the tsvector column is mandatory for acceptable text search performance:
CREATE INDEX idx_chunks_fts
ON document_chunks
USING gin (to_tsvector('english', content));
Building a Complete RAG Retrieval Function in TypeScript
Here is a production-ready retrieval function that performs hybrid search, applies metadata filters, and returns formatted context for an LLM:
async function retrieveContext(
queryText: string,
tenantId: string,
limit = 6
): Promise<string> {
const embedding = await generateEmbedding(queryText); // returns number[]
const result = await sql`
WITH vector_results AS (
SELECT
content,
(1 - (embedding <=> ${embedding}::vector)) AS vec_score
FROM document_chunks
WHERE metadata->>'tenant_id' = ${tenantId}
ORDER BY embedding <=> ${embedding}::vector
LIMIT 20
),
text_results AS (
SELECT
content,
ts_rank_cd(to_tsvector('english', content),
plainto_tsquery('english', ${queryText})) AS text_score
FROM document_chunks
WHERE to_tsvector('english', content) @@
plainto_tsquery('english', ${queryText})
AND metadata->>'tenant_id' = ${tenantId}
LIMIT 20
)
SELECT content
FROM (
SELECT content,
(COALESCE(vec_score, 0) * 0.6 + COALESCE(text_score, 0) * 0.4) AS score
FROM vector_results
FULL OUTER JOIN text_results USING (content)
) combined
ORDER BY score DESC
LIMIT ${limit}
`;
return result.map(r => r.content).join('\n\n');
}
This CTE approach avoids expensive subqueries. The FULL OUTER JOIN on content works because duplicate content across chunks is rare after proper deduplication at ingest time. Adjust weights based on offline evaluation with a validation dataset of queries and expected relevant chunks.
Chunking Strategies That Affect Retrieval Quality
Retrieval quality depends heavily on chunk size and overlap. Fixed-size chunks of 512 tokens with 50-token overlap work for many documentation corpora. Semantic chunking — splitting at paragraph boundaries or using embedding similarity between consecutive sentences — often yields higher relevance but requires more preprocessing logic.
Store the original document_id and chunk_index so you can reconstruct full documents or enforce diversity (avoid returning three chunks from the same document). Adding a chunk_index column also helps when displaying source references to users.
Metadata Filtering and Multi-Tenant Isolation
Apply filters before the similarity search to reduce the candidate set. JSONB indexes on commonly filtered keys improve performance:
CREATE INDEX idx_chunks_tenant
ON document_chunks
USING btree ((metadata->>'tenant_id'));
With a selective filter the planner can use an index scan on the metadata column followed by a limited vector scan, dramatically reducing distance calculations. For strict isolation combine this with Postgres Row Level Security policies that reference the metadata column or a separate tenant table.
Index Maintenance and Update Patterns
When documents change, old embeddings must be removed and new ones inserted. A simple pattern is:
DELETE FROM document_chunks
WHERE document_id = ${id};
-- then re-insert all new chunks
HNSW indexes slow down with frequent updates because each INSERT performs graph maintenance. Periodic REINDEX CONCURRENTLY on the HNSW index restores optimal structure. Schedule reindexing during low-traffic windows; monitor pg_stat_progress_create_index to track progress.
Observability and Query Plan Analysis
Use EXPLAIN (ANALYZE, BUFFERS) on representative queries to see whether the index is used and how many buffers are read. Enable pg_stat_statements and track average latency and calls for queries containing the <=> operator. Key metrics to watch:
- Index scan vs. sequential scan choice
- ef_search or probes value effect on execution time
- Cache hit ratio on the vector index
- CPU time versus IO time split
Tools like pgBadger or the Neon query insights dashboard surface these numbers automatically. When latency spikes, the most common cause is an HNSW index that has not been reindexed after heavy updates, causing degraded graph quality.
Scaling Beyond a Single Node
For datasets larger than a few million vectors, consider Citus columnar storage for the non-vector columns while keeping vectors on the coordinator, or shard by tenant_id. Because vector indexes are not yet distributed by Citus, each shard maintains its own HNSW index. Query federation then merges results using a top-k merge on the similarity scores.
Read replicas can serve vector search traffic if you accept slight staleness; however, the replication lag must be monitored because an embedding inserted on the primary appears on replicas only after WAL replay. For truly global scale, some teams replicate embeddings to specialized vector databases while keeping primary metadata in Postgres, accepting the consistency trade-off.
Cost and Hardware Considerations
Vector indexes increase storage requirements by 1.5–4× depending on dimensionality and index type. On cloud instances, this directly affects billed storage and IOPS. HNSW indexes benefit from instances with high memory-to-CPU ratios because the graph traversal loads many index pages into RAM. A rough starting point for a production RAG application with 500k chunks is a 4 vCPU / 16 GB instance; scale vertically before horizontally for simplicity.
Embedding generation cost usually dominates over query cost. Using smaller models such as text-embedding-3-small instead of text-embedding-3-large reduces both token spend and vector size (from 3072 to 1536 dimensions) while retaining most relevance for English text.
Common Pitfalls and Production Checklist
- Always match the index operator class (
vector_cosine_ops) with the query operator; mismatch silently disables the index. - Normalize embeddings at ingest time if using inner product; otherwise cosine distance is safer.
- Test recall with a held-out set of queries and known relevant chunks before choosing final index parameters.
- Monitor index bloat with
pgstattuple; vacuuming alone does not shrink vector indexes. - Implement retry logic with exponential backoff around embedding API calls; store partial progress to avoid reprocessing entire documents after transient failures.
- Use connection pooling (PgBouncer or Supabase’s pooler) because vector queries are more CPU intensive than typical CRUD workloads.
Following this checklist prevents the majority of production surprises when moving from prototype to thousands of daily users.
Integrating with Modern TypeScript ORMs
While raw SQL offers the most control, Kysely and Drizzle (via raw query escapes) both support vector literals. With Kysely you can create a helper:
sql<number[]>`${embedding}::vector`
This maintains type safety while still using the database’s native casting. For applications already invested in Prisma, the Prisma.sql template literal achieves the same result. The performance difference between ORM-generated and handwritten queries is negligible once the index is hit; the real cost is in the embedding generation step.
Future Extensions and Community Ecosystem
The pgvector project continues to add features such as sparse vector support and improved disk-based indexing. Community extensions like pgai from Timescale add automatic embedding generation inside the database using locally hosted models via foreign data wrappers. These reduce data movement but require careful GPU provisioning on the database host.
Regardless of future improvements, the core patterns — deliberate index parameter tuning, hybrid scoring, metadata filtering before vector computation, and systematic recall evaluation — remain the foundation for reliable semantic search inside PostgreSQL.
