Traditional databases excel at exact matches (status = 'ACTIVE') and basic substring searches. Modern AI applications require semantic search—finding records based on conceptual meaning rather than exact keywords.
The pgvector extension turns PostgreSQL into a high-performance vector database, co-locating embeddings directly alongside relational data.
Understanding Vector Dimensions & Distance Metrics
An embedding is an array of floating-point numbers generated by a machine learning model representing the conceptual coordinates of text, images, or audio:
- OpenAI
text-embedding-3-small: 1,536 dimensions - Google Gemini
text-embedding-004: 768 dimensions
Vector Distance Operators in PostgreSQL
| Operator | Metric | Best Use Case |
|---|---|---|
<-> | Euclidean (L2) Distance | Absolute geometric spatial distance |
<=> | Cosine Distance | Normalized text similarity (ignores vector magnitude) |
<#> | Negative Inner Product | Maximum Inner Product Search (MIPS) |
Table Schema and Indexing: HNSW vs IVFFlat
-- 1. Enable the pgvector extension
CREATE EXTENSION IF NOT EXISTS vector;
-- 2. Create the documents table
CREATE TABLE knowledge_base (
id BIGSERIAL PRIMARY KEY,
title TEXT NOT NULL,
chunk_content TEXT NOT NULL,
metadata JSONB DEFAULT '{}'::jsonb,
-- 1536-dimensional vector column
embedding VECTOR(1536) NOT NULL
);
-- 3. Create an HNSW (Hierarchical Navigable Small World) index
-- HNSW offers much faster search speeds and better recall than IVFFlat without requiring training
CREATE INDEX idx_knowledge_hnsw
ON knowledge_base
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
Building the Similarity Search Match Function
To search vectors from the client SDK, define a PostgreSQL stored procedure using cosine distance:
CREATE OR REPLACE FUNCTION match_knowledge_base (
query_embedding VECTOR(1536),
match_threshold FLOAT DEFAULT 0.75,
match_count INT DEFAULT 5
)
RETURNS TABLE (
id BIGINT,
title TEXT,
chunk_content TEXT,
similarity FLOAT
) LANGUAGE sql STABLE AS $$
SELECT
kb.id,
kb.title,
kb.chunk_content,
-- Convert cosine distance (0 to 2) into similarity score (1 to -1)
1 - (kb.embedding <=> query_embedding) AS similarity
FROM knowledge_base kb
WHERE 1 - (kb.embedding <=> query_embedding) > match_threshold
ORDER BY kb.embedding <=> query_embedding ASC
LIMIT match_count;
$$;
Execute the match query from TypeScript:
const { data: matchedChunks, error } = await supabase.rpc('match_knowledge_base', {
query_embedding: userQueryVector,
match_threshold: 0.80,
match_count: 5
});
Exercises
- Create a table storing user preference embeddings and write a query finding the top 10 most similar users.
- Explain the trade-offs between an IVFFlat index (requires clustering centroids) versus an HNSW index (graph-based traversal).
- Why does storing embeddings in PostgreSQL eliminate the synchronization overhead of dedicated vector databases like Pinecone?