Hybrid search plus a reranker found the right chunk for 44 of 50 questions on LangChain with ChromaDB and 42 on LlamaIndex with FAISS. Plain dense search managed 35 on either stack. For this LangChain ChromaDB Ollama RAG comparison we built both pipelines on the same 2,862 chunks of Kubernetes documentation, embedded them with the same nomic-embed-text model in Ollama and scored four retrieval setups per stack on recall@5, MRR and latency.
The stacks diverge only where their defaults do. Dense search returned the same chunks in both, because the embeddings are identical. The BM25 half is where they split: LlamaIndex stems and lowercases, LangChain splits on whitespace, and that one default put 4 questions between their hybrid scores. The reranker (benchmarked November 2026 on Ubuntu 26.04, CPU only, 16 vCPU) costs about 1.3 seconds per query and buys the biggest jump in the table.
Below are the chunker, both stack scripts, the scoring code and a ragas faithfulness run with a local judge, as run. Bring your own questions in the Step 2 format to score your documents.
Results: recall@5, MRR and latency for both stacks
Each cell is the score over the same 50 questions, retrieving the top 5 chunks. Recall@5 is the share of questions with the gold chunk anywhere in the top 5. MRR@5 rewards rank, so a hit at position 1 scores 1.0 and a hit at position 5 scores 0.2. Latency covers retrieval only, measured per query after two untimed warm-up calls.
| Setup | LangChain + Chroma recall@5 / MRR | LangChain p50 / p95 | LlamaIndex + FAISS recall@5 / MRR | LlamaIndex p50 / p95 |
|---|---|---|---|---|
| Dense (nomic-embed-text) | 0.70 / 0.548 | 21.6 / 28.3 ms | 0.70 / 0.548 | 20.2 / 25.7 ms |
| BM25 only | 0.56 / 0.420 | 9.1 / 14.4 ms | 0.74 / 0.630 | 0.6 / 0.7 ms |
| Hybrid (Ensemble / RRF) | 0.70 / 0.632 | 32.6 / 45.0 ms | 0.78 / 0.636 | 21.4 / 27.3 ms |
| Hybrid + bge-reranker-base | 0.88 / 0.741 | 1,360 / 1,691 ms | 0.84 / 0.732 | 1,311 / 1,580 ms |
| Hybrid, LangChain BM25 tokenized | 0.76 / 0.663 | 32.8 / 44.9 ms | n/a | n/a |
| Hybrid + rerank, tokenized | 0.84 / 0.707 | 1,316 / 1,605 ms | n/a | n/a |
Read the table with the sample size in mind. One question is worth 0.02 of recall, so the 0.88 against 0.84 gap at the top is two questions and sits within the margin of a 50-question set. The gaps that hold up are bigger. Reranking adds 9 questions over hybrid on LangChain and 3 on LlamaIndex. Dense and BM25 disagree on 14 to 19 of the 50, which is why fusing them helps. BM25 as LangChain ships it finds 9 fewer questions than the LlamaIndex BM25.
- Same dense numbers: both stacks embed the identical 2,862 strings through the same Ollama model, so Chroma’s HNSW index and the exact FAISS
IndexFlatIPsearch put the gold chunk at the same rank for all 50 questions. - BM25 gap is a tokenizer: LangChain’s
BM25Retrieverdefaults tostr.split(); swapping in a lowercase alphanumeric tokenizer lifted it from 0.56 to 0.68 with no other change. - Rerank is the expensive win: about 1.3 seconds per query on CPU, 40 to 60 times the hybrid cost, for the top recall and MRR in both stacks.
End to end with gemma3:4b answering from the top 5 chunks, hybrid plus rerank took a median of about 11.5 to 11.9 seconds per question on both stacks, against 9.5 to 10 seconds for the unreranked LangChain setups. Step 7 has p50 and p95 for all four setups on both stacks, and Step 8 the faithfulness scores.
How the benchmark was measured
Our test box was a 16 vCPU, 64 GB cloud VM with no GPU, running Ubuntu 26.04 LTS and Python 3.14. Ollama served three models on CPU: nomic-embed-text for embeddings, gemma3:4b for answers and qwen2.5:7b as the ragas judge. A GPU would shrink the generation and rerank timings, but the retrieval recall would not change, since the same vectors and the same scores come out.

The corpus is the content/en/docs/concepts tree of the Kubernetes website repository, licensed CC BY 4.0. We stripped Hugo front matter, shortcodes and HTML comments, dropped files under 200 characters and split the rest. That left 184 files and 2,862 chunks averaging 791 characters. Kubernetes docs suit this test because they mix exact flag names, which favour keyword search, with long conceptual prose, which favours embeddings.
Each of the 50 test questions comes from a different source file. Every question carries the file it came from, a verbatim evidence string of 40 to 90 characters copied from that file, and a reference answer. A retrieved chunk counts as relevant only when its source matches and it contains the evidence string after whitespace and case are normalised. That makes scoring mechanical: no LLM decides what counts as a hit.
- Keyword questions (25): name the flag, field or term as it appears in the docs, for example the default of
--node-eviction-rate. BM25 should find these. - Paraphrase questions (25): describe the behaviour without the doc’s wording, such as asking what the kubelet does to per-pod container limits when the global cap is hit. Embeddings should find these.
- Latency: wall clock per query from
time.perf_counter(), p50 as the median and p95 as the nearest-rank percentile over 50 samples.
Keeping the two kinds apart matters for reading the results, because every setup scores higher on keyword questions than on paraphrases. A question set of only one kind would flatter whichever retriever suits it. Here is how the pieces connect on the test box.

