What you will be able to do
- Explain why a raw user message is usually a weak retrieval query, and what query understanding does about it
- Classify a user query's intent and use that intent to route the request or choose a prompt template
- Turn entities in a query, such as product, date or region, into metadata filters or tool lookups
- Rewrite and expand vague or conversational queries so retrieval finds documents that use different terms
- Assemble a prompt that holds the user query, resolved facts and retrieved chunks, and choose what to leave out
Key concept
Query understanding — A step at the start of the RAG chain that reads the user's message before retrieval. It works out what the user wants (intent), pulls out the concrete values that narrow the search (key fields), and turns loose wording into terms the knowledge base actually uses. Every later step works from what this step produces.
1.Why the user's message is not yet a retrieval query
A user writes the way people talk: "my usual store", "last quarter", "that error again". A knowledge base is indexed by product names, dates, regions and the terms used in its manuals. Sending the raw message straight to retrieval sometimes works. It fails when the meaning sits in a reference the index cannot resolve, or in a word the documents never use.
For that reason, the RAG chain at inference time often starts with an optional preprocessing step that turns the message into a retrieval query. This step can put the query into a template, use another model to rewrite the request, or extract keywords to help retrieval. Retrieval then works from what this step returns, not from the user's original wording.
Query understanding does three jobs, and each one augments the final prompt in a different way:
- Intent: what the user wants done. This decides the route or the prompt template.
- Key fields: values such as a product, a time period or a region. These become retrieval filters or arguments to a lookup.
- Terms: the words used for search. They are rewritten or expanded so they match the documents' vocabulary.
Each of these jobs is an ordinary model task pointed at the query itself rather than at a document. Intent is a classification task, and key fields come from an extraction task. The foundation model task types (chat, embeddings, vision, reasoning) lesson covers picking a model for that kind of task. What matters here is that the task runs on the user's message, before anything is retrieved.
Checkpoint 1 of 9· Match them up
Query understanding does three jobs on the user's message before retrieval. Match each job to how its output is used in the RAG chain.
Tap a term, then the definition that fits it.
Intent is a classification task that selects the route or template. Key fields come from extraction and narrow the search as filters or lookup arguments. Terms are rewritten so that loose user wording matches how the knowledge base is indexed.
“Analyzing and transforming user queries to better represent intent and extract relevant information, such as filters or keywords, to improve the retrieval process.”Source: docs.databricks.com
2.Intent detection: deciding what the request is for
Intent detection sorts the query into one of a fixed set of categories that you define for the application. A customer-support bot might use "product information", "troubleshooting" and "account management". The category matters because each one needs different context. A troubleshooting question needs passages from the error knowledge base. An account question needs the customer's record. A product question needs catalog data. Once the intent is known, the chain can pick the right prompt template, retriever or tool instead of sending every request down the same path.
Intent also shapes what gets extracted next. With the intent "troubleshooting", the entities worth pulling out are product names and reported errors. With "account management", it is an account number. A common design runs these steps in order: classify the intent, extract entities based on that intent, then rewrite the query using both.
A single, carefully written call is efficient, and for simple queries it is often enough. Once one prompt has to classify, extract and rewrite all at once, splitting it into one call per job usually works better. Each step gets its own instructions and can be checked on its own, at the cost of extra latency. This rule applies to any prompt that tries to carry several complex logic steps at once.
| Step | What the LLM call does | Output passed on |
|---|---|---|
| Intent classification | Assigns the query to a predefined category | "product information", "troubleshooting" or "account management" |
| Entity extraction | Extracts the entities relevant to that intent | Product names, reported errors, account numbers |
| Query rewriting | Rewrites the original query using the intent and entities | A more specific and targeted retrieval query |
Checkpoint 2 of 9· Check yourself
A support bot's first LLM call labels the message "I can't see my invoices since I changed my billing email" as "account management". What should the chain do next?
The intent decides what context is needed and which entities to extract. An account management request needs the customer's record, so the account number is the field to pull out. Product names and errors fit troubleshooting, and rewriting comes after extraction, not before.
“Based on the identified intent, use another LLM call to extract relevant entities from the query, such as product names, reported errors, or account numbers.”Source: docs.databricks.com
Sources1
3.Turning key fields into retrieval filters and lookups
Key fields are the parts of a query that can narrow the search exactly. Examples are a time period ("reports from 2023"), a product or category ("laptops"), and a geographic entity such as a city name or country code. Filter extraction finds these values and passes them to retrieval as extra parameters. The similarity search then runs only over the matching subset of chunks. Filtering cuts the search space sharply and improves both precision and recall. A filter on make, model and year keeps a Camry brake question from pulling in Corolla manuals.
The simplest extractor is deterministic code that looks for known values and builds a filter string. It is fast and predictable. However, it only catches values someone thought to code for.
# Parse query for filter criteria
def extract_filters(user_query):
filter_parts = []
if "Toyota" in user_query:
filter_parts.append('make = "Toyota"')
if "2023" in user_query:
filter_parts.append('year = 2023')
return " AND ".join(filter_parts) if filter_parts else NoneThe LLM-driven alternative hands extraction to the model. With dynamic_filter=True, a VectorSearchRetrieverTool lets the agent read "brake issues in my 2023 Toyota Camry". The agent then extracts the entities, generates the filter, and runs a search that combines semantic matching with exact filtering. The columns list matters here: the agent can only filter on metadata that the index holds.
vector_search_tool = VectorSearchRetrieverTool(
index_name="catalog.schema.car_manuals_index",
# Optional: specify columns to return
columns=["content", "make", "model", "year", "chunk_id"],
# Optional: set number of results
num_results=10,
# Optional: use hybrid (keyword + vector) search
query_type="HYBRID",
# Enable LLM-generated filters based on the agent's understanding of the query
dynamic_filter=True,
)Each extracted value has to arrive in a form the index accepts. Standard endpoints take a Python dictionary in which the key holds both the column and the operator, and multiple keys are combined with AND. Storage-optimized endpoints take a SQL-like string, like the one extract_filters returns.
| Phrase in the user query | Extracted field | Filter |
|---|---|---|
| "a Toyota or a Honda" | make (string, OR) | {"make": ["Toyota","Honda"]} |
| "the 2024 model" | year (integer) | {"year": 2024} |
| "under 55,000" | price (numeric) | {"price <=": 55000} |
| "listed in Q1 2024" | listed_at (timestamp range) | {"listed_at >=": "2024-01-01T00:00:00Z", "listed_at <": "2024-04-01T00:00:00Z"} |
| "in stock" | in_stock (boolean) | {"in_stock": true} |
Some key fields do not name a document at all. They point to a record. "My usual store" means nothing to a vector index, but the application may already hold the user's default store ID. "Q3 EMEA revenue" is a set of rows in a revenue table, not a paragraph in a PDF. The knowledge base behind retrieval can be a vector store, a keyword search or a SQL database. An agent can also call tools for external data or actions, such as a function lookup_order(customer_id, order_id) when a user asks for their order status. In these cases the right move is to extract the field, resolve it against the system that holds the answer, and put the resolved value and the returned data into the prompt. For a stock check, that means the store ID and the current inventory for the SKU. For a revenue comparison, it means the EMEA figures for both quarters plus whatever an anomaly service flagged.
Asking the user is a fallback, not the first step. When a lookup fails, for example when the tool replies "invalid order number", the agent can retry or ask the user for the correct ID. If the application can already resolve the reference from stored preferences or the query itself, a clarifying question before trying only adds a turn. Asking the model to guess the value is worse, because the prompt then carries a made-up fact.
Checkpoint 3 of 9· Check yourself
Your team changes the query-understanding prompt so the LLM pulls "EMEA" out of questions and passes {"region": "EMEA"} to the retriever. Answers still draw on chunks from every region. What is the most likely cause?
Filter extraction is not a prompt-only change. The data pipeline has to store the metadata field on every chunk, and the retriever has to accept and apply the filter. With no region column, there is nothing to filter on.
“The metadata extraction step should ensure that the relevant metadata fields are available for each document/chunk”Source: docs.databricks.com
Checkpoint 4 of 9· Check yourself
A shopper asks, "Is the blue rain jacket in stock at my usual store?" Their profile holds a default store ID, and the agent has an inventory lookup tool. How should the chain build the prompt?
Resolve the reference against the system that holds it first, and put the resolved value and the returned data into the prompt. Ask the user only when a lookup fails. Guessing puts a made-up fact in the prompt, and dumping the data adds context the query does not need.
“If that tool responds with "invalid order number," the agent can retry or prompt the user for the correct ID”Source: docs.databricks.com
Checkpoint 5 of 9· Exam question
A retail chatbot receives: "Can you check if the blue XL hoodie is in stock at my usual store?" The application already has the user's stored preferences, including their default store ID and past purchase history. Which strategy best augments the prompt sent to the LLM so it can answer accurately?
Correct answer: A — Resolve "usual store" to the default store ID held in the user's stored preferences, then add that store ID and the current inventory data for the matching blue XL hoodie SKU at that store to the prompt context sent to the model.
- A. Correct. The application already holds the user's default store ID, so "usual store" can be resolved deterministically from the stored preferences. Adding that store ID together with current inventory for the matching SKU at that store gives the model the specific, user-relevant facts it needs to answer accurately.
- B. Incorrect. The nearest store by IP geolocation is only an approximation of where the user is right now, and it can differ from the store the user means by "usual store". The stored default store ID is the exact reference, so the inventory data would be for the wrong location and the answer could be wrong.
- C. Incorrect. Purchase frequency is only a proxy for the usual store, and it can differ from the default store ID the user saved. Leaving the model to infer the store also means the inventory lookup depends on a model-generated choice and an extra step, when the application already holds the exact store ID.
- D. Incorrect. A semantic product search can find the right hoodie SKU, but it never resolves "usual store". The model receives inventory spread across the store network without being told which location the user means, and it cannot work that out, even though the application has the default store ID.
Checkpoint 6 of 9· Exam question
A financial analyst assistant receives: "Compare Q3 revenue for our EMEA region against the same quarter last year, and flag anything unusual." The application has access to a structured revenue database and an anomaly-detection service. Which augmentation approach best prepares the prompt sent to the LLM?
Correct answer: A — Parse the message for the region and periods, query the revenue database for EMEA figures in Q3 and the same quarter last year, run the anomaly-detection service on those figures, and add the figures and flagged anomalies to the prompt.
- A. Correct. The message names the region and both periods, so the application can pull exactly the EMEA figures for Q3 and the prior-year quarter from the structured database. It can then run the anomaly-detection service on that data and give the LLM the numbers and the flagged items to write up.
- B. Incorrect. The EMEA figures are scoped correctly, but the application skips the anomaly-detection service it has and leaves outlier detection to the LLM. Judging what counts as unusual from two quarterly totals is unreliable, and it is the work the service exists to do before the prompt is built.
- C. Incorrect. The periods are right, but the query and the anomaly check run on company-wide totals. Regional movements are averaged out, so an EMEA-specific swing may not show up, and the LLM never receives the EMEA figures the user asked to have compared.
- D. Incorrect. Running detection on the latest data for each region does not compare Q3 with the same quarter a year earlier. EMEA is retrieved only if it happens to be flagged, so the prompt may lack the two EMEA figures the user asked to have compared.
4.Query rewriting and term expansion
Query rewriting turns a user query into one or more queries that better express what the user meant, phrased so retrieval is more likely to find the right documents. It helps most when the query is complex or ambiguous, or when the user's words differ from the words in the documents. Typical rewrites include:
- turning earlier turns of a multi-turn chat into a standalone question, so "what about the other one?" becomes something that can be searched;
- correcting spelling mistakes;
- replacing words or phrases with synonyms to reach more relevant documents.
Rewriting works best after intent and entities are known. A support bot that has classified a message as troubleshooting, and has extracted "Model Serving" and the reported error, can produce a targeted query such as "My RAG chain is failing to deploy on Model Serving, I'm seeing the following error…". That query is far easier to search than the user's original wording.
Query expansion. The chain generates variations such as "automobile repair", "vehicle servicing" and "auto maintenance" and searches with all of them. This improves recall, because documents that use different terminology are now found.
Query expansion searches with several versions of the query instead of one. There are two ways to use the variations. You can run a separate search for each one and merge the results, or you can join them all into a single retrieval query. The variations are usually generated in the query understanding step. That is why expansion needs changes in both places: the step that produces the variations and the retriever that consumes them.
# Use LLM to expand query with synonyms and related terms
def expand_query(user_query):
prompt = f"""Generate 3 variations of this search query including synonyms:
Query: {user_query}
Return only the variations, one per line."""
variations = llm.generate(prompt).split('\n')
# Search with original + variations
all_results = []
for query in [user_query] + variations:
results = index.similarity_search(query_text=query, num_results=10)
all_results.extend(results)
# Deduplicate and return
return deduplicate_results(all_results)Notice that the original query is kept alongside the variations. Expansion adds ways to match. It does not replace what the user wrote. The deduplication step matters because overlapping searches return the same chunk several times. Without it, the prompt would contain repeated passages.
Checkpoint 7 of 9· Fill the gap
This helper expands a query with LLM-generated synonyms before searching. Which token fills the blank so the loop searches the right set of queries?
# Use LLM to expand query with synonyms and related terms
def expand_query(user_query):
prompt = f"""Generate 3 variations of this search query including synonyms:
Query: {user_query}
Return only the variations, one per line."""
variations = llm.generate(prompt).split('\n')
# Search with original + variations
all_results = []
for query in [ ? ] + variations:
results = index.similarity_search(query_text=query, num_results=10)
all_results.extend(results)
# Deduplicate and return
return deduplicate_results(all_results)Expansion adds ways to match without replacing what the user wrote, so the user's original query is searched along with each generated variation, and the merged results are then deduplicated. Passing the prompt or one variation would drop the user's own wording from the search.
Source: docs.databricks.com5.Assembling the augmented prompt
The augmented prompt is what the LLM actually receives. It combines the user's query with the retrieved context in a template that tells the model how to use each part, often with extra instructions about response format. Everything query understanding produced ends up here: the intent decides which template is used, the resolved key fields and tool results become stated facts, and the chunks found with the rewritten or expanded query become the context.
A typical layout gives the model its role in the system message. The user message then contains the retrieved context first, followed by the instruction to answer the user's request using that context. For the support message "My Model Serving endpoint keeps returning 429 errors when I load test it", the chain extracts "Model Serving", "429 errors" and "load test", queries a retriever over the troubleshooting knowledge base, and puts the matching passages into the prompt before the user's question. Retrieval is what lets the answer draw on proprietary information that was never part of the model's training data.
More context is not the same as better context. How many chunks to retrieve, and how to combine them with the query, can significantly affect answer quality. Three bad choices fail in different ways:
- Dumping everything: an entire purchase history or a full revenue export for every region. The model has to find the relevant entities itself, and they get lost in the noise.
- A static passage on every request: the same rate-limit paragraph added whatever the message says. The model talks about throttling even when the user reported a different failure.
- No retrieval at all: relying on the model's pretrained knowledge for internal procedures. The answer cannot reflect the organisation's own knowledge base.
The prompt that works holds only what this query needs: the resolved fields, the data looked up for them, and the passages found for the extracted terms.
Checkpoint 8 of 9· Match them up
Four teams build the augmented prompt for the same support bot in different ways. Match each design to the result it most likely produces.
Tap a term, then the definition that fits it.
More context is not the same as better context. The amount of retrieved material and how it is combined with the query drive answer quality. Dumping everything buries the relevant entities, a static passage ignores what the user actually asked, and skipping retrieval leaves out proprietary knowledge. The working prompt holds only the context resolved and retrieved for this query.
“how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”Source: docs.databricks.com
Checkpoint 9 of 9· Exam question
A support-ticket assistant receives the raw user message: "My Model Serving endpoint keeps returning 429 errors when I load test it." Before sending this to the LLM, a developer wants to extract the key terms ("Model Serving", "429 errors", "load test") and pull matching sections from an internal troubleshooting knowledge base to inject into the prompt. Which approach best accomplishes this prompt augmentation step?
Correct answer: A — Pull the product name, error code and activity out of the message, search an index of the internal support documentation with those terms, and place the best-matching passages in the prompt ahead of the user's text before calling the model.
- A. Correct. Identifying the product, error code and activity in the message, using them to search the internal support documentation, and placing the best-matching passages in the prompt ahead of the user's text is the prompt augmentation step the developer wants. The model then answers from the company's own troubleshooting content, selected for this specific message.
- B. Incorrect. A persona prompt plus pretrained knowledge involves no term extraction and no lookup in the internal knowledge base, so nothing is added to the prompt from that source. The model's general knowledge of Model Serving rate limits can be outdated or differ from the company's own troubleshooting guidance, which is why the developer wants matching sections injected.
- C. Incorrect. Querying the endpoint's inference table returns request data, not troubleshooting sections from the internal knowledge base. A SQL translation of the message also does not match key terms against documentation text. The prompt ends up with raw log rows instead of the guidance the developer wants to inject.
- D. Incorrect. A fixed passage is not selected from the extracted terms, so it is the same on each request whether or not the message concerns rate limits. It does draw on the knowledge base, but it cannot supply the sections that match a given message. A user reporting a different failure would still get quota guidance and no relevant content.
Sources
(6)
Every claim above is drawn from one of these pages, quoted as it was written on the date shown.
- 1.
“Using the user query directly as a retrieval query can work for some queries.”
↩︎ Why the user's message is not yet a retrieval query“Use an LLM to classify the user's query into predefined categories”
↩︎ Intent detection: deciding what the request is for“use another LLM call to extract relevant entities from the query, such as product names, reported errors, or account numbers”
↩︎ Intent detection: deciding what the request is for“Although this approach may add some latency to the overall process, it can allow for more fine-grained control”
↩︎ Intent detection: deciding what the request is for“Filter extraction involves identifying and extracting these filters from the query and passing them to the retrieval step as additional parameters.”
↩︎ Turning key fields into retrieval filters and lookups“Query rewriting involves translating a user query into one or more queries that better represent the original intent.”
↩︎ Query rewriting and term expansion“Replacing words or phrases in the user query with synonyms to capture a broader range of relevant documents”
↩︎ Query rewriting and term expansion“Use the extracted intent and entities to rewrite the original query into a more specific and targeted format”
↩︎ Query rewriting and term expansion“The multiple variations of a retrieval query are typically generated in this step.”
↩︎ Query rewriting and term expansion“Analyzing and transforming user queries to better represent intent and extract relevant information, such as filters or keywords, to improve the retrieval process.”
↩︎ Key concept“Filter extraction must be done in conjunction with changes to both metadata extraction data pipeline and retriever chain components.”
↩︎ Exam trap 1“either conducting individual searches for each expanded query, or using a concatenation of all expanded search queries in a single retrieval query”
↩︎ Exam trap 3“Analyzing and transforming user queries to better represent intent and extract relevant information, such as filters or keywords, to improve the retrieval process.”
↩︎ Checkpoint“Based on the identified intent, use another LLM call to extract relevant entities from the query, such as product names, reported errors, or account numbers.”
↩︎ Checkpoint“The metadata extraction step should ensure that the relevant metadata fields are available for each document/chunk”
↩︎ Checkpoint - 2.https://docs.databricks.com/aws/en/agents/tutorials/ai-cookbook/fundamentals-inference-chain-ragOfficial docs
“This can involve formatting the query within a template, using another model to rewrite the request, or extracting keywords to aid retrieval.”
↩︎ Why the user's message is not yet a retrieval query“augmenting the user's query with the retrieved context, in a template that instructs the model how to use each component”
↩︎ Assembling the augmented prompt“determining how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”
↩︎ Assembling the augmented prompt“determining how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”
↩︎ Exam trap 4“how many chunks to retrieve in step 2 and how to combine them with the user's query in step 3 can significantly impact”
↩︎ Checkpoint - 3.
“Filtering dramatically reduces search space and improves both precision and recall.”
↩︎ Turning key fields into retrieval filters and lookups“Impact: Improves recall by finding documents with different terminology.”
↩︎ Query rewriting and term expansion - 4.
“multiple keys in the same dict are combined with AND logic”
↩︎ Turning key fields into retrieval filters and lookups - 5.
“The user's request is used to query an outside knowledge base such as a vector store, keyword search, or SQL database.”
↩︎ Turning key fields into retrieval filters and lookups“RAG can include proprietary information not initially used to train the LLM”
↩︎ Assembling the augmented prompt - 6.
“If the user wants their order status, the agent might call a function lookup_order(customer_id, order_id).”
↩︎ Turning key fields into retrieval filters and lookups“Reason about how best to respond, optionally deciding whether to call tools for external data or actions.”
↩︎ Turning key fields into retrieval filters and lookups“the agent can retry or prompt the user for the correct ID”
↩︎ Exam trap 2“If that tool responds with "invalid order number," the agent can retry or prompt the user for the correct ID”
↩︎ Checkpoint