With the explosion of Generative AI, Retrieval-Augmented Generation (RAG), and recommendation engines, web developers must search by semantic intent rather than rigid keyword matching. PostgreSQL with pgvector brings vector embeddings directly into your standard relational database.
| Index Algorithm | Query Recall & Speed | Build Time & RAM | Recommended For |
|---|---|---|---|
| HNSW (Hierarchical Navigable Small World) | State-of-the-art (> 98% recall, < 5ms search). | Higher RAM and build time. | Production Default for web applications. |
| IVFFlat (Inverted File Flat) | Moderate recall (requires tuning probes). | Fast build, low memory footprint. | Massive scale where RAM is constrained. |
-- Step 1: Enable the pgvector extension in PostgreSQL
CREATE EXTENSION IF NOT EXISTS vector;
-- Step 2: Create documents table with a 384-dimensional embedding column
CREATE TABLE knowledge_base (
id SERIAL PRIMARY KEY,
title VARCHAR(255) NOT NULL,
category VARCHAR(50) NOT NULL,
content TEXT NOT NULL,
embedding vector(384) -- 384-dim vector from all-MiniLM-L6-v2
);
-- Step 3: Create high-speed HNSW index with Cosine Distance
CREATE INDEX ON knowledge_base USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
-- Step 4: Hybrid Query - Semantic Search + Relational Filter
SELECT
id,
title,
category,
content,
ROUND((1 - (embedding <=> '[0.024, -0.051, ..., 0.089]'))::numeric, 4) AS similarity_score
FROM knowledge_base
WHERE category = 'Tutorials'
ORDER BY embedding <=> '[0.024, -0.051, ..., 0.089]' -- Cosine distance operator
LIMIT 5;
In your FastAPI backend, generate vector embeddings using SentenceTransformer('all-MiniLM-L6-v2').encode(user_query).tolist() and pass the array directly into your PostgreSQL SQLAlchemy query parameters!
Broaden your statistical analysis, Python data wrangling, and production engineering expertise:
The mathematical vector similarity metrics used by HNSW and IVFFlat.
Build modern semantic search endpoints and RAG data pipelines.
Run PostgreSQL with pgvector extension enabled inside Docker.
Compare document store search with native relational vector extensions.