Only the vector store, the BM25 implementation and the fusion method differ between the two paths. Chunking, embeddings, the reranker model, the prompt and the chat model are shared, so any difference in the table traces back to one of those three components.
Step 1: Install Ollama and the Python packages
Install Ollama with the official script and pull the three models. On CPU the 4.7 GB judge model is the slowest piece of the whole run, so skip it if you do not plan to run ragas. Our Ollama install guide for Ubuntu and Rocky covers GPU drivers and the service unit if you need them.
curl -fsSL https://ollama.com/install.sh | sh
ollama pull nomic-embed-text
ollama pull gemma3:4b
ollama pull qwen2.5:7b
Both stacks share one virtual environment. The pins below are the versions this benchmark ran; LangChain and LlamaIndex both moved import paths in their recent releases, so unpinned installs a few months from now may hit the errors covered later.
sudo apt-get install -y python3-venv python3-dev build-essential git
python3 -m venv ~/rag
~/rag/bin/pip install --upgrade pip
# https://pypi.org/project/langchain/#history https://pypi.org/project/llama-index-core/#history
~/rag/bin/pip install chromadb==1.5.9 langchain==1.5.0 langchain-chroma==1.1.0 \
langchain-community==0.4.2 langchain-ollama==1.1.0 langchain-classic==1.0.8 rank-bm25==0.2.2 \
llama-index-core==0.14.25 llama-index-vector-stores-faiss==0.7.0 \
llama-index-embeddings-ollama==0.10.0 llama-index-llms-ollama==0.11.0 \
llama-index-retrievers-bm25==0.8.0 faiss-cpu==1.16.0 sentence-transformers==6.3.0
Filtered to the packages that matter for retrieval, pip resolved these versions on the test box:

