Engineering teams deploying retrieval-augmented generation (RAG) over internal documents often hit a frustrating failure mode: the AI assistant answers broad conceptual questions fluently, yet misses exact lookups such as contract ID HD-2026-0842, decree 123/2020/ND-CP, or unaccented Vietnamese queries like "chinh sach nghi phep" typed on mobile.
The fault sits in the retrieval layer rather than the language model. Pure dense vector search compresses text into floating-point arrays that blur exact identifiers, while a standalone vector database forces teams to replicate permissions, tenant flags, and metadata from their primary store. For dependable knowledge search inside enterprise systems, teams need lexical matching, accent normalization, and semantic retrieval unified inside one transactional database.
Why vector-only retrieval and separate vector DBs break in production
Multilingual embedding models excel at semantic matching, linking phrases like "travel expense reimbursement" with "business trip advance settlement". That continuous representation becomes a liability when corporate corpora rely on part SKUs, error codes, internal acronyms (PO, GRN, KPI), or mixed Vietnamese-English terms. Cosine similarity often ranks prose with similar structure above the passage holding the exact requested code.
Running an external vector database (such as Pinecone, Qdrant, or Milvus) for hundreds of thousands to several million chunks also adds operational drag. Whenever a policy is revoked, reassigned across departments, or updated in PostgreSQL, background pipelines must push changes to the external index. Queue lag or partial failures leave deleted or restricted records visible in search until re-indexing catches up.
| Architecture dimension | Standalone vector DB + replication pipeline | PostgreSQL + pgvector + Full-Text Search |
|---|
| Transactional consistency (ACID) | Eventual consistency; permission lag possible | Document text, ACLs, and vectors commit in one transaction |
Metadata filtering (tenant_id, expiry) | Requires copying filter attributes and extra indexes | Native SQL WHERE, JOIN, and Row-Level Security |
| Exact SKU, decree, and acronym recall | Weak on dense vectors alone; needs extra lexical index | Direct combination of GIN (tsvector) and pgvector (HNSW) |
| Operational & backup footprint | Two monitoring stacks, two backup jobs, extra network hops | Single PostgreSQL cluster, unified backups and observability |
| Best-fit scale envelope | Tens of millions to billions of vectors, multi-region sharding | |
Vietnamese diacritics, BM25-style ranking, and pgvector in PostgreSQL
For Vietnamese and multilingual corpora, diacritics create a second major breakpoint. Users often drop tone marks in quick searches ("bao cao tai chinh" instead of "báo cáo tài chính"), and input methods introduce tone-placement or Unicode normalization variants ("hòa" vs "hoà"). PostgreSQL's built-in simple dictionary leaves diacritics intact, while the english stemmer distorts Vietnamese words.
A reliable fix normalizes ingested text to Unicode NFC and adds a PostgreSQL configuration backed by the unaccent extension. Indexing only stripped text, however, creates homograph collisions: removing tones from "ma" matches "má", "mả", "mã", "mạ", and "mà" alike. Production lexical search should therefore maintain two GIN-indexed tsvector tiers:
- Exact-accent tier (higher weight): Built from NFC-normalized text so properly accented queries prioritize exact Vietnamese compounds and technical terms.
- Unaccented tier (fallback weight): Built via an
IMMUTABLE SQL wrapper around unaccent (or a stored generated column) to rescue accent-dropped queries.
For lexical scoring, distinguish PostgreSQL's native ts_rank_cd (cover-density ranking used in Supabase's official Hybrid Search guide) from full Okapi BM25 with inverse document frequency (IDF) and document-length normalization. When chunk lengths vary widely, teams can add a PostgreSQL BM25 extension such as pg_search (Tantivy), whereas uniform chunks work well with ts_rank_cd.
On the semantic side, pgvector provides HNSW and IVFFlat approximate nearest-neighbor indexes across L2 (<->), inner product (<#>), and cosine (<=>) operators. For unit-normalized vectors, negative inner product (<#>) skips redundant norm math, and halfvec (16-bit float) cuts HNSW RAM footprint roughly in half while keeping strong recall. Starting in pgvector 0.8.0, iterative index scans (hnsw.iterative_scan) continue traversing the graph when selective WHERE filters discard most neighbors, preventing sparse results under narrow tenant or department filters.
Adding raw lexical and semantic scores directly fails because cosine similarity sits within [0, 1], while BM25 or ts_rank_cd scores are unbounded. A single passage repeating a rare token can overwhelm semantic relevance.
As documented in Supabase's Hybrid Search guide for pgvector, Reciprocal Rank Fusion (RRF) avoids score-scaling heuristics by merging ordinal ranks from each list:
rrf_score = weight_fts / (k + rank_fts) + weight_semantic / (k + rank_semantic)
A smoothing constant k (typically 50 or 60) dampens sharp drops at the top, while the weights balance lexical vs semantic signals. Fetching top_k * 2 rows from the GIN and HNSW branches and joining via FULL OUTER JOIN on document_id promotes items appearing in both lists.
Follow this four-step checklist when shipping to production:
- 01Prepend structural headers to chunks: Include document title, section path, and document ID at the top of each chunk so lexical tokens and embeddings preserve source context.
- 02Pair dual `GIN` (`tsvector` + `unaccent`) with `HNSW` (`halfvec`): Enable
hnsw.iterative_scan = relaxed_order on pgvector 0.8+ so strict tenant and effective-date filters do not starve candidates. - 03Keep RRF fast and rerank selectively: Pull the top 30 to 50 RRF candidates in tens of milliseconds, and optionally run a lightweight multilingual cross-encoder reranker only when top-5 precision is critical.
- 04Track `Recall@10` on a real query suite: Curate 50 to 100 real queries mixing natural questions, unaccented Vietnamese, SKUs, and acronyms before and after tuning weights or changing embedding models.
Scope, caveats, and honest limitations
This guide synthesizes Supabase's official Hybrid Search with pgvector documentation, the pgvector repository specification, and ToanKhonTech's engineering practice in enterprise knowledge retrieval. It is architectural guidance rather than a fixed latency or accuracy benchmark across every dataset and embedding model.
Teams should account for three practical boundaries. First, HNSW indexes perform best when index pages fit in RAM (shared_buffers and OS page cache); beyond tens of millions of vectors with heavy concurrent QPS, a horizontally sharded vector engine scales more easily. Second, simple plus unaccent splits on whitespace rather than Vietnamese compound-word boundaries, so long legal texts may benefit from domain tokenization or pg_trgm trigram fallbacks. Third, stripping accents introduces homograph noise on 1-to-2-word queries, making weighted accented matching and strict SQL access controls essential before passing chunks to an LLM.