RAG with PostgreSQL and pgvector

Store chunks and embeddings in PostgreSQL with pgvector, combine SQL filters with vector search, and answer questions.

Last Updated: 27, Nov 2026

Search Tutorials

--Ads--

Module 7 · Lesson 4 of 8 · Intermediate

RAG with PostgreSQL and pgvector

Store chunks and embeddings in PostgreSQL with pgvector, combine SQL filters with vector search, and answer questions.

If your application already runs on PostgreSQL, you may not need a separate vector database at all. The pgvector extension adds a vector column type and approximate nearest-neighbour indexes to PostgreSQL. In this lesson you build a complete RAG application on PostgreSQL: a schema for documents and chunks, hybrid filtering with SQL, vector search, and grounded answers.

What you will learn

  • How to run PostgreSQL with pgvector and design a RAG schema
  • How to insert chunks and embeddings from Python
  • How to combine SQL filters, joins and vector similarity in one query
  • How to add an HNSW index and keep data in sync with transactions

Prerequisites

  • Basic SQL; Docker (or a PostgreSQL server where you can install extensions)
  • Vector Store Options (pgvector basics)

Step 1: Start PostgreSQL with pgvector

The easiest way is the official pgvector Docker image:

docker run -d --name ragdb -e POSTGRES_PASSWORD=devpassword -p 5432:5432 pgvector/pgvector:pg17

Managed PostgreSQL services on all major clouds also support pgvector; enable it with CREATE EXTENSION vector. Use a strong password and do not expose the port publicly outside local development.

pip install "psycopg[binary]" pgvector sentence-transformers anthropic python-dotenv
.env
DATABASE_URL=postgresql://postgres:devpassword@localhost:5432/postgres
ANTHROPIC_API_KEY=your-key

Step 2: The schema

Keep documents and chunks in separate tables. Documents hold metadata used for filtering and access control; chunks hold text and embeddings.

schema.sql
CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS documents (
    id          bigserial PRIMARY KEY,
    source      text UNIQUE NOT NULL,
    title       text,
    department  text,
    updated_at  date,
    content_hash text
);

CREATE TABLE IF NOT EXISTS chunks (
    id          bigserial PRIMARY KEY,
    document_id bigint NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
    chunk_index int NOT NULL,
    content     text NOT NULL,
    embedding   vector(384) NOT NULL,
    UNIQUE (document_id, chunk_index)
);

CREATE INDEX IF NOT EXISTS chunks_embedding_hnsw ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX IF NOT EXISTS documents_department ON documents (department);

ON DELETE CASCADE means deleting a document removes its chunks automatically, which keeps re-indexing simple.

Step 3: Index documents

pg_rag.py
import hashlib
import os
from datetime import date
from pathlib import Path

import psycopg
from dotenv import load_dotenv
from pgvector.psycopg import register_vector
from rag_helpers import ask, embed            # 384-dimension local embeddings, Claude answers

load_dotenv()
conn = psycopg.connect(os.environ["DATABASE_URL"])
conn.execute("CREATE EXTENSION IF NOT EXISTS vector")
register_vector(conn)
conn.execute(Path("schema.sql").read_text())
conn.commit()

def chunk(text: str, size: int = 900) -> list[str]:
    parts, current = [], ""
    for p in [p.strip() for p in text.split("\n\n") if p.strip()]:
        if current and len(current) + len(p) > size:
            parts.append(current)
            current = ""
        current = f"{current}\n\n{p}" if current else p
    return parts + ([current] if current else [])

def index_file(path: Path, department: str) -> None:
    text = path.read_text(encoding="utf-8")
    digest = hashlib.sha256(text.encode()).hexdigest()
    with conn.transaction():                       # all or nothing for this document
        row = conn.execute("SELECT id, content_hash FROM documents WHERE source = %s",
                           (path.as_posix(),)).fetchone()
        if row and row[1] == digest:
            return                                 # unchanged
        if row:
            conn.execute("DELETE FROM documents WHERE id = %s", (row[0],))   # cascades to chunks
        doc_id = conn.execute(
            "INSERT INTO documents (source, title, department, updated_at, content_hash) "
            "VALUES (%s, %s, %s, %s, %s) RETURNING id",
            (path.as_posix(), path.stem, department, date.today(), digest)).fetchone()[0]
        pieces = chunk(text)
        with conn.cursor() as cur:
            cur.executemany(
                "INSERT INTO chunks (document_id, chunk_index, content, embedding) VALUES (%s, %s, %s, %s)",
                [(doc_id, i, c, v) for i, (c, v) in enumerate(zip(pieces, embed(pieces)))])
    print(f"indexed {path} ({len(pieces)} chunks)")