Note langchain-classic in that list. EnsembleRetriever and ContextualCompressionRetriever no longer live in the main langchain package, and most hybrid search tutorials still import them from the old path. The ragas judge goes into a second environment for a reason explained in the errors section, so do not install ragas here.
Step 2: Chunk the corpus once for both stacks
Fetch only the concepts tree with a shallow sparse clone, which skips the website’s history and the files outside that directory. We tested at commit 2674d50; a newer checkout will produce a slightly different chunk count.
git clone --depth 1 --filter=blob:none --sparse https://github.com/kubernetes/website.git ~/k8s-website
git -C ~/k8s-website sparse-checkout set content/en/docs/concepts
mkdir -p ~/bench && cd ~/bench
The chunker writes one JSON line per chunk with a stable id, the source file and the text. Both stacks read this file, so chunk boundaries cannot be the reason their numbers differ. Create it:
vim ~/bench/prep_corpus.py
Paste the script. It uses LangChain’s text splitter at 1,000 characters with 150 of overlap, a common default that keeps most Kubernetes doc sections to two or three chunks:
import json, re, pathlib
from langchain_text_splitters import RecursiveCharacterTextSplitter
ROOT = pathlib.Path.home() / "k8s-website/content/en/docs/concepts"
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=150)
def clean(text):
text = re.sub(r"^---\n.*?\n---\n", "", text, flags=re.S) # Hugo front matter
text = re.sub(r"\{\{[<%].*?[>%]\}\}", "", text, flags=re.S) # Hugo shortcodes
text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
return re.sub(r"\n{3,}", "\n\n", text).strip()
chunks = []
for path in sorted(ROOT.rglob("*.md")):
body = clean(path.read_text(encoding="utf-8"))
if len(body) < 200:
continue
src = str(path.relative_to(ROOT))
for i, piece in enumerate(splitter.split_text(body)):
chunks.append({"id": f"{src}#{i}", "source": src, "text": piece})
with open("chunks.jsonl", "w") as f:
for c in chunks:
f.write(json.dumps(c) + "\n")
print(f"files={len({c['source'] for c in chunks})} chunks={len(chunks)} "
f"avg_chars={sum(len(c['text']) for c in chunks) // len(chunks)}")
Scoring helpers go in a shared module so that both stacks count hits, time queries and compute percentiles the same way. K is the number of chunks scored and POOL is how many candidates each retriever hands to fusion or the reranker:
vim ~/bench/common.py
Add the helpers. The prompt at the top is shared by both stacks in the generation step:
import csv, json, math, re, statistics, time
EMBED_MODEL = "nomic-embed-text"
CHAT_MODEL = "gemma3:4b"
RERANK_MODEL = "BAAI/bge-reranker-base"
K = 5 # results scored per question
POOL = 10 # candidates each retriever hands to fusion / the reranker
PROMPT = (
"Answer the question using only the context below. "
"If the context does not contain the answer, say you don't know.\n\n"
"Context:\n{context}\n\nQuestion: {question}\nAnswer:"
)
def norm(s):
return re.sub(r"\s+", " ", s).strip().lower()
def load_chunks(path="chunks.jsonl"):
return [json.loads(l) for l in open(path)]
def load_questions(path="questions.jsonl"):
return [json.loads(l) for l in open(path)]
def relevant(q, source, text):
return source == q["source"] and norm(q["evidence"]) in norm(text)
def first_hit(q, results):
"""results: list of (source, text) in rank order; returns 1-based rank or 0."""
for rank, (src, txt) in enumerate(results[:K], 1):
if relevant(q, src, txt):
return rank
return 0
def pct(values, p):
values = sorted(values) # nearest-rank percentile
return values[max(0, math.ceil(p / 100 * len(values)) - 1)]
def summarise(stack, setup, rows):
ranks = [r["rank"] for r in rows]
lat = [r["ms"] for r in rows]
out = {
"stack": stack, "setup": setup, "n": len(rows),
"recall@5": round(sum(1 for r in ranks if r) / len(ranks), 3),
"mrr@5": round(sum(1 / r for r in ranks if r) / len(ranks), 3),
"p50_ms": round(statistics.median(lat), 1),
"p95_ms": round(pct(lat, 95), 1),
}
for kind in ("keyword", "paraphrase"):
sub = [r["rank"] for r in rows if r["kind"] == kind]
out[f"recall@5_{kind}"] = round(sum(1 for r in sub if r) / len(sub), 3)
return out
def run_setup(stack, setup, questions, search):
"""search(question) -> list of (source, text). Two warm-up calls are not timed."""
for q in questions[:2]:
search(q["question"])
rows = []
for q in questions:
t0 = time.perf_counter()
res = search(q["question"])
ms = (time.perf_counter() - t0) * 1000
rows.append({"stack": stack, "setup": setup, "qid": q["qid"], "kind": q["kind"],
"rank": first_hit(q, res), "ms": round(ms, 1)})
return rows
def write_csv(path, rows):
with open(path, "w", newline="") as f:
w = csv.DictWriter(f, fieldnames=list(rows[0].keys()))
w.writeheader()
w.writerows(rows)
Both stacks also expect a questions.jsonl in the same directory, one JSON object per line. Our first line shows every field the scorer reads:
{"qid": "q01", "question": "What is the default value of the kube-controller-manager `--node-eviction-rate` flag?", "kind": "keyword", "source": "architecture/nodes.md", "evidence": "`--node-eviction-rate` (default 0.1) per second, meaning it won't evict pods", "answer": "The default is 0.1 per second, so the controller evicts pods from nodes at a rate of one node every 10 seconds."}
Write your own set against your own documents rather than reusing ours. Pick one question per source file so a single long page cannot dominate the score, copy the evidence string verbatim, and keep keyword and paraphrase questions roughly equal. Include at least one of each kind: summarise() divides by the count of each kind and crashes on a set that lacks one. We drafted ours with a model and then checked every evidence string against its source file, rejecting any that did not match verbatim.
Step 3: Build the LangChain and ChromaDB stack
The LangChain side uses langchain-ollama for embeddings and chat, langchain-chroma for a persistent Chroma collection with cosine distance, the community BM25Retriever and the classic EnsembleRetriever for fusion. Run with no arguments, it ingests on first use, then scores all four setups and writes two CSV files:
vim ~/bench/lc_stack.py
The reranker wraps the hybrid retriever, so it scores up to 20 fused candidates and keeps the best 5:
import argparse, json, os, time
from langchain_core.documents import Document
from langchain_core.prompts import ChatPromptTemplate
from langchain_ollama import OllamaEmbeddings, ChatOllama
from langchain_chroma import Chroma
from langchain_community.retrievers import BM25Retriever
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
from langchain_classic.retrievers import EnsembleRetriever, ContextualCompressionRetriever
from langchain_classic.retrievers.document_compressors import CrossEncoderReranker
from common import *
ap = argparse.ArgumentParser()
ap.add_argument("--answer", help="setup to generate answers with")
ap.add_argument("-n", type=int, default=50)
args = ap.parse_args()
chunks, questions = load_chunks(), load_questions()
docs = [Document(page_content=c["text"], metadata={"source": c["source"]}, id=c["id"]) for c in chunks]
emb = OllamaEmbeddings(model=EMBED_MODEL)
if os.path.isdir("lc_chroma"):
store = Chroma("k8s", embedding_function=emb, persist_directory="lc_chroma")
else:
t0 = time.perf_counter()
store = Chroma("k8s", embedding_function=emb, persist_directory="lc_chroma",
collection_metadata={"hnsw:space": "cosine"})
for i in range(0, len(docs), 256):
store.add_documents(docs[i:i + 256], ids=[d.id for d in docs[i:i + 256]])
print(f"lc ingest: {len(docs)} chunks embedded into Chroma in {time.perf_counter() - t0:.1f}s")
dense = store.as_retriever(search_kwargs={"k": POOL})
bm25 = BM25Retriever.from_documents(docs, k=POOL)
hybrid = EnsembleRetriever(retrievers=[dense, bm25], weights=[0.5, 0.5])
reranker = CrossEncoderReranker(model=HuggingFaceCrossEncoder(model_name=RERANK_MODEL), top_n=K)
rerank = ContextualCompressionRetriever(base_compressor=reranker, base_retriever=hybrid)
setups = {"dense": dense, "bm25": bm25, "hybrid": hybrid, "hybrid+rerank": rerank}
def as_pairs(retriever):
return lambda q: [(d.metadata["source"], d.page_content) for d in retriever.invoke(q)][:K]
if not args.answer:
all_rows, summary = [], []
for name, r in setups.items():
rows = run_setup("langchain+chroma", name, questions, as_pairs(r))
all_rows += rows
summary.append(summarise("langchain+chroma", name, rows))
print(json.dumps(summary[-1]))
write_csv("lc_retrieval.csv", all_rows)
write_csv("lc_summary.csv", summary)
else:
llm = ChatOllama(model=CHAT_MODEL, temperature=0, num_ctx=4096)
chain = ChatPromptTemplate.from_template(PROMPT) | llm
retriever = setups[args.answer]
out = []
for q in questions[:args.n]:
t0 = time.perf_counter()
ctx = [d.page_content for d in retriever.invoke(q["question"])][:K]
t1 = time.perf_counter()
msg = chain.invoke({"context": "\n\n---\n\n".join(ctx), "question": q["question"]})
t2 = time.perf_counter()
out.append({"qid": q["qid"], "question": q["question"], "answer": msg.content,
"contexts": ctx, "retrieve_ms": round((t1 - t0) * 1000, 1),
"total_ms": round((t2 - t0) * 1000, 1),
"eval_tokens": msg.usage_metadata.get("output_tokens") if msg.usage_metadata else None})
print(q["qid"], out[-1]["total_ms"], "ms", flush=True)
with open(f"lc_answers.jsonl", "w") as f:
for o in out:
f.write(json.dumps(o) + "\n")
Run the chunker, then the LangChain evaluation. The first run embeds all 2,862 chunks, which took 301.7 seconds on 16 CPU cores, about 9.5 chunks per second through Ollama:
~/rag/bin/python prep_corpus.py
~/rag/bin/python lc_stack.py | tee lc_eval.log
column -s, -t lc_summary.csv
Here are the chunk count, the on-disk size of both stores and the LangChain summary as captured on the test box:

