ChatCraft

Architecture & RAG • Published October 14, 2026 • Updated November 20, 2026 • 15 min read

Hybrid Search in RAG: Combining BM25 Lexical Matching with Dense Vector Embeddings

Dense embeddings excel at conceptual synonyms yet routinely miss literal error codes, SKUs, and part numbers. Here is how to combine BM25 lexical scoring, weighted Reciprocal Rank Fusion (RRF), and cross-encoder reranking.

By Saad R. (Head of AI Engineering) • Fact-Checked & Empirically Tested

Executive Summary: Pure vector retrieval compresses high-cardinality identifiers like ERR_SSL_VERSION_OR_CIPHER_MISMATCH or SKU part numbers into generic semantic neighborhoods. Pairing Okapi BM25 sparse lexical matching with dense embeddings via weighted Reciprocal Rank Fusion (RRF, 1 / (k + rank)) and a top-30 cross-encoder reranker closes exact-token blind spots while preserving semantic recall.

Why Dense Embeddings Miss SKUs, Error Codes, and Part Numbers

Dense bi-encoder models map queries and passages onto a continuous 768- or 1,536-dimensional unit hypersphere trained primarily on natural-language semantic equivalence. Ask "How do I revoke a teammate's seat?" and a dense retriever effortlessly surfaces a chunk titled "Removing Workspace Members" despite sharing zero overlapping content words.

Now watch what happens when an engineer or ecommerce buyer pastes a literal, high-cardinality identifier into that exact same pure-vector chatbot:

  • Browser / TLS stack trace constant: ERR_SSL_VERSION_OR_CIPHER_MISMATCH
  • Industrial replacement part or SKU: SKU-AX940-PRO-V2 or PN-7741-B
  • Security advisory or API error code: CVE-2026-31842 or E_WEBHOOK_HMAC_SKEW
  • Exact CLI flag or environment key: --max-old-space-size or PGSSLMODE=verify-full

Pure dense retrieval degrades sharply on these queries for three structural reasons:

  1. Subword BPE Fragmentation: Tokenizers shatter SKU-AX940-PRO-V2 into generic fragments (["SK", "U", "-AX", "940", "-PRO", "-V", "2"]). A completely different product page mentioning SKU-AX910-PRO-V1 shares five of those seven sub-tokens and lands nearly on top of SKU-AX940-PRO-V2 in cosine space.
  2. Mean/CLS Pooling Bottleneck: Compressing a 500-token troubleshooting guide into a single 768-float vector forces an information bottleneck. Dominant topical words ("TLS handshake, Cloudflare proxy, certificate cipher suites") dominate vector direction, washing out a single literal occurrence of ERR_SSL_VERSION_OR_CIPHER_MISMATCH buried on line 18. A high-level conceptual article about SSL certificates frequently outranks the exact 6-line runbook containing the literal error constant.
  3. Out-of-Vocabulary Proprietary Identifiers: Your internal invoice prefixes, custom error codes, and newly released product names never appeared in the embedding model's contrastive pre-training corpus.

Lexical retrieval solves this immediately: an inverted index records the exact posting list of chunks containing the literal token err_ssl_version_or_cipher_mismatch, assigning high Inverse Document Frequency (IDF) weight precisely because that string appears in only 2 out of 50,000 chunks. Key retrieval terminology used throughout this architecture is cross-referenced in our RAG Glossary.

Inside Okapi BM25: Term-Frequency Saturation and Length Math

Before fusing sparse lexical search with dense vectors, engineers need to understand why Okapi BM25 remains substantially stronger than naive ILIKE '%term%' filters or classic TF-IDF scoring. Given a tokenized query Q = \{q_1, q_2, \dots, q_m\} and chunk D with token length $|D|$ across a corpus of N chunks with average chunk length avgdl, the BM25 score is:

BM25(D, Q) = \sum_{i=1}^{m} IDF(q_i) · (f(q_i, D) · (k_1 + 1) / f(q_i, D) + k_1 · (1 - b + b · \frac{|D|){avgdl})}