Step 4: Retrieve with SQL filters and vector similarity

The <=> operator is cosine distance; 1 - distance is cosine similarity. SQL filters and joins work exactly as usual:

def retrieve(question: str, k: int = 4, department: str | None = None) -> list[tuple]:
    q = embed(question, query=True)[0]
    sql = """
        SELECT d.source, c.chunk_index, c.content, 1 - (c.embedding <=> %(q)s) AS similarity
        FROM chunks c JOIN documents d ON d.id = c.document_id
        WHERE (%(dept)s::text IS NULL OR d.department = %(dept)s)
        ORDER BY c.embedding <=> %(q)s
        LIMIT %(k)s"""
    return conn.execute(sql, {"q": q, "dept": department, "k": k}).fetchall()

def answer(question: str, department: str | None = None) -> str:
    rows = retrieve(question, department=department)
    sources = "\n\n".join(f'<source id="{n}" file="{src}">\n{content}\n</source>'
                          for n, (src, _, content, _) in enumerate(rows, start=1))
    return ask(f"<sources>\n{sources}\n</sources>\n\nAnswer only from the sources, citing ids like [1]. "
               f"If they do not contain the answer, say so.\n\nQuestion: {question}")

if __name__ == "__main__":
    for p in Path("docs").glob("*.txt"):
        index_file(p, department="hr" if "leave" in p.name else "general")
    print(answer("How many sick days do employees get?", department="hr"))
indexed docs/leave-policy.txt (2 chunks)
indexed docs/remote-work.txt (1 chunks)
indexed docs/expenses.txt (1 chunks)
Employees get 10 days of sick leave per year [1].

Performance tips

  • HNSW index: created above. Tune search breadth per session with SET hnsw.ef_search = 100; (higher is more accurate, slower).
  • Filtered queries: with selective filters, approximate search can return fewer rows than requested. Recent pgvector versions support iterative index scans (SET hnsw.iterative_scan = relaxed_order;) that keep scanning until enough rows match; check your version's documentation.
  • Smaller vectors: the halfvec type stores 16-bit floats, halving storage.
  • Keyword search: PostgreSQL full-text search (tsvector) can provide the keyword half of hybrid search in the same database.

Common errors and troubleshooting

  • type "vector" does not exist: run CREATE EXTENSION vector (requires the extension to be installed on the server).
  • expected 384 dimensions, not 1536: the column dimension must match the embedding model; create a new column or table for a new model.
  • Can't adapt type numpy.ndarray: call register_vector(conn) after connecting.
  • Slow queries: check that the HNSW index exists and that the query orders by the same operator the index was built for (vector_cosine_ops with <=>).

Key takeaways

  • pgvector turns PostgreSQL into a capable vector store with SQL filters, joins and transactions.
  • Separate documents and chunks; use cascading deletes and content hashes for clean re-indexing.
  • Order by <=> with an HNSW index built on vector_cosine_ops.
  • Use row-level security and roles for access control in the same database (RBAC, ABAC and Row-Level Security).

Frequently asked questions

How many vectors can pgvector handle?

Millions comfortably on a well-sized server with HNSW. At hundreds of millions, consider partitioning, quantisation or a dedicated vector database.

Can I use OpenAI embeddings instead?

Yes. Change the column to vector(1536) for text-embedding-3-small and swap the embed function.

Practice exercises

  1. Add a tsvector column and implement hybrid search with reciprocal rank fusion in SQL or Python.
  2. Add an allowed_groups text[] column and filter with && (array overlap).

Related tutorials

  • Vector Index Types
  • LangChain with PostgreSQL pgvector
  • LlamaIndex with PostgreSQL pgvector