Advanced RAG retrieval strategies
LlamaIndex narrowly leads LangChain for built-in query transformation in RAG pipelines.
It depends
LangChain is also recommended for flexible, multi-step workflows with broad tool integrations.
Brands AI mentions
Built-in query rewriting, multi-query retrieval, and knowledge graph methods for RAG
Flexible, modular workflows with broad integrations and query transformation methods
Also mentioned rarely: Cohere Rerank, BGE-Reranker, Deepset, Microsoft GraphRAG, Neo4j, Azure AI Search, LangChain Python, LlamaIndex Connectors, ColBERT, OpenSearch, Qdrant, Pinecone, Ragas, DeepEval, RAGFlow, Haystack, Elasticsearch, Dataworkz, LangChain4j, CRAG, Self-RAG, Weaviate, Jina Reranker, Mongodb, PostgreSQL, pgvector, SPLADE, Cloudflare, IngestIQ, Anthropic, Tavily, BAAI/bge-reranker-v2-m3, Microsoft, LightRAG, Microsoft Semantic Kernel, Gemini, Microsoft Synthetic Data Showcase, Meilisearch, Databricks, CrewAI, MixedBread, Langfuse, NetworkX, TruLens, BGE-M3
- LlamaIndexChatGPTChatGPT 82%Google AI ModeGoogle AI Mode 75%
- LangChainChatGPTChatGPT 79%Google AI ModeGoogle AI Mode 69%
- LangChain LangGraphChatGPTChatGPT 50%Google AI ModeGoogle AI Mode 50%
- Haystack (deepset)ChatGPTChatGPT 53%Google AI ModeGoogle AI Mode 16%
- DSPyChatGPTChatGPT 35%Google AI ModeGoogle AI Mode 9%
What decides this topic
Buying criteria from head-to-head AI comparisons
- SupportLlamaIndex100%
- FeaturesLlamaIndex50%
- BreadthLlamaIndex100%
Questions and answers
Google AI ModeNov 21, 2026
Transitioning from a naive RAG setup to an agent-ready, high-precision retrieval architecture requires
moving past single-shot embedding similarity. Modern production benchmarks show that moving from basic RAG to advanced strategies significantly boosts factual accuracy.The most effective advanced RAG retrieval strategies to implement in an LLM agent framework include:
1. Hybrid Retrieval (Dense + Sparse)
- What it is: Combines semantic dense vector search (via embeddings) with exact-match sparse keyword search (using BM25 or SPLADE), merging the results via Reciprocal Rank Fusion (RRF).
- Why it matters for agents: Dense search handles conceptual queries and paraphrasing, while sparse search reliably catches exact serial numbers, proper nouns, and acronyms that embeddings miss. It is the mandatory production baseline as detailed on Atlan's Advanced RAG Guide.
Additional Core Strategies
Further optimization techniques include secondary Cross-Encoder Reranking to filter noise, Contextual Retrieval to inject macro-context via LLM headers, and Adaptive RAG & Query Routing for dynamic request handling . For complex reasoning and self-correction, frameworks can integrate GraphRAG for knowledge graph traversal or Corrective RAG (CRAG) to trigger web search fallbacks on low-confidence queries. Detailed architectural breakdowns and frameworks can be explored directly via Atlan's Advanced RAG Guide.
To help tailor this to your stack:
- What LLM orchestration framework are you currently using (e.g., LangGraph, LlamaIndex, CrewAI, or custom)?
- What type of data are you retrieving from (dense technical manuals, chat logs, relational DBs, or long-form PDFs)?
Pages cited in this answer 1
ChatGPTNov 21, 2026
Advanced RAG retrieval strategies for LLM agent frameworks
The most effective approach to advanced Retrieval-Augmented Generation (RAG) is to move beyond simple vector similarity search and build a multi-stage, adaptive retrieval architecture.
For an LLM agent framework, I recommend combining semantic retrieval, hybrid search, query transformation, reranking, contextual retrieval, and iterative agent-driven retrieval.
The goal is not simply to retrieve more documents. It is to retrieve the smallest set of highly relevant, diverse, authoritative evidence that allows your agent to answer accurately.
1. The most effective advanced RAG strategies
Here are 12 strategies worth considering, ranked by their practical impact and implementation value.
Tier 1: High-impact retrieval techniques
1. Hybrid search (BM25 + vector search)
(Highest-priority implementation)
Combine dense semantic retrieval with sparse keyword retrieval.
- Dense search captures meaning and conceptual similarity.
- BM25 captures exact terms, identifiers, product names, error codes, and technical terminology.
- Merge results using Reciprocal Rank Fusion (RRF).
Best for: Enterprise knowledge bases, technical documentation, code repositories, and heterogeneous datasets.
Anthropic's experiments found hybrid retrieval consistently stronger than embeddings alone.
2. Cross-encoder reranking
Retrieve 30–100 candidate chunks using inexpensive retrieval methods, then score each query-document pair with a reranker.
- Initial retrieval optimizes recall.
- Reranking optimizes precision.
- Send only the highest-quality 5–15 chunks to the LLM.
Best for: Reducing irrelevant context and improving answer grounding.
This is one of the strongest additions to a conventional RAG pipeline.
3. Multi-query retrieval and query expansion
Have your agent generate several alternative versions of the original question.
Example:
Original: "How do I improve agent memory?"
Generated queries:
- Long-term memory architectures for LLM agents.
- Vector database memory retrieval optimization.
- Semantic memory versus episodic memory.
- Memory consolidation and retrieval in autonomous agents.
Retrieve independently for each query, deduplicate, and fuse the results.
Best for: Ambiguous questions, terminology mismatches, and broad research tasks.
4. Contextual retrieval
Enrich each chunk with a short description of its parent document and its position within the document before indexing.
Instead of indexing:
"It increased by 15%."
Index something like:
"Within the 2025 customer acquisition report, the conversion rate increased by 15%."
This prevents chunks from losing their original meaning when separated from their source documents.
Best for: Large documentation repositories, reports, manuals, and enterprise knowledge bases.
Anthropic reported a 67% reduction in top-20 retrieval failures when combining contextual embeddings, contextual BM25, and reranking in its experiments.
Tier 2: Advanced and agent-oriented retrieval
5. HyDE (Hypothetical Document Embeddings)
Ask the LLM to generate a hypothetical answer or document that would answer the user's question. Embed that generated text and use it as a retrieval query.
Why it works: Questions and relevant documents often use different language. A hypothetical document can bridge that semantic gap.
Best for: Natural-language questions that don't closely resemble the indexed content.
Important: The hypothetical document is a retrieval aid, not evidence. Never treat its claims as factual.
6. GraphRAG (Knowledge Graph Retrieval)
Extract entities, relationships, and connections from your documents to build a knowledge graph.
Example:
Customer → Purchased → Product → Manufactured By → CompanyYour agent can retrieve connected information rather than isolated text chunks.
- Local graph search: entity-specific questions.
- Global graph search: themes and relationships across a large corpus.
- Hybrid graph + vector retrieval: combines structured relationships with semantic search.
Best for: Multi-hop reasoning, organizational intelligence, complex dependencies, and relationship-heavy datasets.
7. Agentic RAG (Iterative retrieval)
Let your agent decide whether it has enough information to answer.
Typical workflow:
- Retrieve initial evidence.
- Analyze evidence gaps.
- Generate follow-up queries.
- Retrieve additional documents.
- Validate evidence coverage.
- Generate the final answer.
Best for: Research agents, autonomous workflows, complex troubleshooting, and multi-step questions.
![Fix RAG Retrieval Errors with CRAG, LangGraph, and Milvus
8. Corrective RAG (CRAG)
Evaluate retrieved documents before allowing them into the generation stage.
- Relevant: use the evidence.
- Partially relevant: refine retrieval.
- Irrelevant: try another retrieval source or strategy.
- Insufficient evidence: abstain or ask for clarification.
Best for: High-accuracy applications where hallucinations are costly.
9. Maximum Marginal Relevance (MMR)
Select results that are both relevant to the query and different from each other.
Without MMR, the top 10 chunks might contain nearly identical passages.
With MMR, the agent receives a broader set of complementary evidence.
Best for: Research, summarization, broad questions, and multi-document synthesis.
10. Hierarchical retrieval (Parent-child retrieval)
Index small chunks for precise matching, but return their larger parent sections for context.
Example:
- Document: 100 pages.
- Parent: 1 chapter.
- Child: 300-token chunk.
- Retrieval: match child, return child plus relevant parent context.
Best for: Long documents, technical manuals, contracts, and research papers.
11. Contextual compression
Retrieve a relatively large candidate set, then extract only the passages that directly support the query.
Techniques include:
- LLM-based evidence extraction.
- Sentence-level relevance filtering.
- Redundancy removal.
- Token-aware context compression.
Best for: Reducing token consumption and keeping agent context focused.
12. Adaptive retrieval (Self-RAG)
Teach your agent to decide when retrieval is necessary and how much retrieval is needed.
- Simple question: answer directly.
- Knowledge-dependent question: retrieve.
- Complex question: decompose and retrieve iteratively.
- Weak evidence: retry or abstain.
Best for: Cost-efficient autonomous agents that handle different classes of questions.
2. Recommended architecture for an advanced RAG agent
Rather than implementing all 12 strategies independently, I would combine them into a modular retrieval pipeline.
1. User query
Original question + conversation history + agent state
2. Intelligent query router
Classify intent, complexity, domain, and retrieval requirements
Query rewriting
Multi-query / HyDE / decomposition
Metadata filtering
Tenant / domain / date / permissions
3. Parallel retrieval layer
Dense vector search
BM25 search
Knowledge graph
Agent memory
4. Fusion and reranking
RRF → deduplication → cross-encoder → MMR
5. Evidence processing
Parent-child expansion → contextual compression → provenance
6. Evidence quality evaluator
Relevance / coverage / freshness / source authority
7. Agent generation
Grounded answer + citations + confidence + abstention
If evidence is insufficient, return to query planning and retrieve again
How I would implement the retrieval controller
The important architectural decision is to make retrieval strategies independently callable tools rather than hardcoding them into one monolithic RAG chain.
For example, your agent could expose these tools:
Tool Responsibility semantic_searchDense vector retrieval keyword_searchBM25 retrieval hybrid_searchCombined retrieval graph_searchRelationship-based retrieval query_expansionGenerate alternative queries rerank_resultsRelevance scoring expand_contextRetrieve parent document sections compress_contextExtract useful evidence evaluate_evidenceDetermine retrieval quality retrieve_moreIterative retrieval This makes it possible for the agent to select the appropriate retrieval strategy dynamically.
3. Example implementation in Python
Here is a simplified orchestration pattern using framework-independent interfaces.
pythonfrom dataclasses import dataclass from typing import Any @dataclass class RetrievalResult: documents: list[Any] confidence: float strategy: str class AdvancedRAG: def __init__( self, vector_store, bm25, reranker, query_expander, evidence_evaluator, compressor, ): self.vector_store = vector_store self.bm25 = bm25 self.reranker = reranker self.query_expander = query_expander self.evidence_evaluator = evidence_evaluator self.compressor = compressor async def retrieve(self, query: str, top_k=10): # 1. Generate alternative queries queries = await self.query_expander.expand(query) # 2. Run semantic and keyword retrieval candidates = [] for q in queries: dense = await self.vector_store.search(q, k=30) sparse = await self.bm25.search(q, k=30) candidates.extend(dense) candidates.extend(sparse) # 3. Deduplicate and fuse rankings candidates = reciprocal_rank_fusion(candidates) # 4. Neural reranking ranked = await self.reranker.rank( query=query, documents=candidates, ) # 5. Diversify evidence diverse = maximal_marginal_relevance( query=query, documents=ranked, lambda_mult=0.7, k=top_k, ) # 6. Compress retrieved context context = await self.compressor.compress( query=query, documents=diverse, ) # 7. Evaluate evidence quality evaluation = await self.evidence_evaluator.evaluate( query=query, documents=context, ) return RetrievalResult( documents=context, confidence=evaluation.confidence, strategy="hybrid_adaptive", )This is an orchestration skeleton: the fusion, MMR, and component interfaces need concrete implementations for your selected vector database and agent framework.
Important improvement: Add an adaptive retrieval loop
Instead of treating retrieval as a one-shot operation, add a bounded feedback loop:
pythonasync def agentic_retrieve(query, rag, max_iterations=3): current_query = query evidence = [] for iteration in range(max_iterations): result = await rag.retrieve(current_query) evidence.extend(result.documents) evaluation = await rag.evaluate_coverage( query=query, evidence=evidence, ) if evaluation.is_sufficient: break current_query = await rag.generate_followup_query( original_query=query, evidence=evidence, missing_information=evaluation.gaps, ) return { "evidence": evidence, "sufficient": evaluation.is_sufficient, "iterations": iteration + 1, }In production, deduplicate evidence across iterations, enforce a latency/token budget, and retain source provenance. An agent should never interpret its own confidence score as proof that evidence is correct.
4. Evaluation: How to know which strategies actually work
One of the biggest mistakes in RAG development is evaluating only the final generated answer.
You should evaluate retrieval and generation independently.
Metric What it measures Priority Recall@K Whether relevant evidence is retrieved Critical Precision@K How much retrieved content is relevant High MRR Position of the first relevant result High nDCG@K Quality of the overall ranking High Context recall Whether evidence covers the answer Critical Faithfulness Whether claims are supported by evidence Critical Answer correctness Whether the final answer is correct Critical Citation accuracy Whether citations support their claims High Latency and cost Operational efficiency High These metrics should be tracked across a representative test set, including questions with missing information and multi-hop reasoning.
Recommended experimentation strategy
Run an ablation study:
Experiment Retrieval configuration A Basic vector search B Vector + BM25 C Vector + BM25 + RRF D Hybrid + reranking E Hybrid + contextual retrieval + reranking F E + query expansion G F + adaptive agentic retrieval H G + GraphRAG Compare all configurations on the same evaluation dataset.
Do not assume that adding more techniques automatically improves results. For example, HyDE and multi-query expansion may add cost without helping precise numerical or identifier-based questions. A 2026 benchmark illustrates why domain-specific testing matters.
5. Technology stack recommendations
Here is a practical selection of technologies for implementing these capabilities.
Component Technologies to consider Agent orchestration LangGraph / LlamaIndex Vector database Qdrant / Pinecone Hybrid search Elasticsearch / OpenSearch Knowledge graph Neo4j Reranking Cohere Rerank / BGE Reranker Evaluation Ragas / DeepEval Observability Langfuse Useful documentation:
- LangGraph agent orchestration
- LlamaIndex retrieval framework
- Microsoft GraphRAG
- Qdrant documentation
- Ragas evaluation
- Langfuse observability
6. My recommended implementation roadmap
If I were engineering a production-grade LLM agent framework, I would implement the following in stages.
-
Phase 1 — Retrieval foundation
(Implement first)
- Hybrid vector + BM25 search.
- Reciprocal Rank Fusion.
- Cross-encoder reranking.
- Metadata filtering.
- Context-aware chunking.
-
Phase 2 — Retrieval intelligence
- Multi-query expansion.
- Query decomposition.
- HyDE.
- Parent-child retrieval.
- MMR diversification.
-
Phase 3 — Autonomous retrieval
- Agentic retrieval loops.
- Evidence quality evaluation.
- Corrective retrieval.
- Adaptive retrieval routing.
- Query-specific retrieval strategies.
-
Phase 4 — Advanced knowledge retrieval
- GraphRAG.
- Long-term agent memory.
- Entity and relationship extraction.
- Hierarchical document summaries.
- Cross-document multi-hop reasoning.
-
Phase 5 — Production optimization
- Retrieval caching.
- Query and embedding caching.
- Evaluation pipelines.
- Latency and cost optimization.
- Source attribution and access-control enforcement.
7. Three additional engineering considerations
These are especially important when building an agent framework rather than a standalone RAG application.
1. Retrieval security
Treat retrieved documents as untrusted data. Enforce tenant and user permissions before retrieval, prevent retrieved instructions from overriding system instructions, and preserve source-level access controls during parent-document expansion.
2. Memory versus knowledge retrieval
Keep different types of information in different retrieval systems:
- Episodic memory: previous interactions and experiences.
- Semantic memory: persistent facts and concepts.
- Procedural memory: workflows, instructions, and skills.
- External knowledge: documentation, databases, and research.
3. Retrieval observability
Log every retrieval decision, including:
- Original and rewritten queries.
- Retrieval strategy selected.
- Candidate documents and scores.
- Reranking decisions.
- Evidence rejected.
- Retrieval iterations.
- Token consumption and latency.
- Final citations.
This makes it possible to identify precisely why an agent failed.
8. Final recommendation
(My recommended production combination)
For the best balance of retrieval accuracy, reasoning capability, and implementation complexity, I would start with:
Advanced hybrid agentic RAG
Layer Recommended strategy Query processing Query rewriting + decomposition Initial retrieval Dense + BM25 Fusion Reciprocal Rank Fusion Ranking Cross-encoder reranking Context Parent-child + contextual retrieval Diversity MMR Complex reasoning GraphRAG Validation Corrective RAG Orchestration Adaptive agentic retrieval Evaluation Ragas + custom benchmarks The biggest performance gains will generally come from getting hybrid retrieval, contextual indexing, and reranking right before introducing more complex agentic behavior.
One question that would help me tailor the architecture:
What framework are you currently building your LLM agent system with?
1. Agent framework
2. Vector database
3. Primary objective
Additional details (optional)
[Input placeholder: e.g. Python, multiple agents, millions of documents] (Current value unavailable.)
[Design my RAG architecture]
I can then develop a more concrete architecture with component interfaces, retrieval algorithms, Python implementation, agent tool definitions, and evaluation benchmarks.
Pages cited in this answer 16
- anthropic.comContextual retrieval in AI systems \ Anthropic
- link.springer.comEvaluating retriever reranker pairings in RAG based on quality and efficiency trade-offs | Discover Computing | Springer Nature Link
- aclanthology.org4.1 RAG Design Space
- llmbook.icsgen-ai.orgSection 35.1: Hybrid Retrieval & Re-Ranking
- anthropic.comContextual retrieval in AI systems \ Anthropic
- llmbook.icsgen-ai.orgSection 35.2: Query Transformation, HyDE & Multi-step Retrieval
- mdpi.comRetrieval Augmented Generation for Large Language Models: A Methodological Survey
- link.springer.comFrom knowledge retrieval to generation: a comprehensive study of RAG's architectures, evolution, and applications | Artificial Intelligence Review | Springer Nature Link
- manning.comChapter 14: Evaluating RAG systems · Retrieval Augmented Generation, The Foundational Ideas | Manning
- arxiv.org[2604.01733] From BM25 to Corrective RAG: Benchmarking Retrieval Strategies for Text-and-Table Documents
- docs.langchain.comLangGraph overview - Docs by LangChain
- docs.llamaindex.aiLlamaIndex Framework, by the makers of LlamaParse | Developer Documentation
- microsoft.github.ioWelcome - GraphRAG
- qdrant.techDocumentation - Qdrant
- docs.ragas.ioRagas
- langfuse.comOpen Source AI Engineering Platform - Langfuse
ChatGPTOct 13, 2026
For advanced RAG (retrieval-augmented generation) techniques like sentence-window retrieval, my top recommendation is LlamaIndex. It is particularly well suited to detail-oriented questions where retrieving the exact sentence matters, but the language model also needs the surrounding context to answer accurately.
The key is to distinguish between frameworks that provide specialized retrieval components out of the box and frameworks that give you more flexibility to build a custom retrieval pipeline.
Best RAG frameworks for fine-grained retrieval
1. LlamaIndex
(Best overall for sentence-window retrieval)
LlamaIndex provides a dedicated
SentenceWindowNodeParserandMetadataReplacementNodePostProcessor. It embeds individual sentences for precise matching, then expands retrieved sentences to include neighboring context before generation.Best for: Technical documentation, lengthy PDFs, policy documents, research papers, and questions about specific facts or exceptions.
Official sentence-window example
2. LangChain
Best for flexible, customized RAG pipelines
LangChain is a strong option when retrieval is one part of a larger application involving agents, tools, custom retrievers, and multiple data sources. You can implement sentence-window retrieval with custom indexing and retrieval logic, although the exact LlamaIndex workflow is not its primary out-of-the-box approach.
Best for: Agentic RAG, complex application workflows, and teams already using the LangChain ecosystem.
Official LangChain documentation
3. Haystack
Best for explicit, production-oriented pipelines
Haystack uses modular components connected into defined pipelines. This makes it attractive when you want to control document preprocessing, retrieval, reranking, and answer generation as distinct stages. Sentence-window behavior can be implemented through custom components or preprocessing and metadata logic.
Best for: Production search, inspectable pipelines, and systems requiring explicit control over each retrieval stage.
Official Haystack documentation
The strongest direct evidence for sentence-window retrieval is LlamaIndex's own implementation and example, which specifically targets more fine-grained retrieval in large documents.
How sentence-window retrieval improves accuracy
Consider a user asking: “What exception applies to the 30-day retention policy?”
A conventional RAG system might retrieve a large chunk that discusses retention generally, while the exact exception is buried elsewhere in that chunk. Sentence-window retrieval makes the matching sentence the retrieval target, then restores neighboring sentences so the answer retains its meaning.
1. Index individual sentences
Create embeddings for small, precise units of text rather than only large chunks.
2. Retrieve the matching sentence
“The standard retention period is 30 days, except where a legal hold applies.”
3. Expand the context window
Include adjacent sentences explaining legal holds, scope, and related conditions.
4. Generate a grounded answer
Answer the question using the precise match and its surrounding context.
LlamaIndex implements this pattern with its sentence-window parser and metadata replacement postprocessor. Its documentation also describes using a window of neighboring sentences around each retrieved sentence.
Other retrieval techniques worth combining
For genuinely detail-oriented questions, I would evaluate more than sentence windows alone.
Technique What it adds When to use it Sentence-window retrieval Precise matching plus local context Exact facts, exceptions, definitions Parent-child retrieval Searches small child chunks but returns a larger parent section Long documents with related explanations Hybrid search Combines semantic vector search and keyword/BM25 search Exact terminology, IDs, names, clause numbers Reranking Reorders retrieved passages by relevance to the question Similar passages or subtle distinctions Metadata filtering Restricts search by document, date, section, or category Large, structured knowledge bases These techniques are complementary. For example, hybrid retrieval can locate a clause containing a specific identifier, while reranking and sentence-window expansion help select and interpret the relevant passage.
My recommended architecture
For a system where correctness on specific questions matters more than keeping the implementation minimal, I would start with:
Document ingestion
Parse PDFs, preserve headings, tables and metadata
Fine-grained indexing
Sentence embeddings + parent/section relationships
Hybrid retrieval
Vector similarity + keyword search + metadata filters
Rerank and expand
Rerank candidates, then restore sentence-window or parent context
Grounded answer with citations
Answer from retrieved evidence and identify source passages
Bottom line: Choose LlamaIndex if advanced document retrieval is your primary concern. Choose LangChain if the retrieval system is part of a broader agent application. Choose Haystack if explicit, modular pipelines are a priority.
Whichever you choose, benchmark it on your actual questions using retrieval recall, answer correctness, citation accuracy, latency, and cost. A framework's built-in features are useful, but the quality of document parsing, retrieval configuration, and evaluation will ultimately determine how well it handles fine-grained questions.
Pages cited in this answer 5
- developers.llamaindex.aiMetadata Replacement + Node Sentence Window | Developer Documentation
- developers.llamaindex.aiNode Postprocessor Modules | Developer Documentation
- python.langchain.comLangChain overview - Docs by LangChain
- docs.haystack.deepset.aiIntroduction to Haystack | Haystack Documentation
- llamaindex.openml.ioNode Parser Modules | OpenML Learn | LlamaIndex
ChatGPTSep 23, 2026
If your main criterion is built-in query-transformation techniques, I’d look closely at Haystack and LlamaIndex; LangChain is also strong, but its query-transformation functionality is more distributed across retrievers/chains.
A useful comparison:
Framework Query rewriting / expansion Multi-query HyDE Query fusion Pipeline composability Haystack Strong ✅ QueryExpander✅ Good Excellent LlamaIndex Very strong ✅ ✅ Excellent Excellent LangChain Strong ✅ ✅/custom ✅ Excellent My take
For a RAG system where query transformation is a first-class pipeline stage, I'd lean toward Haystack. Its current components explicitly support LLM-based query expansion through
QueryExpander, including multi-query retrieval for both text/BM25 and embedding retrievers.It also has a built-in HyDE implementation: the query is transformed into hypothetical documents, embedded, and used for retrieval.
That makes patterns like this fairly natural:
User query │ ├── Query rewrite │ ├── Query expansion → q1, q2, q3 │ ├── HyDE │ └── Original query │ ▼ parallel retrieval │ ▼ merge / dedupe │ ▼ reranker │ ▼ LLMHaystack's pipeline model is particularly nice here because these can be explicit, inspectable components rather than hidden inside a chain.
LlamaIndex is probably the one I'd investigate first if you want the broadest collection of sophisticated retrieval/query-transformation strategies. It's especially attractive if you expect to experiment with things like query decomposition, query fusion, sub-question generation, and multiple retrieval strategies.
LangChain is a good choice if you're already heavily invested in its ecosystem. Its advantage is ecosystem breadth and easy composition, rather than necessarily having the cleanest dedicated "query transformation framework."
What I'd choose
- Starting a new RAG pipeline: Haystack
- Researching/experimenting with lots of retrieval strategies: LlamaIndex
- Already using LangChain: stay with LangChain unless query transformation is becoming a major architectural concern
One important point: don't assume query rewriting automatically improves retrieval. I'd benchmark at least:
- original query
- LLM rewrite
- multi-query expansion
- HyDE
- rewrite + reranking
Measure retrieval recall@k / context recall separately from final answer quality. Otherwise an apparently better answer can hide a retrieval regression.
If you tell me whether your corpus is technical docs, enterprise documents, legal/medical text, or general web-like content, I can give you a more concrete recommendation and a suggested transformation pipeline.
Google AI ModeSep 23, 2026
When it comes to out-of-the-box, comprehensive query transformations, LlamaIndex has the most robust and dedicated built-in query transformation modules compared to other orchestration frameworks like LangChain.
While LangChain treats query rewriting mostly as a recipe you piece together using prompt templates and runnables, LlamaIndex treats query transformation as a first-class citizen with dedicated abstractions, multi-step workflows, and pre-packaged strategies.
Top Framework Options for Query Transformation
Framework Built-in Approach Best Use Case Key Trade-offs LlamaIndex First-class QueryTransformmodules (single-step, multi-step, HyDE, and sub-question decomposition).Advanced RAG pipelines requiring structured query decomposition or multi-intent mapping out of the box. Steeper learning curve and more opinionated abstractions. LangChain Flexible prompt-based chains, custom LCEL runnables, and multi-query retriever wrappers. Highly customized architectures where you want granular control over prompt text and LLM calls. Requires manual assembly; fewer "magical" drop-in transformation classes. Azure AI Search Cloud-native semantic ranking and built-in query rewriting capabilities at the database layer. Enterprise setups tightly coupled with Azure infrastructure. Vendor lock-in and less portable across vector databases. Key LlamaIndex Query Transformation Modules
- HyDE (Hypothetical Document Embeddings): Generates a hypothetical answer first, then embeds that answer to search for real chunks with matching semantics.
- Multi-Queries / Query Expansion: Rewrites a single user input into multiple diverse perspectives or sub-questions to maximize recall through ensemble retrieval.
- Sub-Question Query Engine: Automatically breaks a complex, multi-part user query into isolated sub-questions, routes them to distinct data sources, and synthesizes the final response.
- Step-Back Prompting: Abstracts a specific query into a broader, high-level concept query to catch overarching thematic context.
If you want, let me know:
- Which vector database or retriever you are currently using
- Whether your primary issue is missing context (low recall) or irrelevant noise (low precision)
I can share a quick code snippet or recommend the specific transformation module that fits your setup best.
Top head-to-head comparisons
Since Jul 5Data through Nov 21, 2026Based on 66 AI answers
For agents: this page as Markdown, https://parse.gl/topics/advanced-retrieval-strategy-implementation.md. JSON, MCP · free for the last 90 days, checks from $0.01
This page
Read and search
Connect
npx -y parse-gl check <domain>Copy the CLI commandAn agent can save work before signup: POST https://agent.parse.gl/v1/workspaces
What it costs
Prices: https://parse.gl/pricing.md
Map of the site: https://parse.gl/llms.txt