RAG Chunking, Embeddings and Hybrid Search Done Right

Your RAG bot found the wrong runbook again: the alert said OOMKilled, and vector search returned a memory dashboard page. Most bad answers are retrieval failures. This guide fixes the layers underneath: chunk documents by structure, pick an embedding model on purpose, run a hybrid search that fuses BM25 with vectors, then filter and re-rank.
How hybrid search fits into a RAG pipeline
The RAG 101 pipeline has one retriever: embeddings in a vector store. They match meaning, so "pods keep restarting" finds the crash-loop page, but they miss exact tokens such as error codes and flag names. BM25, the keyword ranking behind Elasticsearch and OpenSearch, is the opposite. Hybrid search runs both and merges the results.
The top lane runs on every merge; the bottom lane runs per question. Only the final LLM call leaves your machine. Start with a virtual environment:
python3 -m venv .venv && source .venv/bin/activate
pip install -U rank_bm25 sentence-transformers
python -c "import rank_bm25, sentence_transformers; print('ok')"
rank_bm25 is a small BM25 library, and sentence-transformers runs the embedding model and the re-ranker. The check prints ok. Models download from Hugging Face on first use, so bake them into the container image if pods have no internet access.
Chunk by structure, not by character count
A fixed-size splitter cuts every N characters, so it separates a command from the sentence that explains it, or a table from its header row. That chunk still scores well and helps nobody. The graphic compares both splitters on the same runbook.
Heading-aware chunks keep code and tables intact, and a breadcrumb such as Checkout 5xx > Roll back keeps the service name inside every chunk. Save this as chunker.py:
import re, subprocess
from datetime import date
HEADING = re.compile(r"^(#{1,3}) (.+)$")
def meta_for(path): # runbooks/<env>/<service>/<page>.md
git = ["git", "log", "-1", "--format=%cs", "--", str(path)]
updated = subprocess.run(git, capture_output=True, text=True).stdout.strip()
return {"env": path.parts[-3], "service": path.parts[-2],
"updated": updated or date.today().isoformat()}
def chunk_markdown(text, source, meta):
chunks, crumbs, buf, in_fence = [], [], [], False
def flush():
if body := "\n".join(buf).strip():
chunks.append({"text": " > ".join(crumbs) + "\n" + body, "source": source, **meta})
buf.clear()
for line in text.splitlines():
if line.startswith("```"):
in_fence = not in_fence # inside a fence, '#' starts a comment
m = None if in_fence else HEADING.match(line)
if m:
flush()
crumbs[len(m.group(1)) - 1:] = [m.group(2)]
else:
buf.append(line)
flush()
return chunks
The fence flag stops a shell comment in a code block from becoming a heading. The breadcrumb is part of the chunk text, so BM25 and the embedder both see the service; metadata comes from the path and Git. Keep sections under about 1,500 characters: the embedding model below reads only 512 tokens and drops the rest.
Choose an embedding model on purpose
An embedding model turns text into a vector, a list of numbers where similar meanings sit close together. Compare models on dimensions (memory), maximum input (longer text is truncated) and where they run (cost and latency):
| Model | Dims | Max input | RAM, 1M chunks | Cost and latency |
|---|---|---|---|---|
| all-MiniLM-L6-v2 | 384 | 256 tokens | 1.5 GB | Free, fastest on CPU |
| bge-small-en-v1.5 | 384 | 512 tokens | 1.5 GB | Free, fast on CPU |
| bge-m3 | 1024 | 8,192 tokens | 4.1 GB | Free, GPU for bulk |
RAM is dimensions × 4 bytes × chunks for float32 vectors. Start with bge-small-en-v1.5 from BAAI for English runbooks, and use bge-m3 for long or multilingual documents. Hosted APIs from OpenAI, Cohere or Voyage remove the hosting work but add a per-token bill and a network hop to your latency SLO.
Pin the model in config and re-embed everything when it changes: vectors from two models are not comparable.
Hybrid search with reciprocal rank fusion
BM25 scores and cosine similarities use different scales, so you cannot simply add them. Reciprocal rank fusion (RRF) uses positions only: a chunk earns 1/(k + rank) from each list it appears in, with k = 60 from the original paper by Cormack, Clarke and Büttcher (2009).
In the diagram, the vector favourite drops to fourth because BM25 never ranked it. Agreement wins: third place in both lists scores 1/63 + 1/63 = 0.0317, beating first and eighth at 1/61 + 1/68 = 0.0311. Save this as search.py:
import pathlib, re
from rank_bm25 import BM25Okapi
from sentence_transformers import SentenceTransformer
from chunker import chunk_markdown, meta_for
chunks = [c for f in sorted(pathlib.Path("runbooks").glob("*/*/*.md"))
for c in chunk_markdown(f.read_text(), str(f), meta_for(f))]
texts = [c["text"] for c in chunks]
def tokenize(text): # keeps kube-proxy and oom_score_adj whole
return re.findall(r"[a-z0-9_.-]+", text.lower())
bm25 = BM25Okapi([tokenize(t) for t in texts])
model = SentenceTransformer("BAAI/bge-small-en-v1.5")
doc_vecs = model.encode(texts, normalize_embeddings=True)
PREFIX = "Represent this sentence for searching relevant passages: "
def rrf(rankings, k=60):
scores = {}
for ranking in rankings:
for rank, idx in enumerate(ranking, start=1):
scores[idx] = scores.get(idx, 0) + 1 / (k + rank)
return sorted(scores, key=scores.get, reverse=True)
def hybrid_search(query, n=50):
kw = bm25.get_scores(tokenize(query))
by_keyword = [int(i) for i in kw.argsort()[::-1][:n] if kw[i] > 0]
q = model.encode(PREFIX + query, normalize_embeddings=True)
by_vector = (doc_vecs @ q).argsort()[::-1][:n].tolist()
return rrf([by_keyword, by_vector])
bge models expect the instruction prefix on queries only, and normalised embeddings make the dot product a cosine similarity. Skipping zero BM25 scores stops a query with no keyword hits from fusing a random ranking. Test with "payments pods keep restarting": the crash-loop section should come back either way.
Past a few thousand chunks, use the native hybrid queries in OpenSearch, Elasticsearch, Qdrant or Weaviate.
Filter by service, env and freshness, then re-rank
Fusion does not know the question came from the checkout on-call in prod. Metadata filters drop the wrong service, the wrong environment and pages untouched for six months. A cross-encoder then reads question and chunk together: slower than comparing vectors, but more precise. The flowchart shows each decision.
Both "no" branches stop before the LLM, so the bot says no runbook covers the question instead of improvising, and the gap becomes a docs ticket. Add this to search.py:
from datetime import date, timedelta
from sentence_transformers import CrossEncoder
reranker = CrossEncoder("cross-encoder/ms-marco-MiniLM-L6-v2")
MAX_AGE = timedelta(days=180)
def allowed(c, service, env):
fresh = date.today() - date.fromisoformat(c["updated"]) <= MAX_AGE
return fresh and c["service"] in (service, "shared") and c["env"] in (env, "all")
def retrieve(query, service, env, top_k=4, min_score=0.0):
cands = [chunks[i] for i in hybrid_search(query) if allowed(chunks[i], service, env)][:20]
if not cands:
return []
scores = reranker.predict([(query, c["text"]) for c in cands])
best = sorted(zip(scores, cands), key=lambda p: p[0], reverse=True)[:top_k]
return [(c, float(s)) for s, c in best if s >= min_score]
Filtering runs first, so the slower model sees at most 20 chunks. The shared service and all env let platform runbooks, such as DNS, match any question. Cross-encoder scores are unbounded (the README example prints 8.6 and 5.5), so set the minimum from your evals. Check it in python -i search.py (illustrative scores):
>>> for c, s in retrieve("checkout 5xx after deploy", "checkout", "prod"):
... print(round(s, 1), c["text"].splitlines()[0])
7.9 Checkout 5xx > Roll back
5.2 Checkout 5xx > Check rollout
If another service's chunk appears, fix its folder, not the prompt, and add the re-rank time to your latency budget.
Measure retrieval like an SLO
I have built RAG pipelines that automate documentation search, and a Slack bot that investigates incidents with that search plus metric and log APIs. Treat retrieval as a number: keep 30 real incident questions, each labelled with the chunk that should come back, and track recall@4, the share whose right chunk lands in the final four.
Re-run the set whenever the chunker, model, filters or threshold change. That is how an incident co-pilot earns trust, and how executable runbooks match the right alert.
Common pitfalls
When an answer is wrong, print the retrieved chunks before you touch the prompt.
| Symptom | Likely cause | Fix |
|---|---|---|
| Error codes never match | Vector-only retrieval | Add BM25, fuse with RRF |
| Command without context | Fixed-size chunks | Split on headings |
| Staging steps in prod | No metadata filter | Filter service and env |
| Retired procedure cited | Stale pages indexed | Freshness filter, CI re-index |
| Worse after an upgrade | Mixed embedding models | Pin, then re-embed all |
Key takeaways
- Split on headings, keep code and tables whole, add a breadcrumb.
- Choose the embedding model by dimensions, input limit and latency; pin it.
- Fuse BM25 and vectors with reciprocal rank fusion, not raw scores.
- Filter, re-rank with a cross-encoder, and refuse when scores are low.
Related articles

From Runbook to Robot: Executable Runbooks as Code
Prose runbooks drift until they fail you at 3 a.m. Write executable runbooks in YAML with pre-checks, dry runs and approval gates, run them with a small Python executor, and let an LLM draft them from your old wiki pages.

AI Incident Triage: A Co-Pilot for the First 10 Minutes
Wire Alertmanager to a small Python worker that queries Prometheus, your deploy log and a RAG index of post-mortems, then posts a cited triage summary to Slack. Read-only by design: humans approve every change.

AIOps Without the Hype: What AI Improves in Observability
Anomaly detection, log clustering, natural-language queries and autonomous RCA: which AIOps features work today, the data quality they need, and how an SRE team can adopt them in 30 days.