Hybrid did not raise recall over dense here: both found 35 of 50. What it changed is rank. MRR went from 0.548 to 0.632 because fusion pushed the right chunk higher in the list when both retrievers agreed. Paraphrase recall even dipped from 0.56 to 0.52, which means the weak BM25 half occasionally pushed a correct dense hit out of the top 5. The Chroma directory took 27 MB for 2,862 vectors plus the text and metadata.
Step 4: Build the LlamaIndex and FAISS stack
The LlamaIndex side stores vectors in a flat FAISS inner-product index. Ollama returns unit-length vectors for nomic-embed-text (a test embedding measured 768 dimensions with a norm of 0.99999997), so inner product equals cosine similarity and the scores match Chroma’s. Hybrid uses QueryFusionRetriever in reciprocal-rank mode with query generation turned off, so no LLM call happens during retrieval:
vim ~/bench/li_stack.py
One setting in the node constructor deserves attention. By default a LlamaIndex TextNode prepends its metadata to the text it embeds, which would make LlamaIndex embed different strings than LangChain. The two excluded_*_metadata_keys arguments switch that off:
import argparse, json, os, time
import faiss
from llama_index.core import Settings, StorageContext, VectorStoreIndex, PromptTemplate, load_index_from_storage
from llama_index.core.schema import TextNode, QueryBundle
from llama_index.core.retrievers import QueryFusionRetriever
from llama_index.core.postprocessor import SentenceTransformerRerank
from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.embeddings.ollama import OllamaEmbedding
from llama_index.llms.ollama import Ollama
from llama_index.vector_stores.faiss import FaissVectorStore
from llama_index.retrievers.bm25 import BM25Retriever
from common import *
ap = argparse.ArgumentParser()
ap.add_argument("--answer", help="setup to generate answers with")
ap.add_argument("-n", type=int, default=50)
args = ap.parse_args()
chunks, questions = load_chunks(), load_questions()
# Keep "source" out of the embedded and prompted text so both stacks embed identical strings.
nodes = [TextNode(text=c["text"], id_=c["id"], metadata={"source": c["source"]},
excluded_embed_metadata_keys=["source"], excluded_llm_metadata_keys=["source"])
for c in chunks]
Settings.embed_model = OllamaEmbedding(model_name=EMBED_MODEL)
Settings.llm = Ollama(model=CHAT_MODEL, temperature=0, context_window=4096, request_timeout=900)
if os.path.isdir("li_faiss"):
store = FaissVectorStore.from_persist_dir("li_faiss")
index = load_index_from_storage(StorageContext.from_defaults(vector_store=store, persist_dir="li_faiss"))
else:
t0 = time.perf_counter()
store = FaissVectorStore(faiss_index=faiss.IndexFlatIP(768))
index = VectorStoreIndex(nodes, storage_context=StorageContext.from_defaults(vector_store=store),
insert_batch_size=256)
print(f"li ingest: {len(nodes)} chunks embedded into FAISS in {time.perf_counter() - t0:.1f}s")
index.storage_context.persist("li_faiss")
dense = index.as_retriever(similarity_top_k=POOL)
bm25 = BM25Retriever.from_defaults(nodes=nodes, similarity_top_k=POOL)
hybrid = QueryFusionRetriever([dense, bm25], similarity_top_k=2 * POOL, num_queries=1,
mode="reciprocal_rerank", use_async=False)
rerank = SentenceTransformerRerank(model=RERANK_MODEL, top_n=K)
def search(name, q):
if name == "hybrid+rerank":
return rerank.postprocess_nodes(hybrid.retrieve(q), query_bundle=QueryBundle(q))
return {"dense": dense, "bm25": bm25, "hybrid": hybrid}[name].retrieve(q)
setups = ["dense", "bm25", "hybrid", "hybrid+rerank"]
if not args.answer:
all_rows, summary = [], []
for name in setups:
fn = lambda q, name=name: [(n.node.metadata["source"], n.node.get_content()) for n in search(name, q)][:K]
rows = run_setup("llamaindex+faiss", name, questions, fn)
all_rows += rows
summary.append(summarise("llamaindex+faiss", name, rows))
print(json.dumps(summary[-1]))
write_csv("li_retrieval.csv", all_rows)
write_csv("li_summary.csv", summary)
else:
qa = PromptTemplate(PROMPT.replace("{context}", "{context_str}").replace("{question}", "{query_str}"))
if args.answer == "hybrid+rerank":
engine = RetrieverQueryEngine.from_args(hybrid, node_postprocessors=[rerank], text_qa_template=qa)
else:
engine = RetrieverQueryEngine.from_args({"dense": dense, "bm25": bm25, "hybrid": hybrid}[args.answer],
text_qa_template=qa)
out = []
for q in questions[:args.n]:
t0 = time.perf_counter()
resp = engine.query(q["question"])
t1 = time.perf_counter()
out.append({"qid": q["qid"], "question": q["question"], "answer": str(resp),
"contexts": [n.node.get_content() for n in resp.source_nodes][:K],
"total_ms": round((t1 - t0) * 1000, 1)})
print(q["qid"], out[-1]["total_ms"], "ms", flush=True)
with open("li_answers.jsonl", "w") as f:
for o in out:
f.write(json.dumps(o) + "\n")
Run it the same way. Ingest into FAISS took 301.3 seconds, within half a second of Chroma, which confirms that Ollama embedding time and not the store dominates ingest:
~/rag/bin/python li_stack.py | tee li_eval.log
column -s, -t li_summary.csv
LlamaIndex scored the same 50 questions like this:

