A BM25 retrieval pipeline in Haystack without any API

MediumRetrieval-augmented generation (RAG)RAG

Goal: Building the retrieval stage of RAG and running it locally.

Python — example.py
from haystack import Document, Pipeline
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
from haystack.document_stores.in_memory import InMemoryDocumentStore

store = InMemoryDocumentStore()
store.write_documents([
    Document(content="MONAI framework for medical imaging deep learning", meta={"lib": "monai"}),
    Document(content="Ultralytics YOLO for real-time object detection", meta={"lib": "ultralytics"}),
    Document(content="PennyLane for quantum machine learning and differentiable circuits", meta={"lib": "pennylane"}),
])
pipe = Pipeline()
pipe.add_component("retriever", InMemoryBM25Retriever(document_store=store, top_k=1))
for q in ["medical imaging segmentation", "quantum circuits"]:
    doc = pipe.run({"retriever": {"query": q}})["retriever"]["documents"][0]
    print(q, "->", doc.meta["lib"], round(doc.score, 3))

Code explanation

We store the documents in an InMemoryDocumentStore and use a BM25 retriever inside a Pipeline. This part needs no language model; to complete RAG, a PromptBuilder and a generator (local or through an API) are added after the retriever.

Requirements

Shell
pip install haystack-ai

How to run

Save the code in a file example.py then run it:

Shell
python example.py

Output recorded during testing

medical imaging segmentation -> monai 2.481
quantum circuits -> pennylane 2.399

This example was actually run and tested on 21 November 2026 on a CPU — haystack-ai 3.5.0, python 3.13.18

Libraries used

Related examples