Skip to main content
Architecture7 min read

RAG on pgvector: Hybrid Search and Citations That Hold Up

The Assistant Core knowledge base: structure-aware chunks, Gemini Embedding 2 at 1,536 dimensions, hybrid search fused with RRF, and [n] citations. With measurements on Vietnamese question sets and why there is still no HNSW index.

RAGpgvectorHybrid SearchEmbeddingKnowledge Base
AC

Assistant Core Team

Engineering

RAG Pipeline with pgvector — Ingest and Query
RAG Pipeline with pgvector — Ingest and Query

When a business wants an AI assistant to answer from internal documents (policies, price lists, procedures), the answer is still RAG: find the right passages first, then let the model answer from them. This post describes the Assistant Core knowledge base as it runs: how documents are split, the embedding model, hybrid search, citations, the numbers measured on Vietnamese question sets, and what we deliberately have not built. Every choice below was measured on a fixed question set before it shipped.

Why RAG and not fine-tuning

Business documents change weekly, while fine-tuning is slow, expensive, and cannot say where an answer came from. RAG separates the two concerns: the document store can change at any time for the cost of an embedding call, and the model only has to read the passages it is given and cite them. For a customer-support assistant, pointing at the source matters as much as being right. See how customers use the knowledge base on the use cases page.

The pipeline today

The two paths meet only at Postgres and at the embedding model.

Write path (an owner adds documents)Read path (the model calls a tool)
Add a file, text, URL or website from the Admin Panel, the web app or Management MCPThe model calls the knowledge_base tool when a question needs your documents
Extract text: PDF, DOCX, PPTX, XLSX, ODT, EPUB, RTF, CSV, TXT, MD, JSON, HTML, XML; scanned PDFs are OCR'dThe question is embedded with the same model used at ingest
Split by structure, at most 2,000 characters, no overlap, heading path storedTake the 30 nearest chunks by vector and the 30 best by keywords
Embed with Gemini Embedding 2, 1,536 dimensions, 100 chunks per callFuse the two rankings with Reciprocal Rank Fusion
Write the document row and its chunks in one transaction; keep the original in S3 for re-indexingReturn up to 8 numbered passages with document › heading and page
Duplicate content (same MD5) is refused before anything is storedThe model answers and appends [n] after each sentence that uses a source

There is no separate worker: ingestion runs inside the request, and a 20-page website takes about a minute.

Structure-aware chunks, no overlap

The most common approach cuts at a fixed character count and overlaps a few hundred characters between neighbours. Simple, but it produces three familiar failures: a heading separated from the text under it, a table cut mid-row, and the overlap putting the same sentence into the top-k twice, taking the place of another passage.

The current splitter follows the Markdown structure of the extracted document:

  • A new chunk starts at a heading once the current one is half full, so a heading always stays with the text below it.
  • A paragraph is cut only when it alone exceeds the size, and then at a line, then a sentence, then a word.
  • Tables are cut between rows, and each piece repeats the header row.
  • Every chunk stores the heading path it sits under, for example Pricing › Pro plan.

The text that gets embedded is the document title, then the heading path, then the chunk; the stored text shown to the model is the chunk alone. This is the cheap version of the "contextual retrieval" idea Anthropic described: instead of asking an LLM to write context for every chunk, we use the context the document structure already provides. On docs-vi (vector only, 348 answerable questions), the title prefix raised recall@1 from 0.523 to 0.556 and MRR from 0.693 to 0.714 compared with putting the title on top of the text as an ordinary line.

Pick the embedding model by measurement, not reputation

We compared text-embedding-3-large with Gemini Embedding 2 on two Vietnamese corpora:

Corpustext-embedding-3-largeGemini Embedding 2
docs-vi (product documentation), recall@10.4510.503
Zalo legal (legal articles), recall@10.7450.882

The price is about 0.5 s more query latency (p95 around 1 s), acceptable because the model searches only when it needs to. The lesson for Vietnamese, and for any language that is not English: public embedding leaderboards lean English, so measure on your own language and documents. Vectors are stored at 1,536 dimensions, one size for the column and the API call. Changing the model means re-indexing everything from the S3 originals, one transaction per document, and while that runs search keeps working on keywords alone. That is the first benefit of hybrid search.