Dense matches LangChain to the third decimal, as expected. BM25 is the outlier: 0.74 recall at 0.6 ms p50, beating dense search on this corpus and running 15 times faster than LangChain’s BM25. The bm25s library behind it precomputes a sparse score matrix and applies an English stemmer, so a question about “evicting” matches a chunk about “eviction”. The LlamaIndex directory took 13 MB, half the Chroma footprint: an 8.8 MB flat index plus a 4.2 MB JSON docstore holding the chunk text. Chroma’s 27 MB keeps text, metadata and the HNSW graph together.
Step 5: Fix hybrid search in LangChain with a BM25 tokenizer
Hybrid search is only as good as its weaker half, and in LangChain that half is BM25Retriever with its default preprocess_func, a bare str.split(). It is case-sensitive and leaves punctuation attached, so the token `percentageOfNodesToScore`? with backticks and a question mark never matches the same word in the docs. Eleven questions that LlamaIndex BM25 answered were misses for LangChain BM25, and six of those wrapped a flag or field name in backticks.
A one-line tokenizer passed at construction fixes it. This script reuses the persisted Chroma store and only rebuilds the BM25 side:
vim ~/bench/lc_bm25_tokenized.py
Add the tokenized variant:
import json, re
from langchain_core.documents import Document
from langchain_ollama import OllamaEmbeddings
from langchain_chroma import Chroma
from langchain_community.retrievers import BM25Retriever
from langchain_community.cross_encoders import HuggingFaceCrossEncoder
from langchain_classic.retrievers import EnsembleRetriever, ContextualCompressionRetriever
from langchain_classic.retrievers.document_compressors import CrossEncoderReranker
from common import *
# The default preprocess_func is str.split(): case-sensitive, punctuation stays glued to words.
def tokenize(text):
return re.findall(r"[a-z0-9]+", text.lower())
chunks, questions = load_chunks(), load_questions()
docs = [Document(page_content=c["text"], metadata={"source": c["source"]}, id=c["id"]) for c in chunks]
store = Chroma("k8s", embedding_function=OllamaEmbeddings(model=EMBED_MODEL), persist_directory="lc_chroma")
dense = store.as_retriever(search_kwargs={"k": POOL})
bm25 = BM25Retriever.from_documents(docs, k=POOL, preprocess_func=tokenize)
hybrid = EnsembleRetriever(retrievers=[dense, bm25], weights=[0.5, 0.5])
rerank = ContextualCompressionRetriever(
base_compressor=CrossEncoderReranker(model=HuggingFaceCrossEncoder(model_name=RERANK_MODEL), top_n=K),
base_retriever=hybrid)
summary, all_rows = [], []
for name, r in {"bm25-tokenized": bm25, "hybrid-tokenized": hybrid, "hybrid-tokenized+rerank": rerank}.items():
rows = run_setup("langchain+chroma", name, questions,
lambda q, r=r: [(d.metadata["source"], d.page_content) for d in r.invoke(q)][:K])
all_rows += rows
summary.append(summarise("langchain+chroma", name, rows))
print(json.dumps(summary[-1]))
write_csv("lc_tokenized_retrieval.csv", all_rows)
write_csv("lc_tokenized_summary.csv", summary)
Run it and print the summary:
~/rag/bin/python lc_bm25_tokenized.py | tee lc_tokenized.log
column -s, -t lc_tokenized_summary.csv
Keyword recall for BM25 alone jumped from 0.64 to 0.88:

