SXF / AI FIELD GUIDE · RAG INFRASTRUCTURE · ENTERPRISE SEARCH
Vector Databases for RAG:
How They Work, When You Need One & How to Choose
An evidence-led guide to pgvector, Qdrant, Weaviate, Pinecone and Milvus: vector search, hybrid retrieval, indexes, ACL filtering and total cost. Includes an original reproducible experiment, an interactive decision matrix and free evaluation resources.
What is the best vector database for RAG?
It depends on the retrieval workload. Start with exact and SQL-first search if that meets your requirements. Evaluate pgvector when vectors belong alongside PostgreSQL data; consider specialized Qdrant, Weaviate and Milvus deployments for search-specific capabilities and control, and managed systems such as Pinecone when hosted operations fit your needs. The decision should be based on verified relevance, filtered recall, latency, privacy, updates and full operating cost—not a vendor ranking.
REFERENCE GUIDE
What is a vector database for RAG?
A vector database for RAG stores embeddings and their document identifiers, supports similarity retrieval and often stores the metadata required for policy filters. In retrieval-augmented generation, a user query is converted into a compatible embedding, relevant allowed chunks are retrieved and the language model uses this evidence when producing an answer. The database does not itself verify whether the generated answer is factual.
Think of an engineering manual: a question like “Why are requests slowing after we hit our quota?” might retrieve a chunk titled “API rate-limit saturation.” Semantic vectors help when words differ. A separate lexical signal can be much stronger for exact terms such as ERR_API_QUOTA_17. This is why real systems should benchmark exact, lexical, semantic and hybrid retrieval rather than assuming vectors solve every problem.
| Component | Role in the retrieval pipeline | Risk without it |
|---|---|---|
| Embedding model | Maps queries and chunks to a consistent vector space | Incompatible versions or poor semantic matches |
| Vector index | Finds approximate or exact neighbors | Slow retrieval or unmeasured recall loss |
| Metadata/ACL filter | Restricts candidate documents by tenant, permissions and revision | Wrong or unauthorized evidence |
| Optional lexical search | Matches exact identifiers and domain vocabulary | Missed product names, versions and error codes |
| Reranking and citation | Reorders candidates and preserves evidence references | Confident answers without supporting sources |
Buy a retrieval capability that returns relevant, authorized, fresh evidence within your latency and cost budget. You do not automatically need a standalone vector database service.
REFERENCE GUIDE
Vector database vs SQL database: when is PostgreSQL enough?
The phrase vector database vs traditional database is misleading if it suggests that SQL cannot search vectors. The open-source pgvector extension adds vector types and exact or approximate nearest-neighbor searching inside PostgreSQL. PostgreSQL also provides full-text search, joins, transactions and row-level security. Test what the existing stack can do before adding a new service.
| Architecture | Typical reason to evaluate it | Important limitation |
|---|---|---|
| PostgreSQL full-text | Exact identifiers, operational record lookup and lexical-heavy corpora | May fail semantic paraphrases |
| PostgreSQL + pgvector | Vectors belong near transactional records, SQL filters and application permissions | Filtered ANN recall, DB load and index maintenance need testing |
| Dedicated vector engine | Specialized retrieval modes, separate scaling and index tuning | More systems, synchronization and operations |
| Managed vector search | Hosted search operations are preferable to owning a fleet | Billing, regional availability and export trade-offs |
| Exact in-process search | Small datasets and controlled experiments | Limited durability, sharing and scaling |
REFERENCE GUIDE
Vector store vs vector database: definitions are not guarantees
Vector store is a broad term for a persistence and retrieval component. Vector database generally indicates searchable vectors with database-like operations. Vendor naming is not a specification: ask for persistence guarantees, index consistency, deletion semantics, tenancy, backup/restore, migration, metrics and service limits.
A hosted “vector store” can be operationally more complete than a small self-managed “vector database.” Conversely, an attractive vector API is not a guarantee that your compliance, ACL and disaster recovery constraints are satisfied. Require evidence for the deployed version and plan, not a generic feature checklist.
REFERENCE GUIDE
An end-to-end RAG reference architecture: from document to verified answer
- Ingest: extract documents, capture source revision, owners, retention policy and stable identifiers.
- Chunk: preserve headings, citations, adjacent context and canonical chunk IDs; tune chunking on real queries.
- Embed: pin the embedding model, dimensions, normalization and distance metric. Store a model version with each chunk.
- Index: insert vectors with text, tenant/ACL metadata, timestamps and deletion information.
- Authorize: derive the allowed document scope from trusted application identity before executing retrieval.
- Retrieve: run dense and, where useful, lexical queries over allowed material. Fuse and optionally rerank a deep enough candidate set.
- Generate and cite: supply only authorized evidence; require abstention when relevant support is unavailable.
- Evaluate: measure retrieval recall, relevance, citation correctness, update visibility and answer faithfulness separately.
Choosing RAG itself versus fine-tuning or long context is covered in RAG vs Fine-Tuning vs Long Context. Choosing the embedding model is covered in Best Embedding Models for RAG. This guide addresses the missing retrieval infrastructure layer.
REFERENCE GUIDE
How vector search works: cosine distance, HNSW and IVFFlat
Vectors are compared using a metric such as cosine distance, Euclidean distance or inner product. Those metrics are not interchangeable without considering vector normalization and the training objective. Exact search evaluates the requested eligible candidates and provides an algorithmic reference. Approximate nearest-neighbor (ANN) methods accelerate search by changing the work performed, possibly sacrificing some recall.
| Method | How it works | What you must measure |
|---|---|---|
| Exact / flat search | Compares query against all eligible candidates | Runtime as the filtered candidate count grows |
| HNSW | Navigates a hierarchical approximate neighbor graph | Recall@k vs latency, graph memory and build time |
| IVFFlat | Searches selected clusters or partitions | Recall vs probes, training and distribution shifts |
| Quantized indexing | Uses compressed numerical representations | Space saving vs approximation error and reranking |
| Exact filtered query | Applies authoritative scope and exact ranking | Strong correctness baseline for tenant and ACL cases |
The foundational HNSW research is Malkov and Yashunin. pgvector documents exact defaults and separately configurable HNSW/IVFFlat indexes. Selective predicates can influence filtered ANN results: benchmark within the authorized candidate set instead of treating global top-k as guaranteed filtered top-k.
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE rag_chunks (
chunk_id BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
tenant_id TEXT NOT NULL,
source_id TEXT NOT NULL,
content TEXT NOT NULL,
embedding vector(3) NOT NULL
);
CREATE INDEX rag_chunks_tenant ON rag_chunks(tenant_id);
CREATE INDEX rag_chunks_ann ON rag_chunks
USING hnsw (embedding vector_cosine_ops);
-- :tenant_id must come from authenticated application context.
SELECT chunk_id, source_id
FROM rag_chunks
WHERE tenant_id = :tenant_id
ORDER BY embedding <=> '[0.6,0.2,0.7]'
LIMIT 5;This SQL is illustrative, not a turnkey access-control implementation. A tenant predicate is not a substitute for independent authorization enforcement or appropriately configured PostgreSQL row-level security.
REFERENCE GUIDE
Hybrid search for RAG: combine semantic retrieval, BM25 and RRF
Hybrid search combines vector-based semantic candidates with lexical or sparse matches. Error codes, part numbers and version identifiers often benefit from keyword search, whereas paraphrased questions benefit from a strong embedding model. Qdrant, Weaviate, Pinecone and Milvus publish different hybrid-search interfaces; those differences must be evaluated with the same labeled queries.
| Query type | Failure with semantic-only retrieval | Approach worth testing |
|---|---|---|
| API error code | Exact literal may not rank high | BM25 or sparse match plus dense candidate fusion |
| Natural-language paraphrase | Exact words differ from the relevant document | Dense semantic retrieval |
| Invoice number | Similar invoice from another tenant | Authorized deterministic SQL lookup |
| Product version and region | Outdated documentation is semantically similar | Pre-retrieval version/region filter |
| Multimodal screenshot | Text index may not represent the screenshot | Evaluated image/text representations |
Reciprocal Rank Fusion (RRF) merges rankings by summing rank-based contributions; one common equation is RRF(d) = Σ 1/(k + rank(d)). The constant, candidate depth and product defaults vary. Never directly add raw BM25 scores to cosine similarity scores without normalization: their scales are different. Both retrieval branches must enforce the same authorization scope.
def rrf(rankings, constant=60):
scores = {}
for ranking in rankings:
for rank, document_id in enumerate(ranking, 1):
scores[document_id] = (
scores.get(document_id, 0) + 1/(constant + rank)
)
return sorted(scores, key=lambda d: (-scores[d], d))
# Both input rankings must already be ACL scoped.REFERENCE GUIDE
Filtering, tenancy and access control: why query order matters
One misleading retrieval design is global vector top-k followed by tenant post-filtering. The global top-k can contain only other-tenant candidates; dropping them afterwards may yield zero results even when several relevant authorized records exist. An appropriately scoped search, or a database's documented filtered ANN strategy, is needed. Vendor filtering implementations differ, so verify correctness and access controls empirically.
| Filter pattern | Risk | Test |
|---|---|---|
| Tenant/ACL scope before exact search | Correct reference, though the eligible set can still be large | Measure exact recall and p95 for largest tenant |
| Engine-supported filtered ANN | Recall may vary with selectivity and index parameters | Compare to scoped exact top-k oracle |
| Global top-k then post-filter | Can return fewer than k and miss eligible records | Detect starvation by tenant/query class |
| Frontend-only filtering | Unauthorized material can reach retrieval or the LLM | Must fail closed before data access |
| Delayed index deletion | Revoked data can remain retrievable | Track deletion freshness and policy proof |
Tenant metadata supplied by the language model is not an authority signal. Your application must bind identities, filter candidates before exposing text, and test deletions and changed permissions. PostgreSQL row-level security and vector-engine server-side filters each have distinct security semantics; neither removes the need for threat modeling.
ORIGINAL SXF RESEARCH
SXF original experiment: 240 synthetic vectors and 40 filtered queries
We constructed 240 two-dimensional synthetic vectors (120 Red, 120 Blue) and evaluated 40 generated query vectors at k=5 (20 per tenant). Red points are deliberately closer to the query angles; the experiment isolates whether filter placement loses eligible neighbors. Two strategies were compared against a tenant-scoped exact top-five ground truth.
| 20 queries per tenant | Recall@5 — pre-filter | Recall@5 — global top-5 then filter | Mean post-filter count |
|---|---|---|---|
| Red | 1.00 | 1.00 | 5 |
| Blue | 1.00 | 0.00 | 0 |
We executed this exact algorithm locally and verified these outcomes. The Blue query still has 120 eligible documents, but global top-five selects Red neighbors. Post-filtering then discards all five. This demonstrates candidate starvation, not a general property of every real vector engine or an estimate of the probability of failure.
No Qdrant, Milvus, Weaviate, Pinecone or pgvector service was tested. There were no real LLM embeddings, model calls, network operations, observed latency or vendor benchmarks. The intentionally adversarial synthetic data support only the stated filter-placement finding.
VENDOR-NEUTRAL SELECTION
pgvector vs Qdrant vs Weaviate vs Pinecone vs Milvus
This comparison summarizes documented features, not a ranking of measured speed. Pricing, availability, service configurations, index defaults and cloud regions vary. Always verify a vendor's current documentation and your plan before procurement.
| System | Documented architecture | Hybrid / filtering approach | Priority to benchmark |
|---|---|---|---|
| pgvector | PostgreSQL-integrated exact and ANN search; SQL joins and transaction tooling | Combine Postgres lexical search and vector rankings; evaluate filtered HNSW | Tenant-filter recall, DB resource contention and row-level security |
| Qdrant | Vector-focused collections, payload attributes and documented multitenancy patterns | Dense and sparse retrieval, hybrid prefetch/fusion | Sparse quality, tenant sharding, memory and ops |
| Weaviate | Search-centric collections with dense and BM25F capabilities | Hybrid BM25/vector retrieval with fusion controls | Schema, ingestion, hybrid quality and update latency |
| Pinecone | Managed index APIs and vector-oriented hosted operations | Dense/sparse and full-text patterns plus metadata filtering | Usage cost, portability, data residency and service limits |
| Milvus | Specialized search engine including multi-vector support | Dense/sparse multi-vector hybrid and filtered search | Cluster operations, performance isolation, indexes and recovery |
“Best” depends on your workload. Database selection cannot be established from a static list of vector counts or a single vendor-provided benchmark. Consider the number of filtered eligible candidates, query distribution, write/delete rate, concurrent traffic, operator experience, residency and true cost per accepted answer.
INTERACTIVE BUYER TOOL
Interactive SXF Vector Database Decision Matrix
Select the constraints of your retrieval workload. This tool builds an evaluation plan without pretending to measure vendor speed, assigning sponsored scores or choosing a universal winner.
This worksheet is rule-based, client-side and vendor-neutral. It does not access your records, assign hidden vendor scores or represent commercial sponsorship. Actual selection requires measured evidence.
REFERENCE GUIDE
How to benchmark vector databases fairly
A credible vector database evaluation requires the same embedding model, corpus, chunking, query labels, index objective and authorization scope for every engine. Different hardware/service tiers or cold/warm cache profiles are not directly comparable without explicit disclosure.
| Metric | What it measures | Common misleading shortcut |
|---|---|---|
| Exact filtered recall@k | Overlap with exact nearest neighbors inside the authorized candidate set | Comparing to global top-k ignoring ACL |
| Human relevance recall / nDCG / MRR | How well meaningful evidence is ranked | Calling ANN geometric recall “answer accuracy” |
| p50, p95, p99 latency | Tail behavior by tenant/filter and query type | Only measuring warm p50 |
| Sustained QPS at SLO | Throughput while maintaining latency and correctness limits | Comparing unlike CPUs, GPUs or managed tiers |
| Ingestion and revocation lag | Time until upserts and deletes become searchable or disappear | Ignoring changed permissions |
| Index build and restore | Time, space and cost to reconstruct data | Assuming index migration is free |
| Total cost per accepted result | Storage, replicas, reads, writes, embedding, generation and ops | Copying advertised cost per GB |
- Define representative tasks and relevance judgments before selecting a vendor.
- Freeze document IDs, embeddings, dimension, metric, indexing defaults and data revisions.
- Establish tenant-scoped exact ground truth and separately annotate human-relevant documents.
- Run lexical, semantic, selective-filter, multilingual, no-answer and exact identifier tests.
- Measure warm/cold cache, concurrent reads, writes, deletes, reindexing and recovery.
- Record configurations, failures, timeouts, distributions and costs instead of one headline score.
- Repeat the benchmark when changing embedding models or data distributions.
REFERENCE GUIDE
Vector database pricing, sizing and total cost
Raw vector payload is only the start of the capacity model. For one million vectors with 1,536 float32 dimensions, raw payload is 6.144 GB (decimal) before index structures, text, metadata, copies, replicas, cache, backup and memory allocator overhead. Compression can reduce payload while changing accuracy and index needs. Vendor pricing must be checked per service tier and usage shape.
Illustrative lower-bound estimate, not a quote for RAM, storage, HNSW or an actual provider.
| Cost component | What to include |
|---|---|
| Embedding | Initial and ongoing re-embedding requests |
| Storage | Raw vectors, graphs, metadata, snapshots and retention |
| Read and writes | Query usage, index updates and replication |
| Compute | Runtime, cache, indexing and shard operations |
| Retrieval quality | Rerankers, labeling, evaluation and test infrastructure |
| Operational risk | Restore drills, migration, vendor egress and on-call staff |
For model-level inference spend, use the SXF AI Model Cost Calculator. The important unit is a verified, authorized answer—not cost per vector alone.
REFERENCE GUIDE
Production operations: versioning, indexing, deletion, backups and observability
Maintain an explicit chain from source document → chunk ID → embedding version → vector ID. Without it, permission changes and embedding migrations are hard to reconcile. Treat deletions and ACL updates as first-class correctness events, not delayed maintenance.
| Operation | Evidence required before production |
|---|---|
| Ingestion | Stable IDs, retry handling, indexing lag, checksum/row count |
| Tenant isolation | Authorization from trusted identity, no cross-tenant results |
| Deletion/revocation | Measured disappearance time and negative queries |
| Model migration | Dual index or reproducible rebuild, version-aware rollback |
| Hybrid retrieval | Monitor dense and lexical legs, fusion input depth and failure |
| Recovery | Snapshot, restore, RPO/RTO and service failure drills |
| Residency/compliance | Regions, subprocessors, exports, encryption and retention |
| Reliability | p95/p99, dead-letter queues, cost per accepted query and runbook |
For the wider deployment envelope—including queues, state and release management—see How to Deploy AI Agents in Production. For when agent memory should be retained, reviewed and forgotten, see AI Agent Memory.
REFERENCE GUIDE
Four practical vector RAG architecture patterns
| Pattern | Useful when | Critical test |
|---|---|---|
| SQL-first RAG | Business records and permissions already live in PostgreSQL | RLS + filtered recall + shared DB resource effects |
| Managed search | Hosting operations are not core team capability | Cost/egress/region, metadata filters and export |
| Self-operated specialist engine | Search tuning or infrastructure control justifies a new service | Shard operations, memory, disaster recovery and upgrades |
| Multimodal/multi-vector | Images, audio or several representations are meaningful to users | Cross-modal relevance and access policy |
These are patterns, not a ranking. The right answer can also be no vector database when deterministic SQL or keyword retrieval solves user needs more reliably and cheaply.
REFERENCE GUIDE
Migrating vector databases without breaking retrieval
- Export document IDs, source versions, embeddings, metadata and ACL model—not vectors alone.
- Pin the existing embedding model, dimension, similarity function and chunking contract.
- Build the target index and replay in-flight updates and deletes.
- Shadow the same authorized queries through both systems and compare exact recall and human relevance.
- Validate tail latency, search cost, deletion and tenant isolation at expected load.
- Canary by cohort and keep a rollback route for outstanding index updates.
- Delete old replicas only after access and retention requirements are verified.
Exportability and the cost of leaving a managed system matter in long-lived enterprise deployments. Document the exit plan before signing a commercial agreement.
REFERENCE GUIDE
Ten common mistakes when choosing a vector database for RAG
- Buying a specialized database before measuring a PostgreSQL/exact baseline.
- Assuming semantic search outperforms literal retrieval for every query.
- Comparing providers with different embeddings, hardware or source documents.
- Applying tenant filtering after an unrestricted global top-k search.
- Trusting a model to determine its own document permissions.
- Changing embedding versions without rebuilding and validating the index.
- Confusing geometric ANN recall with user answer correctness.
- Ignoring update/deletion lag, stale chunks and source provenance.
- Reporting only p50 latencies from toy data with a warm cache.
- Calling vector storage price the entire retrieval system cost.
REFERENCE GUIDE
Vector database for RAG: frequently asked questions
What is a vector database for RAG?
A storage and retrieval system for embeddings, IDs and metadata, used to find evidence for generation. It does not guarantee accurate answers.
Do you always need a vector database for RAG?
No. Small corpora, exact lookups, SQL full-text search or an existing PostgreSQL deployment may satisfy requirements.
What is vector store vs vector database?
Vector store is a broad term for vector storage and retrieval. Vector database usually implies operational data management features, but the labels are not technical standards.
Is pgvector better than Pinecone?
There is no universal winner. pgvector integrates into PostgreSQL; Pinecone offers managed search. Test the same workload, permissions, latency, cost and operational constraints.
What is hybrid search?
Retrieval that combines lexical methods such as BM25 and semantic vector retrieval. Rank fusion can merge both result lists.
What is HNSW?
A graph-based approximate nearest-neighbor algorithm that trades additional indexing resources for faster approximate retrieval.
How do I test vector database recall?
Compute an exact nearest-neighbor ground truth inside the authorized filter, then compare approximate results using recall@k; also label real query relevance separately.
How much memory does a million 1536-dimensional vectors need?
Float32 vector payload alone is 6.144 billion bytes; index structures, metadata, replication and system overhead add more.
Can metadata filtering replace ACL controls?
No. Trusted identities must determine allowed scope before retrieval, and authorization must be enforced by the system rather than by model instructions.
REFERENCE GUIDE
Primary sources, experiment disclosure and editorial methodology
Capabilities in this guide are grounded in official documentation, Postgres and pgvector primary sources and published algorithmic research. We have not conducted comparative hosted vendor benchmarks; no latency, recall superiority, uptime or actual provider pricing is implied by the table. The original SXF demonstration tests only filtered retrieval order in synthetic exact dot-product search. Our evaluation worksheet is a template, not a dataset of measured provider outcomes.
The tools and companies are identified for technical comparison, not sponsored promotion. Service versions, capabilities, limits and costs should be rechecked before deployment. Experiment inputs, code and expected output are available for independent reproduction.