We build it in four steps: the lexical retriever, the dense retriever, the fusion step, and an alternative weighted fusion. Install the two libraries first.
Step 1 — The lexical retriever (BM25)
python · lexical_retriever.py
# ── Retriever 1: BM25 (lexical / exact terms) ─────────────────
from rank_bm25 import BM25Okapi
documents = [
"python developer roadmap guide",
"vector database for semantic search",
"bm25 keyword ranking in elasticsearch",
"error code E4021 connection refused",
]
tokenized = ***REDACTED*** for d in documents]
bm25 = BM25Okapi(tokenized)
def bm25_search(query, top_k=50):
scores = bm25.get_scores(query.lower().split())
ranked = sorted(enumerate(scores), key=lambda x: x[1], reverse=True)
return [(idx, score) for idx, score in ranked[:top_k]]
# Query: "E4021 connection error"
# BM25 finds the exact error code instantly ✅Step 2 — The dense retriever (vectors)
python · dense_retriever.py
# ── Retriever 2: dense vectors (semantic / meaning) ───────────
from sentence_transformers import SentenceTransformer
import numpy as np
model = SentenceTransformer("all-MiniLM-L6-v2")
# Embed the corpus once, store the matrix
doc_vectors = model.encode(documents, normalize_embeddings=True)
def vector_search(query, top_k=50):
q_vec = model.encode([query], normalize_embeddings=True)[0]
# cosine similarity == dot product when vectors are normalised
sims = doc_vectors @ q_vec
ranked = np.argsort(-sims)[:top_k]
return [(int(i), float(sims[i])) for i in ranked]
# Query: "how do I fix a broken database link"
# Vector search finds the E4021 doc even with zero shared words ✅Step 3 — Fuse with Reciprocal Rank Fusion
python · hybrid_rrf.py
# ── Fusion: Reciprocal Rank Fusion (RRF) ──────────────────────
def reciprocal_rank_fusion(ranked_lists, k=60):
"""
ranked_lists: list of ranked lists, each a list of (doc_id, score)
sorted best-first. Scores are IGNORED — only rank matters.
k: damping constant (60 is the standard default)
"""
fused = {}
for ranked in ranked_lists:
for position, (doc_id, _score) in enumerate(ranked):
# position is 0-based, so rank = position + 1
fused[doc_id] = fused.get(doc_id, 0.0) + 1.0 / (k + position + 1)
return sorted(fused.items(), key=lambda x: x[1], reverse=True)
def hybrid_search(query, top_k=10):
lexical = bm25_search(query, top_k=50)
semantic = vector_search(query, top_k=50)
fused = reciprocal_rank_fusion([lexical, semantic], k=60)
return [(documents[i], score) for i, score in fused[:top_k]]
for rank, (doc, score) in enumerate(hybrid_search("E4021 connection error"), 1):
print(f"{rank}. RRF={score:.5f} → {doc}")Step 4 — Alternative: weighted score fusion
python · weighted_fusion.py
# ── Alternative: weighted score fusion (needs normalisation) ──
def min_max(scores):
lo, hi = min(scores), max(scores)
if hi == lo:
return [0.0] * len(scores)
return [(s - lo) / (hi - lo) for s in scores]
def weighted_fusion(query, alpha=0.5, top_k=10):
"""alpha=0 → pure BM25, alpha=1 → pure vectors."""
lexical = dict(bm25_search(query, top_k=50))
semantic = dict(vector_search(query, top_k=50))
candidates = set(lexical) | set(semantic)
lex_norm = dict(zip(lexical, min_max(list(lexical.values()))))
vec_norm = dict(zip(semantic, min_max(list(semantic.values()))))
scored = []
for doc_id in candidates:
score = (alpha * vec_norm.get(doc_id, 0.0)
+ (1 - alpha) * lex_norm.get(doc_id, 0.0))
scored.append((doc_id, score))
scored.sort(key=lambda x: x[1], reverse=True)
return [(documents[i], s) for i, s in scored[:top_k]]
# Tune alpha on a labelled query set — do not guess it.
for alpha in [0.3, 0.5, 0.7]:
print(f"alpha={alpha}", weighted_fusion("semantic search python", alpha)[:3])
Sign in with Google to add comments and replies.