Haystack composes retrieval and language-model components into explicit pipelines. A useful first exercise is retrieval without a hosted model: it makes the document-store/retriever contract visible before adding generation.
Version and installation
This example uses Python 3.12 and Haystack 2.9.0. It intentionally does not mix the legacy farm-haystack, haystack.nodes, or FARMReader API with Haystack 2 components.
python3.12 -m venv .venv
.venv/bin/pip install haystack-ai==2.9.0
A complete local retrieval pipeline
Save this as retrieve.py:
from haystack import Document, Pipeline
from haystack.document_stores.in_memory import InMemoryDocumentStore
from haystack.components.retrievers.in_memory import InMemoryBM25Retriever
store = InMemoryDocumentStore()
store.write_documents([
Document(content="Haystack is developed by deepset."),
Document(content="A retriever selects relevant documents for a query."),
])
pipeline = Pipeline()
pipeline.add_component("retriever", InMemoryBM25Retriever(document_store=store))
result = pipeline.run({"retriever": {"query": "Who develops Haystack?", "top_k": 1}})
documents = result["retriever"]["documents"]
assert len(documents) == 1
assert "deepset" in documents[0].content
print(documents[0].content)
Run .venv/bin/python retrieve.py. The expected line is Haystack is developed by deepset. No API key or downloaded reader model is needed. This validates a sparse retrieval path; it does not yet extract or generate an answer.
Conceptual illustration; labels describe responsibilities, not a deployment specification.
Add answer generation separately
A generator can consume selected documents and a question through a prompt builder. An extractive reader instead identifies an answer span. Those are different tasks with different outputs, dependencies, and evaluation requirements. A vector index is also not automatically compatible with a sparse BM25 retriever.
For a larger corpus, test document splitting, duplicate handling, access filtering, and empty retrieval. Keep a small set of queries with expected relevant documents so a component change can be evaluated independently of the language model.
Version boundaries
The project repository is the version reference for this exercise. The migration guide describes newer API generations; check the selected documentation version before adopting examples. Remove the local .venv after the exercise if it is no longer needed.