PostgreSQL Extensions
PostgreSQL's extension system is why it keeps absorbing entire categories of specialized database — including, now, vector search.
Intermediate
CREATE EXTENSION IF NOT EXISTS pgvector;
CREATE EXTENSION IF NOT EXISTS postgis;
\dx -- list installed extensions, in psql
pgvector adds a vector column type and distance operators — the exact building block behind RAG (retrieval-augmented generation) and semantic search over embeddings. Given this site's focus, this is the extension most worth knowing well.CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE documents (
id SERIAL PRIMARY KEY,
content TEXT,
embedding VECTOR(1536) -- e.g. OpenAI text-embedding-3-small dimensionality
);
-- cosine distance — the standard metric for most text embedding models
SELECT content, embedding <=> '[0.01, -0.02, ...]' AS distance
FROM documents
ORDER BY embedding <=> '[0.01, -0.02, ...]'
LIMIT 5;
| Operator | Distance metric |
|---|---|
<-> | Euclidean (L2) |
<#> | negative inner product |
<=> | cosine distance |
CREATE INDEX ON documents USING hnsw (embedding vector_cosine_ops);
-- HNSW: better query performance, slower to build. ivfflat is the other option: faster to build, needs tuning (lists parameter).
| Extension | Adds |
|---|---|
| PostGIS | geographic/geometric types and spatial queries — the standard for location-based data in Postgres |
| pg_stat_statements | tracks execution statistics for every query that's run — the standard way to find your actual slowest/most frequent queries in production, rather than guessing |
| uuid-ossp / pgcrypto | UUID generation functions (gen_random_uuid() is now built into core as of PG13, making this less necessary than it used to be) |
| pg_trgm | trigram-based fuzzy string matching — typo-tolerant search and similarity scoring that full-text search's exact stemming doesn't cover |