Hybrid search: vectors plus keywords, fused with RRF

Embeddings capture meaning but slip on things that must match exactly: error codes, endpoint names, SKUs, labels in the UI. So every query runs two branches. The keyword branch uses a generated tsvector column over the heading and the text with diacritics removed, so gia goi pro finds giá gói Pro, which is how Vietnamese users type in a hurry. The two rankings are merged with Reciprocal Rank Fusion (Cormack, Clarke and Büttcher, 2009) with k = 60:

-- A sketch of the idea, not the production query
WITH vec AS (
  SELECT id, row_number() OVER (ORDER BY embedding <=> $q) AS r
  FROM knowledge_chunks WHERE assistant_id = $a LIMIT 30
), kw AS (
  SELECT id, row_number() OVER (ORDER BY ts_rank(search_vector, q) DESC) AS r
  FROM knowledge_chunks, plainto_tsquery('simple', unaccent($text)) q
  WHERE assistant_id = $a AND search_vector @@ q LIMIT 30
)
SELECT id, SUM(1.0 / (60 + r)) AS score
FROM (SELECT * FROM vec UNION ALL SELECT * FROM kw) u
GROUP BY id ORDER BY score DESC LIMIT 8;

One small detail decides a lot: the keyword branch requires every word of the query (AND). With OR, common words matched nearly every chunk and recall@1 on docs-vi fell from 0.48 to 0.36. Hybrid retrieval is also where most enterprise search products have converged; the difference here is that it runs inside Postgres instead of adding a service.

No HNSW index yet, on purpose

pgvector offers HNSW and IVFFlat, and we use neither: a search computes the distance to every chunk of the assistant, found through the per-assistant index. For a few thousand chunks that takes milliseconds and gives exact recall. The problem with approximate indexes under a filter is well known: the index scans the whole table and only then filters by assistant, so a small assistant can get too few results back. We will revisit this when one assistant reaches about 100,000 chunks, using pgvector 0.8's iterative scans. The rule: do not add complexity before the numbers show you need it.

A tool, not prompt stuffing; [n] citations

The knowledge base is never pasted into the prompt. The model calls the tool when a question needs it, with actions to search, read a whole document, list documents, and search by name. A search returns numbered passages; on every surface except voice, the prompt asks the model to cite the passage number right after the sentence that uses it, as [2] or [2][5], and never to list sources itself. Citation numbers are unique across the whole conversation, so older answers keep their meaning after a new search. The web app and the chat widget render sources as chips with passage previews; messaging channels and scheduled tasks append the source list to the reply. Uploaded files are private by default: users see the file name and the cited passage but cannot open the file unless the owner turns on "Open cited files".

Measure before shipping

Every retrieval change runs against two fixed question sets:

  • docs-vi: the platform's own 55 Vietnamese documentation pages and 373 hand-written questions in five kinds: factual (189), how-to (70), exact term (64), multi-section (25) and unanswerable (25). About 11% are in English and 9% are typed without diacritics. Split 60/40 into dev and test; the test split runs only to accept a phase.
  • zalo-5k: 5,061 Vietnamese legal articles with 80 human-written questions, an independent cross-check.

The metrics are recall@k, MRR@10 and the characters of context put in front of the model; a change that drops recall@10 or MRR@10 by more than 0.01 against the baseline fails. A separate answer eval has a judge model grade correctness, groundedness, and whether the assistant says "not in the documents" when it should. No question is generated by an LLM, so the dataset does not drift between runs. The answering model can be any model in the multi-LLM architecture; retrieval does not change with it.

If you are building a knowledge base for your assistant

  • Keep clear headings and one topic per document; the splitter and the embedding prefix both rely on them.
  • Keep tables as tables. A price list pasted as prose loses the structure the splitter preserves.
  • Write 30 to 50 real customer questions, including a few the documents cannot answer, and test before opening the assistant to customers.
  • For websites, crawl the support pages instead of uploading PDFs exported from them; web pages are always linked in citations.

The full guides are in the Knowledge base documentation, preparing documents and uploading documents.

Ready to try Assistant Core?

Build an assistant from your documents and put it on Zalo, Messenger, and your website in minutes. Start free.

Create a free assistant