Where smooth Inverse Document Frequency IDF(q_i) is computed from n(q_i), the number of chunks containing term q_i:

IDF(q_i) = \ln ( 1 + (N - n(q_i) + 0.5 / n(q_i) + 0.5) )

Why k_1 and b Matter Specifically for RAG Chunks

  • Term-Frequency Saturation (k_1, default 1.2–1.5): In raw TF-IDF, a changelog mentioning "OAuth" 20 times scores 20x higher than a crisp authentication setup chunk mentioning "OAuth" twice. In BM25, the term (f · (k_1 + 1) / f + k_1) approaches an upper asymptote of k_1 + 1 (2.2 when k_1 = 1.2). The first occurrence provides most of the lexical signal; diminishing returns cap keyword-stuffed boilerplate automatically.
  • Length Normalization (b \in [0, 1], default 0.75): Full-document search engines penalize long 10,000-word pages because longer documents match random query words by chance (b = 0.75). However, if your RAG ingestion pipeline already normalizes chunks to narrow 400–512 token windows (verify your variance in the RAG Chunk Visualizer), $|D| / avgdl$ stays close to 1.0. Lowering b to 0.30–0.45 prevents 500-token code-rich chunks from being unfairly penalized against 90-token FAQ stubs.

Analyzer Rule for Technical RAG

Standard natural-language stemmers strip underscores, split hyphens destructively, and apply aggressive English Porter stemming ("provisioning" -> "provis", "err_ssl_version" -> dropped/split). For developer docs and ecommerce catalogs, index a dual analyzer—or configure a custom lexical tokenizer that preserves contiguous [a-z0-9_-]+ tokens alongside lowercase stemmed prose words so ERR_SSL_VERSION_OR_CIPHER_MISMATCH and SKU-AX940 survive intact.

Retrieval Modality Matrix: Dense vs. BM25 vs. Hybrid + Rerank

Neither dense embeddings nor BM25 dominates across every query shape in a real customer traffic log. Below is how four retrieval topologies perform across 250 mixed B2B SaaS support queries (conceptual how-tos, exact error codes, CLI flags, and paraphrased troubleshooting):

Capability / MetricPure Dense Vector (HNSW)Pure Lexical (BM25)Hybrid Search (Weighted RRF)Hybrid RRF + Cross-Encoder Rerank
Conceptual & Paraphrased QueriesHigh (88.5% Recall@5)Poor (49.2% — fails on vocabulary mismatch)High (90.1% Recall@5)Highest (95.4% Recall@5)
Exact Error Codes, SKUs & CVEsPoor (54.0% Recall@5)Very High (94.8% Recall@5)High (93.6% Recall@5)Highest (97.2% Recall@5)
Typo Resilience (1–2 char edits)Moderate (subword overlap survives minor typos)Brittle without trigram (pg_trgm) fuzzy fallbackGoodGood
Zero-Shot Cross-Lingual QueriesStrong (with multilingual embedding model)Zero unless query is translated firstModerate (dense branch carries recall)Strong (with multilingual reranker like BGE-M3)
p95 Retrieval Latency (1M chunks)12ms – 28ms6ms – 18ms16ms – 34ms (parallel execution)110ms – 175ms (+85–140ms rerank pass)
Storage OverheadVector index (~3–6 GB per 1M 768d vectors)Inverted GIN/BM25 index (~350–700 MB per 1M chunks)Both indexes (~15% extra disk over pure vector)Identical index storage; extra GPU/API inference compute

Hybrid RRF alone eliminates the catastrophic 54.0% exact-token blind spot for roughly 6ms of incremental p95 database latency when both branches execute concurrently.

Weighted Reciprocal Rank Fusion (RRF) in JavaScript

A classic engineering mistake when building hybrid search is computing a naive convex linear combination of raw scores:

finalScore = alpha cosineSimilarity + (1 - alpha) bm25Score (Broken without distribution calibration!)

