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.

Evergreen guide5 search systems40-query experimentDecision matrix + downloads
DIRECT ANSWER

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.

Practical components of a vector RAG retrieval system
ComponentRole in the retrieval pipelineRisk without it
Embedding modelMaps queries and chunks to a consistent vector spaceIncompatible versions or poor semantic matches
Vector indexFinds approximate or exact neighborsSlow retrieval or unmeasured recall loss
Metadata/ACL filterRestricts candidate documents by tenant, permissions and revisionWrong or unauthorized evidence
Optional lexical searchMatches exact identifiers and domain vocabularyMissed product names, versions and error codes
Reranking and citationReorders candidates and preserves evidence referencesConfident answers without supporting sources
The buying decision

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.

Vector database versus relational and lexical search
ArchitectureTypical reason to evaluate itImportant limitation
PostgreSQL full-textExact identifiers, operational record lookup and lexical-heavy corporaMay fail semantic paraphrases
PostgreSQL + pgvectorVectors belong near transactional records, SQL filters and application permissionsFiltered ANN recall, DB load and index maintenance need testing
Dedicated vector engineSpecialized retrieval modes, separate scaling and index tuningMore systems, synchronization and operations
Managed vector searchHosted search operations are preferable to owning a fleetBilling, regional availability and export trade-offs
Exact in-process searchSmall datasets and controlled experimentsLimited 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

SXF RAG reference architecture with documents and ACL, chunks and embeddings, vector and text index, authorization, hybrid retrieval, and answer generation
Original SXF architecture illustrates the ingestion and query pipelines and the policy boundary.
  1. Ingest: extract documents, capture source revision, owners, retention policy and stable identifiers.
  2. Chunk: preserve headings, citations, adjacent context and canonical chunk IDs; tune chunking on real queries.
  3. Embed: pin the embedding model, dimensions, normalization and distance metric. Store a model version with each chunk.
  4. Index: insert vectors with text, tenant/ACL metadata, timestamps and deletion information.
  5. Authorize: derive the allowed document scope from trusted application identity before executing retrieval.
  6. Retrieve: run dense and, where useful, lexical queries over allowed material. Fuse and optionally rerank a deep enough candidate set.
  7. Generate and cite: supply only authorized evidence; require abstention when relevant support is unavailable.
  8. 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.

Indexing methods and production trade-offs
MethodHow it worksWhat you must measure
Exact / flat searchCompares query against all eligible candidatesRuntime as the filtered candidate count grows
HNSWNavigates a hierarchical approximate neighbor graphRecall@k vs latency, graph memory and build time
IVFFlatSearches selected clusters or partitionsRecall vs probes, training and distribution shifts
Quantized indexingUses compressed numerical representationsSpace saving vs approximation error and reranking
Exact filtered queryApplies authoritative scope and exact rankingStrong 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.

REFERENCE SQL · POSTGRESQL + PGVECTOR
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;
Security clarification

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.

Hybrid search selection by query intent
Query typeFailure with semantic-only retrievalApproach worth testing
API error codeExact literal may not rank highBM25 or sparse match plus dense candidate fusion
Natural-language paraphraseExact words differ from the relevant documentDense semantic retrieval
Invoice numberSimilar invoice from another tenantAuthorized deterministic SQL lookup
Product version and regionOutdated documentation is semantically similarPre-retrieval version/region filter
Multimodal screenshotText index may not represent the screenshotEvaluated 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.

PYTHON · BASIC RECIPROCAL RANK FUSION
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.

Authorization and metadata filter correctness
Filter patternRiskTest
Tenant/ACL scope before exact searchCorrect reference, though the eligible set can still be largeMeasure exact recall and p95 for largest tenant
Engine-supported filtered ANNRecall may vary with selectivity and index parametersCompare to scoped exact top-k oracle
Global top-k then post-filterCan return fewer than k and miss eligible recordsDetect starvation by tenant/query class
Frontend-only filteringUnauthorized material can reach retrieval or the LLMMust fail closed before data access
Delayed index deletionRevoked data can remain retrievableTrack 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

SXF original offline filtering lab with synthetic red and blue tenant vectors, comparing prefiltered to global top-5 post-filtering
The figure represents executed deterministic exact-search results; no database vendor or ANN engine was benchmarked.

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.

SXF deterministic offline experimental results, 21 October 2026
20 queries per tenantRecall@5 — pre-filterRecall@5 — global top-5 then filterMean post-filter count
Red1.001.005
Blue1.000.000

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.

Limits of the evidence

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.

