# Search Platform: Hybrid ANN + BM25 with Re-ranking
# =================================================
# This is a complete, self-contained Python implementation of a hybrid search platform.
# It combines:
# - ANN (FAISS for semantic similarity using sentence embeddings)
# - BM25 (lexical term matching)
# - Hybrid fusion (Reciprocal Rank Fusion - RRF)
# - Re-ranking (Cross-encoder for precise query-document scoring)
#
# Requirements (pip install):
# pip install sentence-transformers rank_bm25 faiss-cpu numpy torch streamlit
#
# Usage:
# 1. Run this script directly for CLI demo.
# 2. Or run `streamlit run this_script.py` for a web UI.
#
# Key Features:
# - Scalable to millions of docs (FAISS IVF index).
# - Configurable fusion weights.
# - GPU support via FAISS/Transformers.
import numpy as np
import faiss
import streamlit as st
from sentence_transformers import SentenceTransformer, CrossEncoder
from rank_bm25 import BM25Okapi
from typing import List, Dict, Tuple, Optional
import torch
class HybridSearchPlatform:
def __init__(self, embedding_model='all-MiniLM-L6-v2', cross_encoder_model='cross-encoder/ms-marco-MiniLM-L-6-v2'):
"""
Initialize the search platform.
"""
# Semantic embedding model (dense vectors)
self.embedder = SentenceTransformer(embedding_model)
self.embedding_dim = self.embedder.get_sentence_embedding_dimension()
# Lexical BM25
self.bm25 = None
self.tokenized_corpus = None
# ANN Index (FAISS)
self.ann_index = None
self.doc_embeddings = None
self.doc_texts = None # Store original docs for retrieval
# Re-ranker (cross-encoder)
device = 'cuda' if torch.cuda.is_available() else 'cpu'
self.reranker = CrossEncoder(cross_encoder_model, device=device)
# Fusion params
self.rrf_k = 60.0 # RRF constant
self.top_k_retrieve = 100 # Candidates for re-ranking
self.top_k_final = 10 # Final results
def index(self, documents: List[str], build_ann=True, nlist=100, nprobe=10):
"""
Index documents.
- Computes embeddings for ANN.
- Tokenizes for BM25.
"""
self.doc_texts = documents
n_docs = len(documents)
# BM25 indexing
self.tokenized_corpus = [doc.lower().split() for doc in documents]
self.bm25 = BM25Okapi(self.tokenized_corpus)
# ANN indexing
if build_ann:
self.doc_embeddings = self.embedder.encode(documents, show_progress_bar=True, normalize_embeddings=True)
self.doc_embeddings = self.doc_embeddings.astype('float32')
# Build IVF index for scalability
quantizer = faiss.IndexFlatIP(self.embedding_dim) # Inner product (cosine sim since normalized)
self.ann_index = faiss.IndexIVFFlat(quantizer, self.embedding_dim, nlist, faiss.METRIC_INNER_PRODUCT)
self.ann_index.train(self.doc_embeddings)
self.ann_index.add(self.doc_embeddings)
self.ann_index.nprobe = nprobe # Trade-off speed/accuracy
print(f"Indexed {n_docs} documents.")
def _normalize_scores(self, scores: np.ndarray) -> np.ndarray:
"""Min-max normalize scores to [0,1]."""
scores = np.array(scores)
return (scores - scores.min()) / (scores.max() - scores.min() + 1e-8)
def _rrf_fusion(self, ann_ranks: np.ndarray, bm25_scores: np.ndarray) -> np.ndarray:
"""
Reciprocal Rank Fusion (RRF).
RRF(rank) = 1 / (k + rank), sum over retrievers.
"""
ann_rrf = 1.0 / (self.rrf_k + ann_ranks)
bm25_norm = self._normalize_scores(bm25_scores) # Normalize BM25 to rank-like
bm25_rrf = 1.0 / (self.rrf_k + bm25_norm * len(ann_ranks))
return ann_rrf + bm25_rrf
def search(self, query: str, alpha_ann: float = 0.7) -> List[Dict[str, any]]:
"""
Hybrid search with re-ranking.
Returns top_k_final results with scores.
"""
if not self.doc_texts or self.bm25 is None:
raise ValueError("Index documents first with .index()")
query_tokens = query.lower().split()
bm25_scores = self.bm25.get_scores(query_tokens)
# ANN retrieval
query_emb = self.embedder.encode([query], normalize_embeddings=True).astype('float32')
ann_distances, ann_indices = self.ann_index.search(query_emb, self.top_k_retrieve)
ann_scores = ann_distances[0] # Cosine sim
ann_ranks = np.argsort(-ann_scores) # Ranks by descending score
# Hybrid fusion (RRF)
hybrid_scores = self._rrf_fusion(ann_ranks, bm25_scores)
hybrid_indices = np.argsort(-hybrid_scores)[:self.top_k_retrieve]
# Prepare candidates for re-ranking: (query, doc) pairs
candidates = [(query, self.doc_texts[i]) for i in hybrid_indices]
# Re-rank
rerank_scores = self.reranker.predict(candidates)
rerank_indices = np.argsort(-rerank_scores)[:self.top_k_final]
# Final results
results = []
for idx in rerank_indices:
doc_idx = hybrid_indices[idx]
results.append({
'doc_id': doc_idx,
'text': self.doc_texts[doc_idx],
'rerank_score': float(rerank_scores[idx]),
'ann_score': float(ann_scores[ann_ranks == doc_idx][0] if doc_idx in ann_ranks else 0),
'bm25_score': float(bm25_scores[doc_idx])
})
return results
# Demo Data
SAMPLE_DOCS = [
"The quick brown fox jumps over the lazy dog.",
"A fast brown fox leaps over a sleepy dog.",
"Python is a programming language created by Guido van Rossum.",
"Machine learning uses algorithms to learn from data.",
"Approximate Nearest Neighbors (ANN) speed up similarity search.",
"BM25 is a ranking function for information retrieval.",
"Hybrid search combines vector and keyword search.",
"Re-ranking improves precision with cross-encoders.",
"FAISS is a library for efficient similarity search.",
"Sentence Transformers provide easy embeddings."
]
# CLI Demo
if __name__ == "__main__":
print("Building Hybrid Search Platform...\n")
platform = HybridSearchPlatform()
platform.index(SAMPLE_DOCS)
while True:
query = input("\nEnter query (or 'quit'): ").strip()
if query.lower() == 'quit':
break
results = platform.search(query)
print("\nTop Results:")
for i, res in enumerate(results, 1):
print(f"{i}. Score: {res['rerank_score']:.3f}")
print(f" {res['text'][:100]}...\n")
# Streamlit Web UI (uncomment to use)
"""
import streamlit as st
st.title("🧠 Hybrid ANN + BM25 Search Platform")
platform = HybridSearchPlatform()
if 'indexed' not in st.session_state:
with st.spinner("Indexing sample docs..."):
platform.index(SAMPLE_DOCS)
st.session_state.indexed = True
st.success("Indexed!")
query = st.text_input("Search query:", "hybrid search")
if st.button("Search") and query:
with st.spinner("Searching..."):
results = platform.search(query)
for i, res in enumerate(results, 1):
st.markdown(f"**{i}.** Score: {res['rerank_score']:.3f} | ANN: {res['ann_score']:.3f} | BM25: {res['bm25_score']:.3f}")
st.write(res['text'])
st.divider()
"""
Quick Start
- Install deps:
pip install sentence-transformers rank_bm25 faiss-cpu numpy torch streamlit
- Run CLI demo: Save as
hybrid_search.py and python hybrid_search.py
- Run Web UI: Uncomment the Streamlit section at bottom, then
streamlit run hybrid_search.py
How It Works
- Indexing: Embed docs with
all-MiniLM-L6-v2 → FAISS IVF (scalable ANN). Tokenize for BM25.
- Retrieval:
- ANN: Top-100 semantic matches (cosine sim).
- BM25: Lexical scores.
- Hybrid: RRF fuses ranks (robust to score scales).
- Re-ranking: Cross-encoder (
ms-marco-MiniLM-L-6-v2) scores top-100 candidates → Top-10.
- Scalability: FAISS handles 1M+ docs easily. GPU accel via
torch.
Customization
- Tune params:
alpha_ann, top_k_retrieve, rrf_k.
- Production: Use Pinecone/Weaviate for managed vectors, Elasticsearch for BM25.
- Your data: Replace
SAMPLE_DOCS with platform.index(your_docs_list).
Query "hybrid search ANN BM25" on sample data → See magic! 🚀 Questions? Ask away.