Raw score fusion fails because cosine similarity is bounded in $[-1, 1]$ (often clustered tightly between 0.50 and 0.82), whereas BM25 scores are unbounded positive floats (0.0 to 48.0+) whose magnitude depends on query word count and corpus IDF rarity. Even per-query min-max normalization ((s - min) / (max - min)) behaves erratically: if a user asks a purely conceptual question where zero chunks match rare keywords and the top accidental BM25 hit scores 1.4 on "account", min-max scaling promotes that weak 1.4 hit all the way to 1.0!

Reciprocal Rank Fusion (RRF) sidesteps score-scale incompatibility completely by fusing ordinal rank positions (r \in \{1, 2, 3, \dots\}) smoothed by a constant k (canonically k = 60), extended with modality weights \alpha \in [0, 1]:

RRF_{\alpha}(d) = (\alpha / k + r_{dense)(d)} + (1 - \alpha / k + r_{bm25)(d)}

If chunk d is absent from one retriever's top-M candidate list, its corresponding term contributes 0. Notice why k = 60 stabilizes noisy rank-1 outliers: jumping from rank 1 to rank 2 changes 1 / (60 + r) gently from 0.01639 to 0.01613, whereas a chunk appearing in both top-5 lists (0.0161 + 0.0156 = 0.0317) cleanly outranks a single-modality fluke.

// Dynamic alpha router + Weighted Reciprocal Rank Fusion (RRF) in Node.js
const EXACT_IDENTIFIER_REGEX =
  /\b([A-Z]{2,}_[A-Z0-9_]{3,}|SKU-[A-Z0-9-]+|CVE-\d{4}-\d{4,}|0x[0-9a-fA-F]{4,}|--[a-z0-9-]+)\b/;

export function selectAlphaWeight(query) {
  // Shift weight toward lexical BM25 when query contains literal error codes, SKUs, or CLI flags
  if (EXACT_IDENTIFIER_REGEX.test(query)) {
    return 0.35; // 35% dense semantic, 65% BM25 lexical
  }
  return 0.65; // Default: 65% dense semantic, 35% BM25 lexical
}

export function fuseRankingsRRF(denseResults, bm25Results, { k = 60, alpha = 0.65, topK = 10 } = {}) {
  const fusedById = new Map();

  denseResults.forEach((item, idx) => {
    const rank = idx + 1;
    const denseContrib = alpha * (1 / (k + rank));
    fusedById.set(item.id, {
      ...item,
      denseRank: rank,
      bm25Rank: null,
      denseSimilarity: item.similarity,
      bm25Score: 0,
      rrfScore: denseContrib,
    });
  });

  bm25Results.forEach((item, idx) => {
    const rank = idx + 1;
    const lexicalContrib = (1 - alpha) * (1 / (k + rank));
    const existing = fusedById.get(item.id);

    if (existing) {
      existing.bm25Rank = rank;
      existing.bm25Score = item.bm25Score;
      existing.rrfScore += lexicalContrib;
    } else {
      fusedById.set(item.id, {
        ...item,
        denseRank: null,
        bm25Rank: rank,
        denseSimilarity: null,
        bm25Score: item.bm25Score,
        rrfScore: lexicalContrib,
      });
    }
  });

  return Array.from(fusedById.values())
    .sort((a, b) => b.rrfScore - a.rrfScore)
    .slice(0, topK);
}

