FullStack AI Hub
Studio
lesson depth
Mastery
not started · 0%

Query Rewriting and Routing

Transform and route queries while preserving user intent, policy context, and evaluation traceability.

Freshness: current•15 min read•Retrieval and Knowledge Systems

Key Learning Outcomes

  • ✓Explain the operating model behind Query Rewriting and Routing.
  • ✓Evaluate trade-offs and failure modes for Query Rewriting and Routing.
  • ✓Apply Query Rewriting and Routing to a production decision.
Full Technical Reference Document

Mental model

A production query understanding layer raises retrieval recall on vague, conversational, or multi-part questions by resolving pronouns, expanding internal acronyms, decomposing compound queries, and routing intents to specialized indexes—while strictly preserving user negations, exact IDs, metadata filters, and immutable raw-to-rewritten audit traces.

Raw query & session filters
Deterministic acronym & ID lock
Intent routing & sub-query split
Bounded parallel store dispatch
Merge RRF + attach raw provenance
Conceptual teaching model synthesized from:Introduction to Information RetrievalRetrieval-Augmented Generation for Knowledge-Intensive NLP Tasks

Learning outcomes

  • Combine fast deterministic normalization (acronym lookup, exact SKU/error-code regexes) ahead of bounded LLM rewriting or HyDE expansion.
  • Route queries selectively across heterogeneous backends (SQL/metrics warehouse, AST code search, hybrid policy docs) with low-latency fallbacks.
  • Preserve strict negation predicates, time ranges, and exact identifiers while tracing every rewrite step for debugging.

Theory

Real enterprise queries rarely arrive cleanly phrased for BM25 or dense embeddings: users type "why did Q3 APAC renewals drop compared to last year without EU exclusions?" or "ERR-4092 timeout after upgrade". Passing an un-rewritten pronoun query ("does it apply in Germany?") loses retrieval recall, whereas unleashing an unconstrained LLM rewriter often deletes exact error tokens (ERR-4092), flips without EU into positive EU, or invents nonexistent product versions. Production routers organize query transformation as a constrained multi-stage pipeline:

Transformation TechniqueLatency TaxBest Problem ClassMandatory Guardrail
Deterministic Regex + Acronym Map< 2 msExact ticket codes, error strings, known org acronymsBypass neural rewrite entirely on exact ID lookup
Conversational Coreference Rewrite150–350 msFollow-up turns ("what about tier 2 limits?")Inject only bounded last 2–3 turns; emit structured JSON filters
Multi-Query / Step-Back Split200–450 msCompound comparisons ("compare SOC2 vs HIPAA retention")Cap sub-queries <= 3; execute concurrently behind global timeout
Store / Metadata Router5–250 msStructured SQL vs. code symbol index vs. hybrid prose corpusRetain dual-route fallback onto general docs when confidence < 0.7
python
import re
from dataclasses import dataclass
​
EXACT_ID_RE = re.compile(r"\b(?:ERR-\d+|INC-\d+|CVE-\d{4}-\d+)\b")
DOMAIN_GLOSSARY = {
"k8s": "Kubernetes",
"kv": "key-value cache",
"soc2": "SOC 2 Type II compliance",
}
​
@dataclass(frozen=True)
class QueryPlan:
raw_query: str
locked_tokens: tuple[str, ...]
expanded_queries: tuple[str, ...]
target_stores: tuple[str, ...]
exclude_terms: tuple[str, ...]
​
def plan_deterministic_query(raw_query: str) -> QueryPlan:
"""Lock exact identifiers and negations cleanly before invoking optional neural expansion."""
locked = tuple(EXACT_ID_RE.findall(raw_query))
negations = tuple(re.findall(r"\b(?:without|excluding|not)\s+([A-Za-z0-9_-]+)", raw_query, flags=re.I))
​
tokens = raw_query.split()
expanded_words = [DOMAIN_GLOSSARY.get(tok.lower(), tok) for tok in tokens]
glossary_query = " ".join(expanded_words)
​
stores: list[str] = ["hybrid_docs"]
if locked:
stores.insert(0, "incident_exact_bm25")
if any(k in raw_query.lower() for k in ("revenue", "latency p95", "count", "how many")):
stores.append("metrics_sql_warehouse")
​
candidates = [raw_query]
if glossary_query != raw_query:
candidates.append(glossary_query)
return QueryPlan(
raw_query=raw_query,
locked_tokens=locked,
expanded_queries=tuple(dict.fromkeys(candidates)),
target_stores=tuple(dict.fromkeys(stores)),
exclude_terms=negations,
)

Trade-offs

LLM-based query decomposition and hypothetical document embeddings (HyDE) deliver large recall gains on underspecified conceptual queries and ambiguous cross-document comparisons, yet add 200–500 ms TTFT overhead ahead of vector retrieval and risk drifting away from terse literal identifiers. Deterministic dictionary expansion plus fast structured small-model routing adds minimal latency (&lt; 80 ms) and guarantees zero identifier mutation, while failing when conversational intent genuinely shifts mid-thread across implicit topics. Always running the literal original raw_query cleanly alongside any neural sub-queries guarantees deterministic lexical precision never regresses.

Failure modes and misconceptions

  • Dropping Negations and Metadata Predicates: Summarizing "policies excluding contractor accounts after 2025" into "contractor account policies" retrieves strictly false-positive matches.
  • Rewriting Exact Identifiers: Neural query expanders routinely normalize SKU-884A or ERR-4092 into generic English phrases, breaking sparse BM25 exact matching.
  • Unbounded Sub-Query Fan-Out: Letting an agent emit 10 parallel sub-queries per turn multiplies vector DB load 10x and overflows context budgets with redundant paragraphs.
  • Opaque Trace Loss: Logging only rewritten queries hides why downstream synthesis hallucinated; traces must store raw input, extracted filters, and per-route rank contributions.

Decision scenario

An internal developer portal mixes Jira incident tickets (INC-1042), structured latency telemetry SQL tables, and Markdown runbooks. Users report that queries containing exact kernel flags or "excluding staging" frequently miss obvious runbooks. Architect a deterministic-first query planner locking identifiers and negations before selective sub-query decomposition.

Reflect before revealing the guide

What constraints and trace artifacts must be preserved whenever a query rewriting layer modifies user input before retrieval?

Prerequisites & Related Concepts (3)

Private notes

0 words
Included In Free Course
Free · Verifiable Credential

FS-401RAG Engineer

Build evidence-carrying retrieval systems from ingestion and provenance through search reranking grounded generation and evaluation.

21 concepts~25h self-paced
Start Free Course
Weekly Engineering Dispatch

Get the weekly systems teardown

One technical note per week covering inference bottlenecks, retrieval harnesses, and commit-pinned teardowns.