With the tokenizer, LangChain hybrid reaches 0.76 against 0.78 for LlamaIndex, one question apart, at the same 33 ms p50 as before. Paraphrase recall for BM25 stayed at 0.48 because lowercasing does not stem: “evict” and “eviction” are still different tokens. If you run LangChain hybrid search on technical docs, pass a tokenizer; the default leaves recall on the table for free. Adding a stemmer such as PyStemmer to tokenize() is the next thing we would try.
The tokenized hybrid plus rerank came out at 0.84, below the untokenized 0.88. That is two questions, inside the noise of this set, and a reminder not to read a ranking into differences of that size. The reranker sees a different candidate pool when BM25 changes, and with 20 candidates and 5 slots the order at the edge can flip either way.
Step 6: Measure what bge-reranker-base costs
The reranker is BAAI/bge-reranker-base, an MIT-licensed cross-encoder that reads the question and each candidate chunk together and outputs a relevance score. Both stacks load it through sentence-transformers on CPU and score the full fused pool, up to 20 chunks per query. It added 1,328 ms at p50 on LangChain and 1,290 ms on LlamaIndex over plain hybrid.
- Recall gain: +0.18 on LangChain (35 to 44 questions) and +0.06 on LlamaIndex (39 to 42). The weaker the first-stage retriever, the more the reranker recovers.
- Paraphrase gain: 0.52 to 0.80 on LangChain and 0.64 to 0.76 on LlamaIndex, the largest per-kind change in the whole benchmark.
- Cost driver: CPU time scales with pool size times chunk length; halving
POOLto 5 per retriever should roughly halve the rerank time (we did not measure it), but it also halves the candidates the reranker can rescue.
Whether 1.3 seconds is acceptable depends on what follows it. In a chat pipeline the LLM call took seven to eight times longer on this box, so the reranker is a small share of the wait. For a search box that must answer in 100 ms, it is out of budget on CPU, and plain LlamaIndex hybrid at 21 ms with 0.78 recall is the better trade. A GPU would change this calculation, but we did not measure one, so treat the CPU figure as the ceiling.
Step 7: Measure end-to-end latency with gemma3:4b
Both scripts take --answer to run the full pipeline: retrieve with the named setup, put the top 5 chunks in the shared prompt and ask gemma3:4b at temperature 0 with a 4,096 token context. We ran the hybrid plus rerank setup for all 50 questions on each stack, one after the other so they never shared the CPU:
~/rag/bin/python lc_stack.py --answer hybrid+rerank -n 50 > lc_gen.log
~/rag/bin/python li_stack.py --answer hybrid+rerank -n 50 > li_gen.log
A short script summarises the per-question timings and counts how often the model answered that it did not know:
vim ~/bench/genstats.py
It reuses the nearest-rank percentile from common.py, written inline here so the file runs on its own:
import json, math, statistics
def pct(v,p):
v=sorted(v); return v[max(0,math.ceil(p/100*len(v))-1)]
for f in ["lc_answers.jsonl","li_answers.jsonl"]:
rows=[json.loads(l) for l in open(f)]
for k in ["retrieve_ms","total_ms","eval_tokens"]:
v=[r[k] for r in rows if r.get(k) is not None]
if v: print(f, k, "n=",len(v),"p50=",statistics.median(v),"p95=",pct(v,95),"mean=",round(statistics.mean(v),1))
dk=sum(1 for r in rows if "don't know" in r["answer"].lower() or "does not contain" in r["answer"].lower())
print(f,"dont_know=",dk)
Run it against the two answer files:
~/rag/bin/python genstats.py
Our LangChain script records retrieval and total time separately, while the LlamaIndex query engine reports only the total:

