Loading…
Loading documentation...
Implement hybrid full-text and pgvector HNSW retrieval in PostgreSQL 17 with tenant isolation, halfvec memory savings, ef_search tuning, and citations.
Commands checked on 2026-11-23 with PostgreSQL 17, pgvector 0.8+, Node.js 24, pg 8.13+.
A multi-tenant Retrieval-Augmented Generation (RAG) knowledge database inside PostgreSQL 17 combining pgvector HNSW cosine similarity and PostgreSQL tsvector keyword ranking—strictly partitioned by tenant ID (environmentId) so customers can never retrieve another tenant's documents or research notes.
vector extension; see PostgreSQL for a web app or Cloud databases with vector and SQL.nomic-embed-text / bge-large or Ollama.Enable vector, store document metadata separately from chunks, index both semantic vectors (hnsw) and lexical search (GIN tsvector), and partition every customer memory row by environmentId:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE kb_documents (
id TEXT PRIMARY KEY,
scope TEXT NOT NULL, -- 'public_docs' | 'tenant_memory'
environment_id TEXT, -- NULL only for public_docs
title TEXT NOT NULL,
source_url TEXT NOT NULL,
checksum TEXT NOT NULL,
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE kb_chunks (
id TEXT PRIMARY KEY,
document_id TEXT NOT NULL REFERENCES kb_documents(id) ON DELETE CASCADE,
environment_id TEXT,
chunk_index INTEGER NOT NULL,
content TEXT NOT NULL,
tsv tsvector GENERATED ALWAYS AS (to_tsvector('english', content)) STORED,
embedding halfvec(1024),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX kb_chunks_tsv_idx ON kb_chunks USING GIN (tsv);
CREATE INDEX kb_chunks_env_idx ON kb_chunks (environment_id);
Notice halfvec(1024) halves RAM requirements compared to 32-bit vector(1024) while preserving nearly identical recall.
Temporarily raise maintenance_work_mem during index creation so Postgres builds the HNSW graph in RAM instead of spilling to disk:
SET maintenance_work_mem = '1GB';
SET max_parallel_maintenance_workers = 4;
CREATE INDEX kb_chunks_hnsw_idx
ON kb_chunks USING hnsw (embedding halfvec_cosine_ops)
WITH (m = 16, ef_construction = 64);
Always inject the server-verified environment_id inside the WHERE predicate before taking top-K neighbors—never filter tenant ownership in application memory after fetching global top-K vectors, or rare/filtered queries will silently return zero tenant matches or leak neighboring tenants:
BEGIN;
SET LOCAL hnsw.ef_search = 100;
WITH semantic AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY embedding <=> $1::halfvec) AS r
FROM kb_chunks
WHERE environment_id IS NULL OR environment_id = $2
LIMIT 30
),
lexical AS (
SELECT id, ROW_NUMBER() OVER (ORDER BY ts_rank_cd(tsv, plainto_tsquery('english', $3)) DESC) AS r
FROM kb_chunks
WHERE (environment_id IS NULL OR environment_id = $2)
AND tsv @@ plainto_tsquery('english', $3)
LIMIT 30
)
SELECT c.id, c.content, d.title, d.source_url,
COALESCE(1.0 / (60 + s.r), 0.0) + COALESCE(1.0 / (60 + l.r), 0.0) AS rrf_score
FROM kb_chunks c
JOIN kb_documents d ON d.id = c.document_id
LEFT JOIN semantic s ON s.id = c.id
LEFT JOIN lexical l ON l.id = c.id
WHERE s.id IS NOT NULL OR l.id IS NOT NULL
ORDER BY rrf_score DESC
LIMIT 8;
COMMIT;
Verify index usage with EXPLAIN (ANALYZE, BUFFERS) inside psql:
EXPLAIN (ANALYZE, BUFFERS)
SELECT id FROM kb_chunks
WHERE environment_id = 'ENV-DEMO'
ORDER BY embedding <=> array_fill(0.01::real, ARRAY[1024])::halfvec
LIMIT 5;
Confirm Postgres selects an Index Scan using kb_chunks_hnsw_idx (once rows accumulate) and sub-10ms lookup latency with clean tenant scoping.
environment_id. Default pgvector HNSW iteratively visits candidates, and very small tenants can exhaust hnsw.ef_search = 40 scanning other tenants' nodes first. Upgrade to pgvector 0.8+ (SET hnsw.iterative_scan = relaxed_order;), raise ef_search = 120, or pair vector search with GIN full-text fallback.different vector dimensions. Every chunk inserted must share the exact embedding model dimension; store the model ID + dimension alongside kb_documents so re-embedding upgrades never mix dimensions.tsvector) search with dense vector search via Reciprocal Rank Fusion (RRF) because exact CLI flags, systemd directives (ProtectSystem=strict), and error codes (ECONNREFUSED) match poorly on embeddings alone.<untrusted_external_data>) before feeding it to an LLM.hnsw.iterative_scan on multi-tenant pgvector 0.8+ databases so selective tenant filters stay accurate.Every Servers Are Up virtual machine and container includes an integrated HTML5 browser-based SSH, RDP, and VNC console in your dashboard, default-off inbound firewall rules with per-IP allow-lists, and full programmatic control via REST API v1 and Model Context Protocol (MCP). Explore our Virtual Datacenter Plans or reach out to Servers Are Up Support.