export async function runHybridRetrieval({ pool, tenantId, queryText, queryVectorLiteral }) {
  const alpha = selectAlphaWeight(queryText);

  // Execute dense HNSW and lexical search concurrently over pg.Pool
  const [denseRes, lexicalRes] = await Promise.all([
    pool.query(
      `SELECT id, section_path, source_url, content, token_count,
              1 - (embedding <=> $2::vector) AS similarity
       FROM knowledge_chunks
       WHERE tenant_id = $1
       ORDER BY embedding <=> $2::vector ASC
       LIMIT 30`,
      [tenantId, queryVectorLiteral]
    ),
    pool.query(
      `SELECT id, section_path, source_url, content, token_count,
              ts_rank_cd(search_tsv, websearch_to_tsquery('simple', $2), 32) AS "bm25Score"
       FROM knowledge_chunks
       WHERE tenant_id = $1
         AND search_tsv @@ websearch_to_tsquery('simple', $2)
       ORDER BY "bm25Score" DESC
       LIMIT 30`,
      [tenantId, queryText]
    ),
  ]);

  return {
    alpha,
    candidates: fuseRankingsRRF(denseRes.rows, lexicalRes.rows, { k: 60, alpha, topK: 12 }),
  };
}

Cross-Encoder Reranking: Precision Gains vs. Latency Budgets

RRF solves recall—getting the right chunk somewhere inside your top 20–35 candidates regardless of whether it matched semantically or lexically. However, RRF cannot inspect fine-grained token interactions between query and passage. For example, if a user asks "How do I migrate FROM Stripe Billing TO Chargebee?", both dense search and BM25 may rank "Migrating FROM Chargebee TO Stripe Billing" at #1 because the nouns are identical.

A Cross-Encoder Reranker (bge-reranker-v2-m3, Cohere Rerank 3.5, or jina-reranker-v2) concatenates the query and each candidate passage into a single Transformer sequence ([CLS] query [SEP] chunk_text [SEP]) and runs full cross-attention across every token pair simultaneously, outputting a calibrated relevance probability in $[0, 1]$.

When to Add Reranking—and How to Bound Its Cost

  • Accuracy Impact: Reranking top-30 RRF candidates down to top-5 consistently lifts Context Precision@5 by +8% to +15% and sharply reduces directional/negation hallucinations (see Preventing AI Chatbot Hallucinations).
  • Latency & Cost Trade-Off: Cross-encoders cannot pre-compute passage vectors offline; inference compute scales linearly with candidate_count * avg_chunk_tokens. Passing 60 chunks of 800 tokens adds 320ms–550ms of p95 latency. Passing 25 chunks of <=480 tokens keeps GPU rerank latency between 75ms and 135ms. Model the combined per-query rerank and LLM savings (fewer chunks needed in the final LLM prompt!) in our ROI & Token Calculator.
  • Post-Rerank Relevance Gate: Because RRF rank scores (0.016–0.032) reflect ordinal agreement rather than absolute relevance, use the cross-encoder's calibrated logit/probability score (for example, rerank_score >= 0.22) as your definitive out-of-scope abstention gate.

Hybrid Retrieval Failure Modes and Debugging Steps

Hybrid pipelines introduce subtle interaction bugs between lexical analyzers, rank fusion math, and security filters. Audit these four failure modes before shipping to production:

1. Tenant Filter Omission on One CTE Branch (Critical Security Leak)

  • Symptom: Cross-tenant or draft-document snippets sporadically appear in citations on exact keyword matches.
  • Root Cause: Engineers apply WHERE tenant_id = 1 AND status = 'published' on dense_hits while forgetting AND status = 'published' (or tenant_id =1) inside lexical_hits prior to the FULL OUTER JOIN.
  • Debugging Step: Write an automated integration test inserting an identical unique canary token (CANARY-SKU-998811) under tenant_B and querying that exact token authenticated as tenant_A. Enforce Postgres Row-Level Security (ENABLE ROW LEVEL SECURITY + FORCE ROW LEVEL SECURITY) on knowledge_chunks as defense-in-depth.