The median question took 11.9 seconds on LangChain and 11.5 seconds on LlamaIndex, with p95 at 15.7 and 14.5 seconds. Retrieval with reranking was 1.4 seconds of that, so about 88 percent of the wait is the language model. The answers were short, a median of 18.5 output tokens, which means most of the 10 seconds went into reading the roughly 1,000-token prompt of five chunks, not into writing. On CPU, prompt length is the lever: cutting to 3 chunks would save more time than any retriever change in this article. Each stack declined to answer, saying the context did not contain it, on 3 of 50 questions.
To time the other three setups end to end, we rebuilt the lab on a fresh VM of the same size, with the same pinned versions and the corpus at the same commit. The retrieval scores came out identical to the first box, setup for setup. Each setup then answered all 50 questions on each stack. Both scripts always write to the same answer file, so keep a copy of the hybrid plus rerank answers first and rename the file after every run:
cp lc_answers.jsonl "lc_answers_hybrid+rerank.jsonl"
cp li_answers.jsonl "li_answers_hybrid+rerank.jsonl"
for s in dense bm25 hybrid; do
~/rag/bin/python lc_stack.py --answer "$s" -n 50 > "lc_gen_$s.log" 2>&1
mv lc_answers.jsonl "lc_answers_$s.jsonl"
~/rag/bin/python li_stack.py --answer "$s" -n 50 > "li_gen_$s.log" 2>&1
mv li_answers.jsonl "li_answers_$s.jsonl"
done
cp "lc_answers_hybrid+rerank.jsonl" lc_answers.jsonl
cp "li_answers_hybrid+rerank.jsonl" li_answers.jsonl
The last two lines put the hybrid plus rerank answers back where Step 8 expects them. On the second VM we copied those two files over from the first box instead. A second summary script prints one row per stack and setup:
vim ~/bench/genstats_all.py
It uses the same nearest-rank p95 and the same refusal test as genstats.py, which counts answers containing “don’t know” or “does not contain”, so the refusal column is a floor rather than an exact count:
import json, math, statistics
def pct(v,p):
v=sorted(v); return v[max(0,math.ceil(p/100*len(v))-1)]
print(f"{'stack':<6}{'setup':<15}{'n':>3}{'p50 ms':>10}{'p95 ms':>10}{'dont_know':>11}")
for stack in ["lc","li"]:
for s in ["dense","bm25","hybrid","hybrid+rerank"]:
rows=[json.loads(l) for l in open(f"{stack}_answers_{s}.jsonl")]
v=[r["total_ms"] for r in rows]
dk=sum(1 for r in rows if "don't know" in r["answer"].lower() or "does not contain" in r["answer"].lower())
print(f"{stack:<6}{s:<15}{len(v):>3}{statistics.median(v):>10.0f}{pct(v,95):>10.0f}{dk:>11}")
Run it from the same directory as the answer files:
~/rag/bin/python genstats_all.py
All eight rows came back with 50 answers each:
stack setup n p50 ms p95 ms dont_know
lc dense 50 9529 15970 7
lc bm25 50 10061 14537 10
lc hybrid 50 9685 13053 5
lc hybrid+rerank 50 11858 15682 3
li dense 50 18027 24027 1
li bm25 50 19425 22686 1
li hybrid 50 29046 45537 0
li hybrid+rerank 50 11515 14538 3
The two hybrid+rerank rows come from the first VM’s answer files, because the rerun of that setup was stopped at 34 of 50 questions; the other six rows are from the second VM.
On LangChain the cheap setups answer in about 9.5 to 10 seconds at the median, so the reranker adds roughly 2 seconds end to end while lifting recall@5 from 0.70 to 0.88. The LlamaIndex rows without the reranker are slower because the query engine’s default compact mode sends every retrieved node to the model: 10 chunks for dense and BM25, and up to 20 from hybrid fusion, against 5 on LangChain. Twenty chunks do not fit in a 4,096-token window, so compact mode splits them and makes extra refine calls to the model. The reranker’s top_n=5 is what trims the LlamaIndex prompt back to five chunks, which is why its rerank row is the fastest on that stack.
- Compare like for like: before you time LlamaIndex without a reranker, set
similarity_top_k=5on the dense and BM25 retrievers, and on theQueryFusionRetrieveritself for hybrid, or the stack pays for two to four times the context. Build separate top-5 retrievers for those timing runs, because the same objects feed fusion and the reranker. - Read the refusal column too: LangChain’s BM25 setup declined 10 of 50 questions, the price of its weak tokenizer, while the LlamaIndex hybrid, with up to 20 chunks, never declined and took 45.5 seconds at p95.
The faithfulness scores in the next step use the hybrid plus rerank answers, the configuration we would ship on either stack.
Step 8: Score faithfulness with ragas and a local judge
Retrieval recall says whether the right chunk arrived; faithfulness says whether the answer stuck to the chunks it got. ragas asks a judge model to split the answer into claims. It then checks each claim against the retrieved context. The score is the share of supported claims. We used qwen2.5:7b through Ollama’s OpenAI-compatible endpoint as the judge, on the first 25 answers from each stack.
ragas gets its own virtual environment, with langchain-community held below the release the RAG stacks use. The reason is the first error in the next section:
python3 -m venv ~/ragas-env
~/ragas-env/bin/pip install --upgrade pip
# https://pypi.org/project/ragas/#history
~/ragas-env/bin/pip install "ragas==0.4.3" "langchain-community<0.4" openai
The scoring script uses the collections API, the recommended path since ragas 0.4: llm_factory wraps an OpenAI client pointed at Ollama, and Faithfulness.ascore() takes the question, the answer and the contexts directly, with no dataset object:
vim ~/bench/ragas_faithfulness.py
Add the judge loop. It prints one line per answer and a JSON summary at the end:
import asyncio, json, statistics, sys, time
from openai import AsyncOpenAI
from ragas.llms import llm_factory
from ragas.metrics.collections import Faithfulness
JUDGE = "qwen2.5:7b"
answers_file, n = sys.argv[1], int(sys.argv[2])
client = AsyncOpenAI(base_url="http://127.0.0.1:11434/v1", api_key="ollama")
llm = llm_factory(JUDGE, provider="openai", client=client, temperature=0, max_tokens=2048)
metric = Faithfulness(llm=llm)
async def main():
rows = [json.loads(l) for l in open(answers_file)][:n]
scores, failed = [], 0
for r in rows:
t0 = time.perf_counter()
try:
res = await metric.ascore(user_input=r["question"], response=r["answer"],
retrieved_contexts=r["contexts"])
scores.append(res.value)
print(r["qid"], round(res.value, 3), f"{time.perf_counter() - t0:.1f}s", flush=True)
except Exception as e:
failed += 1
print(r["qid"], "FAILED", type(e).__name__, str(e)[:160], flush=True)
print(json.dumps({"file": answers_file, "judge": JUDGE, "scored": len(scores), "failed": failed,
"mean": round(statistics.mean(scores), 3),
"median": round(statistics.median(scores), 3),
"below_0.5": sum(1 for s in scores if s < 0.5)}))
asyncio.run(main())
Score the first 25 answers from each stack:
~/ragas-env/bin/python ragas_faithfulness.py lc_answers.jsonl 25 > ragas_lc.log
~/ragas-env/bin/python ragas_faithfulness.py li_answers.jsonl 25 > ragas_li.log
tail -n 1 ragas_lc.log ragas_li.log
Each answer took the judge 23 to 66 seconds on CPU, so the 50 judgements ran for about 29 minutes, two to five times longer per answer than gemma3 took to write it. The last line of each log holds the summary:

