RAG

Hybrid search for RAG: BM25 + embeddings in TypeScript

In what are embeddings I ended with a promise: embeddings are great at meaning and bad at exact strings, so production search usually combines them with keyword search. That combination is hybrid search, and it is the most common first upgrade for a RAG system.

This post builds it in TypeScript: a 40-line BM25, a 10-line rank fusion, the embedding search you already have, and an optional reranker. Then it does something most hybrid search tutorials skip: it measures whether each piece helps. Spoiler: hybrid won, and the reranker did not.

Why one search is not enough#

Two failure modes, both real, both from the test set in this post:

  • Embeddings blur identifiers. Ask "what does E1042 mean" over docs that describe errors E1040, E1041, E1042, E1043 and E1044. The embedding search answers with E1040. To a model that captures meaning, those five lines say almost the same thing.
  • Keywords miss paraphrases. Ask "Where do I put API keys?" and the right line says "Secrets come from the vault; never commit .env files." Not one word in common, so keyword search finds nothing.

Each method fails where the other is strong. Hybrid search runs both and merges the results.

Questionone query inBM25 +embeddingstwo rankedlistsFuse with RRFone ranked listRerank(optional)measure first!
Two cheap searches, one merge. The reranker is an extra, not a requirement.

BM25: keyword search done properly#

BM25 is the ranking function behind Elasticsearch and Lucene. For each query word a document contains, it adds a score that is higher when the word is rare across your documents (inverse document frequency), grows with repeats but with diminishing returns (k1), and is corrected for document length (b). The usual defaults, which Elasticsearch also uses, are k1 = 1.2 and b = 0.75.

ts
// Words too common to tell documents apart.
const STOP = new Set(
  ("a an and are as at be by do does for from how i in is it my " +
    "of on or so the to what when where who why with you").split(" "),
);

/** Lowercase words and numbers, minus stopwords. */
export const tokenize = (s: string): string[] =>
  (s.toLowerCase().match(/[a-z0-9]+/g) ?? []).filter(
    (w) => !STOP.has(w),
  );

/** Build a BM25 keyword index. Returns a scoring function. */
export function bm25(docs: string[], k1 = 1.2, b = 0.75) {
  const toks = docs.map(tokenize);
  const avgLen = toks.reduce((s, t) => s + t.length, 0) / docs.length;
  const df = new Map<string, number>(); // docs containing the word
  for (const t of toks) {
    for (const w of new Set(t)) df.set(w, (df.get(w) ?? 0) + 1);
  }
  const idf = (w: string) => {
    const n = df.get(w) ?? 0; // rare words weigh more
    return Math.log((docs.length - n + 0.5) / (n + 0.5) + 1);
  };

  return (query: string): number[] =>
    toks.map((t) => {
      let score = 0;
      for (const w of new Set(tokenize(query))) {
        const tf = t.filter((x) => x === w).length;
        if (tf === 0) continue;
        const norm = 1 - b + (b * t.length) / avgLen;
        score += (idf(w) * tf * (k1 + 1)) / (tf + k1 * norm);
      }
      return score;
    });
}

The stopword list matters more than it looks. Without it, filler words like "my", "do" and "who" count as evidence, even though they say nothing about which document answers the question. Real search engines use language analyzers that do this (and stemming, so "deploys" matches "deploy"). This one is deliberately small.

Reciprocal Rank Fusion: merge rankings, not scores#

You cannot add a BM25 score (say 3.7) to a cosine similarity (say 0.42): they are on different scales. Reciprocal Rank Fusion (RRF), from a 2009 paper by Cormack, Clarke and Büttcher, sidesteps that by ignoring scores and using positions. Every document gets 1 / (k + rank) from each list it appears in:

ts
/** Indexes of `scores`, best first. Optionally drop non-matches. */
const ranking = (scores: number[], min = -Infinity) =>
  scores
    .map((s, i) => [s, i])
    .filter(([s]) => s > min)
    .sort((a, b) => b[0] - a[0])
    .map(([, i]) => i);

/** Reciprocal Rank Fusion: reward documents both lists rank high. */
export function rrf(rankings: number[][], k = 60): number[] {
  const score = new Map<number, number>();
  for (const list of rankings) {
    list.forEach((doc, rank) => {
      score.set(doc, (score.get(doc) ?? 0) + 1 / (k + rank + 1));
    });
  }
  return [...score].sort((a, b) => b[1] - a[1]).map(([doc]) => doc);
}

k = 60 is the value from the paper, and Elasticsearch's default too. A larger k flattens the curve so lower-ranked documents count more. The effect: a document that shows up in both lists beats one that tops a single list. The test for this function checks exactly that: a document that is second in both lists wins against two documents that are each first in one.

Run both searches, fuse, done. embed and cosine come from the embeddings post, unchanged.

ts
/** Keyword and meaning search, fused. Returns doc indexes. */
export async function hybridSearch(query: string, docs: Doc[]) {
  const keyword = bm25(docs.map((d) => d.text))(query);
  const [q] = await embed([query]);
  const meaning = docs.map((d) => cosine(q, d.vector));
  const byKeyword = ranking(keyword, 0); // only real matches
  const byMeaning = ranking(meaning);
  return {
    keyword: byKeyword,
    meaning: byMeaning,
    hybrid: rrf([byKeyword, byMeaning]),
  };
}