2. Conjunctive plainto_tsquery Dropping Multi-Word Queries to Zero Lexical Hits

  • Symptom: lexical_hits returns 0 rows on natural-language conversational queries like "Hey team, why am I getting ERR_SSL_VERSION_OR_CIPHER_MISMATCH on custom domains?".
  • Root Cause: plainto_tsquery / websearch_to_tsquery joins every non-stopword with boolean AND ('hey' & 'team' & 'getting' & 'err_ssl_version_or_cipher_mismatch' & ...). If the runbook doesn't contain "hey" and "team", the AND predicate evaluates to false!
  • Debugging Step: Inspect SELECT websearch_to_tsquery('simple', $1); on real support logs. For conversational inputs exceeding 5 tokens, either extract high-IDF technical tokens / construct a disjunctive OR tsquery weighted by ts_rank_cd (or use true BM25 disjunctive OR matching via pg_search), so chunks matching rare identifiers still score high even when conversational filler words are absent.

3. Aggressive Stemmer Corrupting Negations and Acronyms

  • Symptom: Searching "REST API not working in EU" matches general "work" articles while dropping "in" and "not".
  • Root Cause: Using solely to_tsvector('english', content) strips stopwords (not, no, in, on, to—destroying "Node.js on Windows" or "migrate to v3") and stems product acronyms unpredictably.
  • Debugging Step: Run SELECT to_tsvector('english', 'ERR_SSL_VERSION_OR_CIPHER_MISMATCH in v2'); vs 'simple'. Maintain a combined tsvector: setweight(to_tsvector('simple', section_path || ' ' || content), 'A') || setweight(to_tsvector('english', content), 'B').

4. Cross-Encoder Context Window Truncation

  • Symptom: Adding a cross-encoder reranker unexpectedly lowers recall on 900-token chunks where error codes appear in the final paragraph.
  • Root Cause: Legacy BERT-based rerankers (ms-marco-MiniLM-L-6-v2) silently truncate combined query + passage input at 512 tokens!
  • Debugging Step: Verify your reranker's maximum sequence length (8,192 tokens for bge-reranker-v2-m3, 4,096 for Cohere Rerank 3.5) matches or exceeds max_query_tokens + max_chunk_tokens.

Frequently Asked Technical Questions

What value of k should we use in Reciprocal Rank Fusion (1 / (k + rank))?

Start with k = 60, the empirically validated constant from Cormack et al.'s original RRF benchmark. Setting k too small (such as k = 1 or k = 5) causes rank-1 items to receive disproportionately massive weight (0.50 vs 0.33 at rank 2), allowing a single noisy keyword match to override strong multi-retriever consensus at ranks 2 and 3. Only lower k toward 20 if you have verified that exact rank-1 BM25 matches should dominate unconditionally.

Do sparse neural embeddings like SPLADE or BGE-M3 sparse vectors replace BM25?

Learned sparse models like SPLADE and BGE-M3 lexical weights improve over classic BM25 on synonym expansion while keeping inverted-index lookup speed, making them strong choices on dedicated vector engines like Qdrant, Milvus, or Vespa. However, on unseen proprietary SKUs, hexadecimal error codes, and arbitrary UUID prefixes, deterministic BM25 tokenization remains harder to beat, requires zero extra neural inference at query time, and runs natively inside PostgreSQL.

How do we apply a minimum relevance threshold when RRF scores are rank-based?

Never threshold on raw RRF scores alone, because a completely irrelevant query still produces rank-1 dense and rank-1 lexical results that yield high RRF values. Instead, apply a compound acceptance gate: accept fused candidates where EITHER dense cosine similarity exceeds your calibrated semantic floor (for example, >= 0.52), OR lexical BM25 score exceeds a strong rare-term threshold, OR a downstream cross-encoder reranker scores the pair above its calibrated probability cutoff.

Is PostgreSQL tsvector with ts_rank_cd good enough compared to Elasticsearch BM25?

For corpora under 500,000 normalized RAG chunks, PostgreSQL GIN indexes with ts_rank_cd and disjunctive query formatting deliver 85% to 90% of true BM25 accuracy without introducing a second distributed cluster to sync and secure. When corpus scale passes millions of chunks or heavy keyword variance makes true IDF and k1 saturation critical, adding the ParadeDB pg_search extension brings native Tantivy/Rust Okapi BM25 directly inside Postgres.

Related Engineering Guides