The Trap of Naive Dense Vector Retrieval
When engineering teams build their first Retrieval-Augmented Generation (RAG) prototype, the architecture usually looks deceptively simple: chunk text, pass chunks through an embedding model (like OpenAI text-embedding-3-small), store vectors in a database, and execute cosine similarity searches for incoming queries.
In demo environments, this works like magic. But the moment you deploy a naive vector-only RAG system into high-stakes production enterprise environments—such as medical record search, technical documentation, or real estate databases—the architecture begins to fail in predictable ways:
- The SKU / Identifier Failure: Dense vector embeddings represent semantic meaning, not exact characters. Searching for exact terms like
ERR_CONN_TIMEOUT_904or product codeSKU-8842-Xoften retrieves completely unrelated chunks that share a vague conceptual context. - Domain Terminology & Acronyms: Niche technical acronyms or medical terms often get averaged out in vector space, resulting in low precision.
- Lack of Structural Filtering: Dense vector indexes are notoriously difficult to filter efficiently by metadata (e.g., date ranges, tenant IDs, price thresholds) without sacrificing recall or hitting severe performance bottlenecks.
To achieve production-grade precision, top engineering studios rely on Hybrid Search: pairing the exact keyword precision of sparse Lexical Search (BM25) with the deep conceptual understanding of Dense Vector Search.
The Hybrid Architecture: BM25 Sparse Search + Dense Embeddings
Why pair ElasticSearch with pgvector in a Next.js App Router environment instead of relying on a single database?
| Search Vector | Primary Engine | Algorithmic Foundation | Strengths |
|---|---|---|---|
| Sparse (Lexical) | ElasticSearch 8.x | BM25 / TF-IDF | Instant exact matches, typo tolerance, synonyms, metadata filtering, aggregations. |
| Dense (Semantic) | PostgreSQL + pgvector | HNSW / Cosine Distance | Natural language intent, conceptual similarity, multilingual comprehension. |
By combining both systems, query retrieval operates across two parallel axes: ElasticSearch catches the precise terminology, proper nouns, and filter constraints, while pgvector catches semantic intent even when the user uses completely different phrasing.
Data Flow & Dual-Indexing Pipeline
In our architecture, document ingestion follows a dual-indexing strategy:
- Document Chunking: Input documents are split into overlapping semantic chunks (e.g., 512 tokens with a 64-token overlap).
- Embedding Generation: Chunks pass through the embedding model to produce a 1536-dimensional vector.
- Parallel Persistence: The raw text chunk and structured metadata are indexed into ElasticSearch (for BM25 indexing), while the vector embedding and relational metadata are saved to PostgreSQL via
pgvector.
Step 1: Database Schema & HNSW Indexing in PostgreSQL
In PostgreSQL, enable the extension and construct an optimized HNSW (Hierarchical Navigable Small World) index to keep vector retrieval sub-10ms:
CREATE EXTENSION IF NOT EXISTS vector;
CREATE TABLE document_chunks (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
document_id VARCHAR(255) NOT NULL,
chunk_index INT NOT NULL,
content TEXT NOT NULL,
metadata JSONB DEFAULT '{}'::jsonb,
embedding vector(1536),
created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
);
-- Create an HNSW index for ultra-fast cosine similarity search
CREATE INDEX idx_chunks_embedding_hnsw
ON document_chunks
USING hnsw (embedding vector_cosine_ops)
WITH (m = 16, ef_construction = 64);Step 2: Dual-Indexing Pipeline in Node.js / TypeScript
When storing a document, push text and metadata to ElasticSearch while simultaneously storing the vector representation in Postgres:
import { Client as ElasticClient } from '@elastic/elasticsearch';
import { pgPool } from '@/lib/db';
import { openai } from '@/lib/ai';
const esClient = new ElasticClient({ node: process.env.ELASTICSEARCH_URL! });
export async function indexDocumentChunk(id: string, docId: string, text: string, metadata: Record<string, any>) {
// 1. Generate dense vector embedding
const embeddingResponse = await openai.embeddings.create({
model: 'text-embedding-3-small',
input: text,
});
const embedding = embeddingResponse.data[0].embedding;
// 2. Dual-index concurrently via Promise.all
await Promise.all([
// Index into ElasticSearch for BM25 keyword matching
esClient.index({
index: 'rag_chunks',
id: id,
document: {
doc_id: docId,
content: text,
metadata,
created_at: new Date().toISOString(),
},
}),
// Index into PostgreSQL with pgvector
pgPool.query(
`INSERT INTO document_chunks (id, document_id, content, metadata, embedding)
VALUES ($1, $2, $3, $4, $5)`,
[id, docId, text, JSON.stringify(metadata), JSON.stringify(embedding)]
),
]);
}Step 3: Parallel Retrieval & Reciprocal Rank Fusion (RRF) in Next.js
When a query arrives in a Next.js Server Action, we query both engines in parallel. Because BM25 scores and Cosine Distance operate on completely different numeric scales, we cannot simply add their raw scores. Instead, we use Reciprocal Rank Fusion (RRF) to re-rank chunks based on their positional rank in each result set.
RRF Formula: RRF_Score(d) = Σ (1 / (k + rank_bm25(d))) + (1 / (k + rank_vector(d)))
Where k is a smoothing constant (typically 60).
interface RankedChunk {
id: string;
content: string;
score: number;
}
export async function hybridRetrieve(query: string, topK = 5): Promise<RankedChunk[]> {
// 1. Generate query embedding
const embeddingRes = await openai.embeddings.create({
model: 'text-embedding-3-small',
input: query,
});
const queryVector = JSON.stringify(embeddingRes.data[0].embedding);
// 2. Execute parallel search queries
const [esResults, pgResults] = await Promise.all([
// Sparse BM25 Query from ElasticSearch
esClient.search({
index: 'rag_chunks',
size: 20,
query: {
match: { content: query }
}
}),
// Dense Vector Cosine Query from pgvector
pgPool.query(
`SELECT id, content, (1 - (embedding <=> $1)) as similarity
FROM document_chunks
ORDER BY embedding <=> $1 ASC
LIMIT 20`,
[queryVector]
)
]);
// 3. Compute Reciprocal Rank Fusion (RRF)
const rankMap = new Map<string, { content: string; score: number }>();
const K = 60;
// Process ElasticSearch BM25 Ranks
esResults.hits.hits.forEach((hit: any, index: number) => {
const id = hit._id;
const rank = index + 1;
const rrfScore = 1 / (K + rank);
rankMap.set(id, { content: hit._source.content, score: rrfScore });
});
// Process pgvector Dense Ranks
pgResults.rows.forEach((row: any, index: number) => {
const id = row.id;
const rank = index + 1;
const rrfScore = 1 / (K + rank);
if (rankMap.has(id)) {
rankMap.get(id)!.score += rrfScore;
} else {
rankMap.set(id, { content: row.content, score: rrfScore });
}
});
// Sort by combined RRF score and take top K
return Array.from(rankMap.entries())
.map(([id, data]) => ({ id, content: data.content, score: data.score }))
.sort((a, b) => b.score - a.score)
.slice(0, topK);
}What Each Strategy Gets Right — and Wrong
The trade-offs are consistent enough across deployments to state plainly — but the only numbers that matter are the ones you measure on your own corpus. Build a small evaluation set first: 50–100 real queries with known-correct chunks, scored against each strategy before you commit the architecture.
| Retrieval strategy | Exact identifiers (SKUs, error codes) | Paraphrased intent | Typical failure mode |
|---|---|---|---|
| Dense vector only | Weak — identifiers average out in vector space | Strong | Confidently retrieves the right neighborhood, wrong fact |
| BM25 lexical only | Strong | Weak — vocabulary mismatch kills recall | Misses everything the user phrased differently |
| Hybrid with RRF | Strong | Strong | Pays for two engines and a fusion step — run them in parallel so latency is the slower engine, not the sum |
The reason RRF specifically: it fuses ranks, not scores, so BM25 relevance numbers and cosine distances never need to be normalized against each other — the step where most hand-rolled hybrid implementations quietly go wrong.
Production Best Practices for Next.js Deployment
- Server-Side Execution Only: Always execute retrieval inside Next.js Server Actions or Route Handlers (`app/api/rag/route.ts`). Never expose database connection strings or ElasticSearch endpoints to client bundles.
- Connection Pooling: Use connection poolers like
pg-gatewayor Supabase Transaction Pooler when deploying Next.js to serverless environments (Vercel / AWS Lambda) to prevent connection exhaustion. - Sub-100ms Query Latency: Running ElasticSearch and
pgvectorin parallel viaPromise.all()ensures overall retrieval latency is bottlenecked only by the slower of the two services (usually ~40–60ms), keeping total server response time well below 100ms.
Conclusion: Engineering Intelligence That Works
RAG is not just about connecting an LLM to a database—it's about retrieving the exact ground-truth context your model needs to answer accurately. By pairing ElasticSearch's proven BM25 keyword power with pgvector's semantic understanding, engineering teams eliminate hallucination vectors caused by missing context.
We have been building search and retrieval systems since long before anyone called them RAG — the same disciplines behind our search database work apply directly here. If you are designing a hybrid retrieval layer, we are happy to pressure-test the architecture with you.
Frequently Asked Questions
What is hybrid search in a RAG system?
Hybrid search runs two retrieval methods in parallel and merges their results: sparse lexical search with BM25 catches exact terms, proper nouns and filter constraints, while dense vector search catches semantic intent even when a user phrases things differently. Here, Elasticsearch handles the BM25 side, PostgreSQL with pgvector handles the embeddings, and Reciprocal Rank Fusion combines the two ranked lists.
Why does vector-only RAG fail on product codes and error messages?
Dense embeddings represent semantic meaning, not exact characters, so identifiers such as SKUs or error codes average out in vector space. A query for an exact code often retrieves chunks that merely share a vague conceptual context. Vector-only retrieval also struggles with niche acronyms and with efficient metadata filtering, which is why it is paired with lexical BM25 search.
How does Reciprocal Rank Fusion combine BM25 and vector search results?
RRF scores each chunk by its position in each result list rather than by raw scores, adding 1 divided by k plus its rank for every list it appears in, with k typically set to 60. Because it fuses ranks, BM25 relevance numbers and cosine distances never need normalizing against each other, which is where most hand-rolled hybrid implementations quietly go wrong.
Does running Elasticsearch and pgvector together slow down retrieval?
Not if both queries run in parallel. Running them concurrently with Promise.all means overall retrieval latency is set by the slower of the two services, usually around 40 to 60 milliseconds, rather than the sum of both. The real cost of hybrid retrieval is operating two engines and a fusion step, not doubled latency.
How do I know whether hybrid search is better for my data?
Measure it on your own corpus before committing to the architecture. Build a small evaluation set of 50 to 100 real queries with known-correct chunks, then score dense-only, BM25-only and hybrid retrieval against it. The general trade-offs are consistent across deployments, but the only numbers that matter are the ones you measure on your own documents.
