Build a Production RAG Agent with pgvector and PostgreSQL
This deep-dive covers rag agent pgvector postgresql ubuntu with actionable analysis, practical implications, and expert insights.
Why PostgreSQL + pgvector Is the Pragmatic Choice for Production RAG
Most Retrieval-Augmented Generation prototypes break in production because vector storage gets separated from application permissions, freshness timestamps, and backups. By adding the open-source pgvector extension to PostgreSQL 16 on Ubuntu 24.04, your vector embeddings live right beside your relational tables, inherit full ACID backups, and support hybrid semantic + keyword search in a single SQL query.
Step 1: Install PostgreSQL 16 and pgvector on Ubuntu 24.04
Ubuntu 24.04 includes PostgreSQL 16 and the prebuilt pgvector package directly in APT (or via the official PGDG repository):
sudo apt update
sudo apt install -y postgresql-16 postgresql-16-pgvector python3-venv python3-pip
sudo systemctl enable --now postgresql
Create a dedicated database and application user:
sudo -u postgres psql -c "CREATE USER rag_app WITH PASSWORD 'change_me_strong';"
sudo -u postgres psql -c "CREATE DATABASE rag_db OWNER rag_app;"
sudo -u postgres psql -d rag_db -c "CREATE EXTENSION IF NOT EXISTS vector;"
Step 2: Create a Hybrid Semantic + Full-Text Schema
Store each document chunk with its 768-dimensional embedding, a generated PostgreSQL tsvector column for exact keyword matching, and both an HNSW index and a GIN full-text index:
CREATE TABLE knowledge_chunks (
id BIGSERIAL PRIMARY KEY,
tenant_id INTEGER NOT NULL DEFAULT 1,
source_url TEXT NOT NULL,
heading TEXT NOT NULL,
content TEXT NOT NULL,
embedding vector(768) NOT NULL,
fts tsvector GENERATED ALWAYS AS (to_tsvector('english', heading || ' ' || content)) STORED,
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
);
CREATE INDEX idx_chunks_embedding_hnsw
ON knowledge_chunks USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);
CREATE INDEX idx_chunks_fts_gin
ON knowledge_chunks USING GIN (fts);
CREATE INDEX idx_chunks_tenant ON knowledge_chunks (tenant_id);
Step 3: Ingest Documents and Query with Hybrid Reciprocal Rank Fusion
Install psycopg, pgvector, and sentence-transformers in a Python virtual environment:
python3 -m venv ~/rag-env && source ~/rag-env/bin/activate
pip install "psycopg[binary]" pgvector sentence-transformers openai
Use Reciprocal Rank Fusion (RRF) inside a single SQL query to blend vector similarity and exact full-text matches cleanly:
import psycopg
from pgvector.psycopg import register_vector
from sentence_transformers import SentenceTransformer
embedder = SentenceTransformer("BAAI/bge-base-en-v1.5")
HYBRID_SQL = """
WITH semantic AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> %(vec)s) AS rank_s
FROM knowledge_chunks
WHERE tenant_id = %(tenant)s
ORDER BY embedding <=> %(vec)s
LIMIT 20
),
keyword AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(fts, plainto_tsquery('english', %(q)s)) DESC) AS rank_k
FROM knowledge_chunks
WHERE tenant_id = %(tenant)s
AND fts @@ plainto_tsquery('english', %(q)s)
LIMIT 20
)
SELECT
c.heading,
c.source_url,
c.content,
COALESCE(1.0 / (60 + s.rank_s), 0.0) + COALESCE(1.0 / (60 + k.rank_k), 0.0) AS rrf_score
FROM knowledge_chunks c
LEFT JOIN semantic s ON s.id = c.id
LEFT JOIN keyword k ON k.id = c.id
WHERE s.id IS NOT NULL OR k.id IS NOT NULL
ORDER BY rrf_score DESC
LIMIT 5;
"""
def retrieve(conn: psycopg.Connection, query: str, tenant_id: int = 1) -> list[dict]:
vec = embedder.encode(query, normalize_embeddings=True).tolist()
with conn.cursor() as cur:
cur.execute(HYBRID_SQL, {"vec": vec, "q": query, "tenant": tenant_id})
rows = cur.fetchall()
return [
{"heading": r[0], "source_url": r[1], "content": r[2], "score": float(r[3])}
for r in rows
]
Step 4: Ground the LLM Prompt with Verifiable Citations
Pass only the top 4 to 5 retrieved chunks to your local Ollama or vLLM endpoint with a strict system instruction: answer solely from the provided context, cite the source_url for each technical claim, and explicitly state when the knowledge base lacks the answer.
Tuning PostgreSQL Memory for Fast HNSW Queries
- Increase
shared_buffers: Set to 25 percent of system RAM so HNSW graph layers stay hot in memory. - Increase
maintenance_work_mem: Set to1GBor2GBduring bulk index creation to speed up HNSW builds by 3x to 5x. - Tune
hnsw.ef_searchper session: Default is40; raise to80or100withSET LOCAL hnsw.ef_search = 80;when accuracy matters more than 2ms of extra latency.
Summary
PostgreSQL 16 with pgvector gives you a single, battle-tested datastore for both relational application state and sub-15ms hybrid RAG retrieval. Combining HNSW semantic search with PostgreSQL tsvector via RRF delivers noticeably sharper technical answers than pure vector search alone.
Was this technical analysis helpful?
Your feedback informs our benchmark updates and ongoing article audits.
FAQ
Frequently Asked Questions
Structured for search engines and AI answer systems (AEO/GEO).
Using pgvector avoids running and backing up a second database system. You can filter embeddings by tenant_id, permissions, and publish dates inside a single transactional SQL query.
Choose HNSW for almost all production RAG workloads. It provides better query recall and lower latency, and you can create it on an empty table before inserting vectors.
Dense embeddings capture semantic meaning rather than exact token spelling. Combining pgvector cosine distance with PostgreSQL full-text search (tsvector / ts_rank) via Reciprocal Rank Fusion fixes exact-match recall.
Chunks of 400 to 600 tokens with 60 to 80 tokens of overlap preserve code blocks and surrounding explanations without diluting vector specificity.
More answers in our FAQ hub.
Newsletter
Practical Linux & Applied AI Newsletter
Get new tested tutorials and benchmark comparisons delivered directly to your inbox. Zero spam.
Join Weekly guides readers getting our weekly digest.
- Practical Linux administration & terminal workflows
- Tested open-source AI setups & benchmarks
- Zero spam - unsubscribe anytime