Prev Next

AI / LangGraph LangChain Interview questions II

How do retrievers work in LangChain?

A Retriever in LangChain is a Runnable that takes a string query and returns a list of Document objects. It is the standard abstraction that decouples the RAG chain from the specific search mechanism — you can swap a vector store retriever for a keyword search retriever or a hybrid retriever without changing the chain.

Types of retrievers available in LangChain:

  • VectorStoreRetriever — most common; wraps a vector store and performs similarity (or MMR) search. Created via vectorstore.as_retriever()
  • MultiQueryRetriever — uses an LLM to generate multiple query variants, retrieves for each, deduplicates results
  • ContextualCompressionRetriever — post-processes retrieved documents to extract only the relevant sentences, reducing noise injected into the prompt
  • SelfQueryRetriever — parses natural language queries to extract both a semantic search string and metadata filters (e.g. 'articles from 2024 about Python')
  • ParentDocumentRetriever — retrieves small chunks for precision but returns their larger parent documents for fuller context
  • EnsembleRetriever — combines results from multiple retrievers (e.g. BM25 keyword + vector) using reciprocal rank fusion
from langchain_community.retrievers import BM25Retriever
from langchain.retrievers import EnsembleRetriever

bm25 = BM25Retriever.from_documents(docs, k=4)
vector = vectorstore.as_retriever(search_kwargs={"k": 4})

hybrid = EnsembleRetriever(retrievers=[bm25, vector], weights=[0.5, 0.5])
results = hybrid.invoke("How does LangChain memory work?")

What does ContextualCompressionRetriever do to retrieved documents?
What does EnsembleRetriever combine, and why is this useful?

More Related questions...

Show more question and Answers...


Comments & Discussions