← All articles

RAG · August 16, 2026 · 4 min read

Hybrid search: combining BM25 and embeddings

Learn how to combine BM25 and vector embeddings using Reciprocal Rank Fusion to build a robust, production-grade hybrid search system on Podstack GPUs.

In the landscape of modern Information Retrieval (IR), we are often presented with a false dichotomy: use traditional keyword-based search (BM25) or modern vector-based semantic search (Embeddings).

While vector embeddings excel at capturing context and synonyms—understanding that "dog" and "canine" are related—they often struggle with "exact match" scenarios, such as product serial numbers, technical acronyms, or specific proper nouns. This is where Hybrid Search comes in. By combining the lexical precision of BM25 with the semantic depth of dense vectors, you can build search systems that are significantly more robust than either method alone.

The Architecture of Hybrid Search

Hybrid search typically follows a two-pronged workflow:

  1. Lexical Branch (BM25): The query is tokenized, and documents are scored based on term frequency and inverse document frequency. This handles exact keyword overlap.
  2. Dense Branch (Embeddings): The query is passed through a transformer model (like BGE or E5) to generate a vector. A vector database then performs a cosine similarity search.
  3. Fusion: The results from both lists are combined using an algorithm like Reciprocal Rank Fusion (RRF) to produce a final, re-ranked list of documents.

Implementing Hybrid Search with Python

To implement this effectively, you need a GPU to handle the embedding generation at scale. While you could run these on a CPU, latency will become a bottleneck as your document count grows.

Here is a practical implementation using the rank_bm25 library for the lexical side and a sentence-transformer for the embedding side.

import numpy as np
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
from sklearn.metrics.pairwise import cosine_similarity

# 1. Prepare your data
documents = [
    "Podstack provides on-demand GPUs billed by the second.",
    "Hybrid search combines BM25 and vector embeddings for better recall.",
    "Deep learning models require high-performance A100 or H100 GPUs.",
    "Python functions can be deployed as serverless GPU endpoints."
]
query = "How to run GPU functions on demand?"

# 2. BM25 (Lexical Search)
tokenized_corpus = [doc.split(" ") for doc in documents]
bm25 = BM25Okapi(tokenized_corpus)
lexical_scores = bm25.get_scores(query.split(" "))

# 3. Embeddings (Semantic Search)
# Note: Run this on a Podstack GPU instance for production speeds
model = SentenceTransformer('BAAI/bge-small-en-v1.5')
doc_embeddings = model.encode(documents)
query_embedding = model.encode([query])
semantic_scores = cosine_similarity(query_embedding, doc_embeddings)[0]

# 4. Reciprocal Rank Fusion (RRF)
def rrf_score(ranks, k=60):
    return sum(1.0 / (k + rank) for rank in ranks)

# Combine and rank
final_results = []
for i in range(len(documents)):
    # In a real app, you'd calculate actual rank positions
    # Here we use a weighted sum as a simplified fusion
    combined_score = (0.3 * lexical_scores[i]) + (0.7 * semantic_scores[i])
    final_results.append((documents[i], combined_score))

final_results.sort(key=lambda x: x[1], reverse=True)
for doc, score in final_results:
    print(f"Score: {score:.4f} | {doc}")

Practical Tips for Hybrid Search

1. Normalize Your Scores

BM25 scores are unbounded (they can range from 0 to infinity), while cosine similarity is typically between -1 and 1. Before combining them, it is crucial to normalize both sets of scores to a 0-1 range, or use RRF, which relies on the rank (1st, 2nd, 3rd) rather than the raw score.

2. Tuning the Alpha

In the fusion step, you will often see a parameter called alpha. An alpha of 1.0 is pure vector search; an alpha of 0.0 is pure BM25. For most RAG (Retrieval-Augmented Generation) applications, an alpha between 0.6 and 0.8 (weighting embeddings more heavily) tends to perform best.

3. Domain-Specific Tokenization

If you are working in a niche field (like legal or medical), ensure your BM25 tokenizer doesn't strip out critical stop-words that might carry weight in that domain.

Scaling with Podstack

Running embedding models for millions of documents requires consistent, high-throughput compute. Podstack makes this transition seamless for ML engineers. Instead of managing complex infrastructure, you can wrap your embedding logic into a Python function and deploy it as a serverless GPU endpoint.

You can spin up a dedicated worker to index your documents using the Podstack API:

Podstack does not ship a command-line interface. Use the console, the Python package `podstack-sdk`, or the API at https://podstack.ai/api/v1 with a `ps_live_` key.

With Podstack’s per-second billing, you only pay for the exact time it takes to generate your embeddings. Once your vectors are stored, you can use Podstack's serverless inference to handle the query-time embedding generation, ensuring your hybrid search remains snappy and cost-effective.

Conclusion

Hybrid search is the gold standard for production-grade retrieval. By pairing the keyword-matching reliability of BM25 with the conceptual understanding of embeddings, you provide a search experience that handles both technical queries and natural language effortlessly. By leveraging Podstack's on-demand GPUs, you can ensure that the "semantic" half of your hybrid search remains fast, scalable, and easy to maintain.

Try it on Podstack

Per-second GPUs and pay-per-token models. Add $5, get $10 on your first top-up.

Start building