What you need
- A PostgreSQL database with the pgvector extension. If you don’t have one, the Docker file below is enough to try. The code needs pgvector 0.8 or newer because of the filtering.
- Python 3.11 or newer and an API key for embeddings and answers. Use a key that belongs to this project only, so you can see what it costs.
- A folder of documents. Start with 20–50 documents you know well, so you can judge the answers.
PostgreSQL is our choice for new projects, and jajob uses PostgreSQL with pgvector for its vectors. One database for both ordinary data and vectors means one backup, one access model and one place to delete.
1. The database
Docker Compose with the official pgvector image. The port is only open on the machine itself. The password comes from a .env file and never sits in the code.
services:
db:
image: pgvector/pgvector:pg17
restart: unless-stopped
environment:
POSTGRES_USER: rag
POSTGRES_DB: rag
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
ports:
- "127.0.0.1:5432:5432"
volumes:
- pgdata:/var/lib/postgresql/data
volumes:
pgdata:
If you install PostgreSQL through a control panel, check pg_hba.conf afterwards. aaPanel, for example, sets trust as the login method, so anyone who gets a shell on the server becomes superuser.
2. Tables and index
Two tables: documents with source, fingerprint and the groups allowed to see the document, and chunks with the text, page number and embedding. Delete a document and its chunks and embeddings disappear automatically. That matters when someone asks to be erased.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE IF NOT EXISTS documents (
id bigserial PRIMARY KEY,
source text NOT NULL UNIQUE, -- file path or URL
sha256 text NOT NULL, -- changed file = re-index
acl text[] NOT NULL DEFAULT '{}', -- groups allowed to see the document
indexed_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE IF NOT EXISTS chunks (
id bigserial PRIMARY KEY,
document_id bigint NOT NULL REFERENCES documents(id) ON DELETE CASCADE,
page int, -- page number for citations
body text NOT NULL,
embedding vector(1536) NOT NULL -- text-embedding-3-small = 1536 dimensions
);
CREATE INDEX IF NOT EXISTS chunks_embedding_hnsw
ON chunks USING hnsw (embedding vector_cosine_ops);
CREATE INDEX IF NOT EXISTS documents_acl_gin
ON documents USING gin (acl);
The HNSW index with vector_cosine_ops keeps search fast, even at hundreds of thousands of chunks. pgvector can index vector up to 2,000 dimensions. If your embedding model has more dimensions, or you want to halve the space, use the halfvec type, which can be indexed up to 4,000 dimensions.
3. Indexing and answering in Python
rag.py below does four things. chunk() groups whole sentences into chunks of about 1,200 characters so a thought is not cut in half. index_file() skips unchanged files and replaces changed files completely in one transaction. search() finds the six nearest chunks the user’s groups may see. ask() lets the model answer from exactly those and returns the sources the answer actually cites.
# pip install "psycopg[binary]" pgvector openai pypdf numpy
import hashlib
import os
import re
from pathlib import Path
import numpy as np
import psycopg
from openai import OpenAI
from pgvector.psycopg import register_vector
from pypdf import PdfReader
EMBED_MODEL = "text-embedding-3-small" # 1536 dimensions, $0.02 per 1M tokens
ANSWER_MODEL = "gpt-6-luna" # the cheapest model that does the job
MIN_SIMILARITY = 0.30 # below this: say "I don't know"
ai = OpenAI() # reads OPENAI_API_KEY from the environment
db = psycopg.connect(os.environ["DATABASE_URL"], autocommit=True)
db.execute(Path("schema.sql").read_text()) # tables and index (see the SQL above)
register_vector(db)
def pages(path: Path):
"""(page number, text) for a PDF; the whole file as page 1 for .md/.txt."""
if path.suffix.lower() == ".pdf":
for n, page in enumerate(PdfReader(path).pages, start=1):
yield n, page.extract_text() or ""
else:
yield 1, path.read_text(encoding="utf-8")
def chunk(text: str, size: int = 1200) -> list[str]:
"""Group whole sentences into chunks of about 1,200 characters (~300 tokens)."""
units = []
for s in re.split(r"(?<=[.!?])\s+|\n\s*\n", text):
s = " ".join(s.split())
units += [s[i:i + size] for i in range(0, len(s), size)] # very long "sentences" are cut hard
parts, buf = [], []
for u in units:
if buf and sum(len(x) + 1 for x in buf) + len(u) > size:
parts.append(" ".join(buf))
buf = buf[-1:] if len(buf[-1]) < size // 3 else [] # overlap: a short last sentence carries over
buf.append(u)
if buf:
parts.append(" ".join(buf))
return parts
def embed(texts: list[str]) -> list[np.ndarray]:
res = ai.embeddings.create(model=EMBED_MODEL, input=texts)
return [np.array(d.embedding, dtype=np.float32) for d in res.data]
def index_file(path: Path, acl: list[str]) -> int:
"""Index one file. Unchanged files are skipped; changed files are replaced completely."""
sha = hashlib.sha256(path.read_bytes()).hexdigest()
row = db.execute("SELECT sha256 FROM documents WHERE source = %s", (str(path),)).fetchone()
if row and row[0] == sha:
return 0
rows = [(n, body) for n, text in pages(path) for body in chunk(text)]
vecs = []
for i in range(0, len(rows), 100): # 100 chunks per API call
vecs += embed([body for _, body in rows[i:i + 100]])
with db.transaction(): # all or nothing: no half-indexed documents
db.execute("DELETE FROM documents WHERE source = %s", (str(path),)) # old chunks go with it
doc_id = db.execute(
"INSERT INTO documents (source, sha256, acl) VALUES (%s, %s, %s) RETURNING id",
(str(path), sha, acl),
).fetchone()[0]
for (n, body), vec in zip(rows, vecs):
db.execute(
"INSERT INTO chunks (document_id, page, body, embedding) VALUES (%s, %s, %s, %s)",
(doc_id, n, body, vec),
)
return len(rows)
def search(question: str, groups: list[str], k: int = 6):
"""The k most similar chunks that the user's groups may see."""
db.execute("SET hnsw.iterative_scan = relaxed_order") # pgvector 0.8+: filtering without empty results
q = embed([question])[0]
return db.execute(
"""
SELECT d.source, c.page, c.body, 1 - (c.embedding <=> %s) AS similarity
FROM chunks c JOIN documents d ON d.id = c.document_id
WHERE d.acl && %s::text[]
ORDER BY c.embedding <=> %s
LIMIT %s
""",
(q, groups, q, k),
).fetchall()
def generate(instructions: str, prompt: str) -> str:
return ai.responses.create(model=ANSWER_MODEL, instructions=instructions, input=prompt).output_text
def ask(question: str, groups: list[str]) -> dict:
hits = [h for h in search(question, groups) if h[3] >= MIN_SIMILARITY]
if not hits:
return {"answer": "I can't find that in the documents you have access to.", "sources": []}
context = "\n\n".join(f"[{i}] ({src}, page {page})\n{body}" for i, (src, page, body, _) in enumerate(hits, 1))
answer = generate(
"Answer only from the numbered context. Cite every claim as [n]. "
"If the context does not contain the answer, say so. Answer in the language of the question.",
f"Context:\n{context}\n\nQuestion: {question}",
)
used = sorted({int(n) for n in re.findall(r"\[(\d+)\]", answer) if 0 < int(n) <= len(hits)})
return {"answer": answer, "sources": [{"n": n, "source": hits[n - 1][0], "page": hits[n - 1][1],
"text": hits[n - 1][2]} for n in used]}
if __name__ == "__main__":
for f in Path("documents").rglob("*"):
if f.suffix.lower() in {".pdf", ".md", ".txt"}:
print(f, index_file(f, acl=["all"]))
print(ask("What is the notice period for a salaried employee?", groups=["all"]))
Run it with DATABASE_URL and OPENAI_API_KEY set in the environment. The first run creates the tables, indexes the documents folder and asks a sample question. We ran the code against PostgreSQL 17 with pgvector 0.8 using a local test embedding instead of the API, so the test cost nothing. It is the same trick we use in jajob, where embeddings and vector store are swappable modules and tests run on a simple cosine calculation.
Four details that matter
The filter belongs in the search. Group access is checked in the SQL (d.acl && %s) before the model sees anything. But pgvector filters after the index scan. With default settings and a filter matching only 10 % of chunks, you get about four hits on average. That is why the code turns on iterative scans, available from pgvector 0.8.
“I don’t know” is a valid answer. Below a similarity of 0.30 the code does not answer. Tune that number on your own test questions. In our multilingual knowledge base we let the system stay silent when the score is too low, rather than guess.
Instructions in English, answers in the user’s language. We always write prompts and instructions in English, while the answer comes back in the language of the question. Models follow English instructions most precisely.
Several languages need one extra step. If your documents are in one language and the questions in another, have a model write a few likely questions per document in each language at indexing time, and index them with the text. For us that lifted similarity from 0.048 to 0.84 for the same question, at one model call per document.
Next steps
The recipe is deliberately simple. For production you still need an import from where the documents live (SharePoint, Google Drive, Odoo) so permissions follow automatically. You also need keyword search next to vector search – PostgreSQL has tsvector built in – and a log of questions and answers. In jajob we combine exactly keyword search, vector search and a reranker. Before anything goes live, build the test from Quality and testing. Running costs are on the cost page.
Sources
- pgvector on GitHub — HNSW,
vector_cosine_ops, 2,000/4,000 dimensions, iterative scans from 0.8.0, checked 19.11.2026 - OpenAI – API pricing — text-embedding-3-small $0.02 and gpt-6-luna $0.10 / $0.50 per million tokens, checked 19.11.2026
Questions about the recipe
Can we use a model other than OpenAI?
Yes. Swap out embed() and generate(). Remember that the table’s vector(1536) must match the embedding model’s dimensions, and that all documents must be re-indexed when you change embedding model.
How big should chunks be?
We start at about 1,200 characters, roughly 300 tokens. Smaller chunks give more precise hits but less context. Test with your own questions.
What about Word and Excel files?
Convert them to text first, for example with python-docx or by saving as PDF. Spreadsheets rarely suit RAG; numbers belong in a database the model can query directly.
Can the model run on our own server?
Yes, embeddings and answers can come from a local model. Model and hardware choices are on lokal-ai.best-choice.dk.
Fixed price, no commitment
Get a fixed price for AI on your own data
Tell us briefly what you use today and what you want to achieve. A person answers by e-mail with a proposal and a fixed price before any work starts.
- A fixed price before we start
- An answer by e-mail, no calls
- Your details are used only to answer you