Look at ranking(keyword, 0). My first version did not have that 0, and it was a real bug: when no document contained any query word, every BM25 score was 0, and my "ranking" still listed all documents in their original order. That arbitrary order then voted in the fusion. Keyword search must contribute only documents that actually match.

Optional: a reranker#

A reranker (a cross-encoder) reads the question and a candidate together and scores how well that one document answers that one question. That is more precise than comparing two independently computed vectors, and also much slower, so you only rerank the top few results:

ts
const RERANKER = "Xenova/ms-marco-MiniLM-L-6-v2"; // a cross-encoder
const tok = await AutoTokenizer.from_pretrained(RERANKER);
const ce = await AutoModelForSequenceClassification.from_pretrained(
  RERANKER,
);

/** Score each (query, doc) pair together; slower, more precise. */
export async function rerank(query: string, texts: string[]) {
  const pairs = tok(texts.map(() => query), {
    text_pair: texts,
    padding: true,
    truncation: true,
  });
  const { logits } = await ce(pairs);
  return ranking(Array.from(logits.data as Float32Array));
}

Both models run locally with transformers.js (npm install @huggingface/transformers). No API key.

Does it help? I measured#

The test set: 18 short internal docs (handbook rules, error codes E1040 to E1044, config names like MAX_UPLOAD_MB and MAX_UPLOADS_PER_DAY) and 14 questions, a mix of paraphrases and exact terms. For each method, how often is the right document ranked first?

MethodRight answer first (of 14)
Keyword (BM25)10
Embeddings11
Hybrid (RRF)12
Hybrid + reranker (top 5)11

Where they differ:

QuestionBM25EmbeddingsHybrid
what does E1042 mean✓✗ (E1040)✓
E1043✓✗ (E1040)✓
Where do I put API keys?✗ (no match)✓✓
When does the pager duty switch?✗ (no match)✓✓
Who has to approve my changes?✗ (on-call)✓✗ (on-call)
How do I get my code live?✗✗✗

Three honest takeaways:

  1. Hybrid fixed what embeddings blur. Both error-code questions went from wrong to right, and the paraphrases embeddings handled stayed right.
  2. Fusion can also import keyword mistakes. "approve my changes" matched the on-call rule ("the rotation changes every Monday") on a single shared word, and that was enough to win the fusion. Weighting the lists differently, or a better analyzer, could fix it. So could more data, which is the real point: tune with your questions, not mine.
  3. The reranker was not a free win. This general-purpose cross-encoder (trained on web search) fixed "approve my changes" but broke two others, including E1042. Rerankers trained on your kind of text, or larger ones, may do much better, but you will only know by measuring.

Fourteen questions is a smoke test, not a benchmark. It is still more evidence than "hybrid is best practice". The same idea at a larger scale is an eval: keep 20 to 50 real questions with known answers, and rerun them whenever you change chunking, models or weights.

  • Your users search for identifiers: error codes, SKUs, function names, ticket numbers, config keys. Add it now.
  • Your docs are short and distinct: embeddings alone may be fine. Measure first.
  • You already use Postgres or Elasticsearch: both have keyword search built in, so hybrid is mostly a matter of running two queries and fusing them.

How I tested this#

Everything ran under Node 24 with @huggingface/transformers 4.3.1, using all-MiniLM-L6-v2 for embeddings and ms-marco-MiniLM-L-6-v2 for reranking. The tests check the tokenizer, that BM25 weighs rare words and short documents correctly and scores non-matches 0, that RRF favors documents found by both lists, and the exact numbers in the tables above.

Sources: Okapi BM25, Elasticsearch BM25 defaults, Elasticsearch RRF, Reciprocal Rank Fusion paper (Cormack, Clarke, Büttcher, 2009).

Frequently asked questions

What is hybrid search in RAG?

Hybrid search runs a keyword search (usually BM25) and a vector search over the same documents, then merges the two ranked lists into one. It catches both exact matches, like error codes and config names, and paraphrases that share no words with the answer.

What is BM25?

BM25 is the classic keyword ranking function used by search engines such as Elasticsearch and Lucene. It scores a document higher when it contains the query's words, especially rare ones, with diminishing returns for repeats and a correction for document length.

What is Reciprocal Rank Fusion?

A way to merge ranked lists without comparing their scores: each document gets 1 / (k + rank) from every list it appears in, and the totals decide the final order. k is usually 60. Documents that rank well in both lists rise to the top.

Do I need a reranker?

Maybe. A cross-encoder reranker reads the question and each candidate together, which can be more precise, but it is slower and not automatically better. In my small test, an off-the-shelf reranker lost one answer overall. Test it on your own questions before you ship it.

Why do embeddings miss exact terms?

Embeddings capture overall meaning, so near-identical strings such as error codes E1040 and E1042 end up with almost the same vector. Keyword search treats them as different words, which is exactly what you want for identifiers.