Five vector database architectures: official documentation-based qualitative comparison
SystemDocumented architectureHybrid / filtering approachPriority to benchmark
pgvectorPostgreSQL-integrated exact and ANN search; SQL joins and transaction toolingCombine Postgres lexical search and vector rankings; evaluate filtered HNSWTenant-filter recall, DB resource contention and row-level security
QdrantVector-focused collections, payload attributes and documented multitenancy patternsDense and sparse retrieval, hybrid prefetch/fusionSparse quality, tenant sharding, memory and ops
WeaviateSearch-centric collections with dense and BM25F capabilitiesHybrid BM25/vector retrieval with fusion controlsSchema, ingestion, hybrid quality and update latency
PineconeManaged index APIs and vector-oriented hosted operationsDense/sparse and full-text patterns plus metadata filteringUsage cost, portability, data residency and service limits
MilvusSpecialized search engine including multi-vector supportDense/sparse multi-vector hybrid and filtered searchCluster 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.

Evaluation path
Editorial integrity

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.

Practical vector-search evaluation scorecard
MetricWhat it measuresCommon misleading shortcut
Exact filtered recall@kOverlap with exact nearest neighbors inside the authorized candidate setComparing to global top-k ignoring ACL
Human relevance recall / nDCG / MRRHow well meaningful evidence is rankedCalling ANN geometric recall “answer accuracy”
p50, p95, p99 latencyTail behavior by tenant/filter and query typeOnly measuring warm p50
Sustained QPS at SLOThroughput while maintaining latency and correctness limitsComparing unlike CPUs, GPUs or managed tiers
Ingestion and revocation lagTime until upserts and deletes become searchable or disappearIgnoring changed permissions
Index build and restoreTime, space and cost to reconstruct dataAssuming index migration is free
Total cost per accepted resultStorage, replicas, reads, writes, embedding, generation and opsCopying advertised cost per GB
  1. Define representative tasks and relevance judgments before selecting a vendor.
  2. Freeze document IDs, embeddings, dimension, metric, indexing defaults and data revisions.
  3. Establish tenant-scoped exact ground truth and separately annotate human-relevant documents.
  4. Run lexical, semantic, selective-filter, multilingual, no-answer and exact identifier tests.
  5. Measure warm/cold cache, concurrent reads, writes, deletes, reindexing and recovery.
  6. Record configurations, failures, timeouts, distributions and costs instead of one headline score.
  7. 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.

Raw vector payload only—
Payload × copies—

Illustrative lower-bound estimate, not a quote for RAM, storage, HNSW or an actual provider.

Complete costs for production vector-based RAG
Cost componentWhat to include
EmbeddingInitial and ongoing re-embedding requests
StorageRaw vectors, graphs, metadata, snapshots and retention
Read and writesQuery usage, index updates and replication
ComputeRuntime, cache, indexing and shard operations
Retrieval qualityRerankers, labeling, evaluation and test infrastructure
Operational riskRestore 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.

Production operations checklist for vector RAG systems
OperationEvidence required before production
IngestionStable IDs, retry handling, indexing lag, checksum/row count
Tenant isolationAuthorization from trusted identity, no cross-tenant results
Deletion/revocationMeasured disappearance time and negative queries
Model migrationDual index or reproducible rebuild, version-aware rollback
Hybrid retrievalMonitor dense and lexical legs, fusion input depth and failure
RecoverySnapshot, restore, RPO/RTO and service failure drills
Residency/complianceRegions, subprocessors, exports, encryption and retention
Reliabilityp95/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

Four vendor-neutral RAG architecture patterns
PatternUseful whenCritical test
SQL-first RAGBusiness records and permissions already live in PostgreSQLRLS + filtered recall + shared DB resource effects
Managed searchHosting operations are not core team capabilityCost/egress/region, metadata filters and export
Self-operated specialist engineSearch tuning or infrastructure control justifies a new serviceShard operations, memory, disaster recovery and upgrades
Multimodal/multi-vectorImages, audio or several representations are meaningful to usersCross-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

  1. Export document IDs, source versions, embeddings, metadata and ACL model—not vectors alone.
  2. Pin the existing embedding model, dimension, similarity function and chunking contract.
  3. Build the target index and replay in-flight updates and deletes.
  4. Shadow the same authorized queries through both systems and compare exact recall and human relevance.
  5. Validate tail latency, search cost, deletion and tenant isolation at expected load.
  6. Canary by cohort and keep a rollback route for outstanding index updates.
  7. 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

  1. Buying a specialized database before measuring a PostgreSQL/exact baseline.
  2. Assuming semantic search outperforms literal retrieval for every query.
  3. Comparing providers with different embeddings, hardware or source documents.
  4. Applying tenant filtering after an unrestricted global top-k search.
  5. Trusting a model to determine its own document permissions.
  6. Changing embedding versions without rebuilding and validating the index.
  7. Confusing geometric ANN recall with user answer correctness.
  8. Ignoring update/deletion lag, stale chunks and source provenance.
  9. Reporting only p50 latencies from toy data with a warm cache.
  10. 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.

Source and editorial policy

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.