Mean faithfulness came out at 0.807 for LangChain and 0.827 for LlamaIndex, with a median of 1.0 and 4 of 25 answers below 0.5 on each. The 0.02 gap is half an answer and means nothing. All 50 judgements completed with no parse failures, which a 7B judge does not always manage. Treat these numbers as noisy: 25 samples per stack and a small judge are enough to spot trends, not to rank stacks.
Reading the low scores one by one shows why. Four of the eight answers under 0.5 were “I don’t know” replies, which contain no supported claims and score 0, so a model that declines correctly is punished. Two more were the bare answer “403 Forbidden” to q12, scored 0 on both stacks even though the chunk holding it ranked first. A one-phrase answer gives the judge no statement to verify. One was a correct subtraction: both stacks answered “20 seconds” to the same shutdown question, and the judge gave LangChain 0.0 and LlamaIndex 1.0 for identical text. The useful catch was LlamaIndex q06, where the retriever missed the gold chunk and gemma3 lifted the 1.22 release number from an unrelated API Priority and Fairness chunk. The judge scored it 0, and a reader would have been misled.
- Filter refusals first: score “I don’t know” answers separately, or the faithfulness mean partly measures how often retrieval failed.
- Expect judge variance: the same answer scored 0.0 on one stack and 1.0 on the other, with only the fifth context chunk different. The judge reacts to the whole context set, so spot-check low scores by hand before you compare configurations.
Faithfulness and recall answer different questions, so keep both. Recall told us which retriever to fix; faithfulness flagged the answer that dressed a wrong chunk up as a fact.
Errors on current LangChain, LlamaIndex and ragas versions
Every error below came up on the test box with the pinned versions from Step 1. Most come from code written for older releases, which is still what most RAG tutorials and many LLM-generated snippets contain.
ModuleNotFoundError: No module named ‘langchain_community.chat_models.vertexai’
Installing ragas into the same environment as the current LangChain stack breaks even import ragas. The ragas LLM wrapper imports a Vertex AI chat class from langchain-community, and the community package’s current release no longer ships that module:

pip does not catch this because ragas does not cap its langchain-community requirement. Install ragas in a separate environment with "langchain-community<0.4", as in Step 8, which resolved to the 0.3.31 release and imports cleanly. The judge only talks to Ollama over HTTP, so it does not need to share packages with the RAG stacks.
ModuleNotFoundError: No module named ‘langchain.retrievers’
LangChain v1 moved the legacy retrievers, chains and text splitters out of the main package. Two imports that most hybrid search examples still use now fail, and from langchain.chains import RetrievalQA fails the same way with No module named 'langchain.chains':

The LangChain v1 migration guide says the old retrievers and chains now live in langchain-classic. The other rows below are the partner packages that worked on the test box. The mappings this benchmark needed:
| Old import | Current import | Package |
|---|---|---|
langchain.retrievers.EnsembleRetriever | langchain_classic.retrievers.EnsembleRetriever | langchain-classic |
langchain.retrievers.ContextualCompressionRetriever | langchain_classic.retrievers.ContextualCompressionRetriever | langchain-classic |
langchain.text_splitter | langchain_text_splitters | langchain-text-splitters |
langchain.chains.RetrievalQA | langchain_classic.chains.RetrievalQA, or an LCEL chain such as prompt | llm | langchain-classic or langchain-core |
langchain_community.vectorstores.Chroma | langchain_chroma.Chroma | langchain-chroma |
langchain_community.embeddings.OllamaEmbeddings | langchain_ollama.OllamaEmbeddings | langchain-ollama |
The last two still import from the community package but print deprecation warnings: a LangChainDeprecationWarning for the Ollama embeddings class, and a DeprecationWarning on every langchain_community import saying the package is being sunset. This benchmark still imports BM25Retriever and HuggingFaceCrossEncoder from langchain_community and lives with the warning; pin the package so the sunset does not surprise you.
ImportError: cannot import name ‘VectorStoreIndex’ from ‘llama_index’
Pre-0.10 LlamaIndex examples import from the top-level package, which is now an empty namespace. The exact message on the test box ended with (unknown location). Every core class lives under llama_index.core, and each integration is its own pip package with its own module path, for example llama-index-vector-stores-faiss imports as llama_index.vector_stores.faiss.
LlamaIndex embeds metadata you did not ask for
This one raises no error, which makes it worse. A TextNode with metadata embeds source: architecture/nodes.md followed by the text unless the key is listed in excluded_embed_metadata_keys. In a comparison that means the two stacks embed different strings; in production it means file paths leak into similarity scores. Exclude metadata keys that carry no meaning for the query.
ChromaDB vs FAISS: which stack to pick
On retrieval quality the two stacks are a tie once each is configured properly: 0.88 against 0.84 with reranking and 0.76 against 0.78 for tokenized hybrid, both within two questions. The choice comes down to defaults, operations and the shape of your pipeline, not to a recall gap.
- LlamaIndex with FAISS: better out of the box. Its stemmed BM25 at 0.6 ms is the best cheap retriever we measured, and hybrid at 21 ms reaches 0.78 with no tuning. FAISS is an in-process index with no server and no metadata filtering beyond what you build, so it suits a fixed corpus that is rebuilt rather than updated.
- LangChain with ChromaDB: needs the tokenizer fix to match, then performs the same. Chroma persists documents, metadata and vectors together, supports filtering and incremental upserts, and can run as a server when several processes share one store.
- Either, with a reranker: if your answers go through an LLM anyway, add the cross-encoder. It was the single largest recall gain in both stacks, and on CPU it costs about an eighth of the generation time.
Whichever you pick, build a question set like ours before tuning anything. Fifty questions with verbatim evidence strings exposed a tokenizer default that cost LangChain BM25 9 questions, and no amount of reading the docs would have shown it. If your store needs to scale past one process, our Qdrant, Weaviate, Milvus and pgvector comparison covers the server-side options, and the Qdrant RAG pipeline with Ollama and LangChain shows the same retrieval pattern against a networked store. For a PostgreSQL-based setup, see self-hosted RAG with Ollama and pgvector; the same PostgreSQL server can also persist LangGraph threads in Postgres when an agent has to resume a conversation. If you are still deciding whether retrieval is the right tool at all, MCP vs RAG vs agent skills compares the three approaches. Readers who want the theory behind dense and sparse retrieval will find the strongest titles in our list of RAG and vector database books.