A context set is the domain knowledge that powers
QueryData.
It defines how your business logic works before your application goes live, so
that QueryData can answer natural language questions with near-100% accuracy
and low online latency.
While domain context can take many forms, context sets support three specialized context types:
- Query templates: Pre-approved SQL queries for common business questions.
- Query facets: Modular filters, such as "starter family" or "ocean view," that attach dynamically to templates.
- Value searches: Entity lookups that map user phrases to exact database values and resolve ambiguity.
The following databases are supported:
- AlloyDB for PostgreSQL
- Cloud SQL for MySQL
- Cloud SQL for PostgreSQL
- Spanner
- Firestore with MongoDB compatibility
- Bigtable
What are context sets
You author and optimize context sets at design time by using the
context engineering agent.
The context engineering agent runs a representative golden benchmark through
QueryData, scores the results, and iteratively refines
(hill-climbs)
your context set. It then checks the final version against an unseen held-out
test set to avoid overfitting, and automatically uploads the context set to
Google Cloud.
Pairing your database with a curated context set delivers two core production benefits:
- Near-100% accuracy that generalizes: Database schemas describe tables and columns, but they can't tell a model what distance counts as "near" or what rating makes a school "good." Context sets ground QueryData in your organization's verified business rules, while parameterized patterns let a compact context set generalize across phrasing variations, filter combinations, and entity values.
- Fast online execution and low latency: Context engineering moves expensive
schema reasoning offline to design time:
- Context-matched execution with a context set: Fast single-pass execution through precompiled template matching and indexed value lookups.
- Zero-shot synthesis for unanticipated queries without templates: Takes 2 to 3 times longer because the model must explore schema metadata and synthesize SQL at runtime.
- Open agentic exploration using raw SQL tools: Often takes more than 30 seconds due to multi-turn trial-and-error queries and error correction loops.
Context placement architecture
When preparing a database for QueryData, place each type of domain knowledge in the context tier that matches its scope and retrieval behavior:
| Tier | Mechanism | What to include | Guardrails |
|---|---|---|---|
| Tier 1: Schema catalog comments | Inline databaseTableReferences schema field descriptions |
Terse column meanings, measurement units (such as cents compared to dollars, or UTC timestamps), closed enum values (for example, 'PENDING', 'SETTLED', 'FAILED'), and deprecation notes |
Injected whenever the table is in scope. Keep comments concise so they don't bloat the schema prompt. |
| Tier 2: Global prompt context | Outer orchestrator agent instructions (included in the QueryData prompt) or DataAgent system_instruction |
Cross-table invariants, default reporting timezones, global soft-delete filters (such as deleted_at IS NULL), merged-entity ID bridges, and historical era cutover dates |
Included on every request without top-K retrieval filtering. Keep concise (under 1,500 tokens). |
| Tier 3A: Query templates | templates in the context set JSON file |
8 to 25 composable multi-table join, aggregation, and grain backbones with $1, $2 parameter placeholders |
Strip all -- and /* ... */ comments so single-line JSON compaction does not comment out trailing SQL. Avoid hardcoding conditional policy cutoffs into general templates. |
| Tier 3B: Query facets | facets in the context set JSON file |
Domain vocabulary, named metrics, and scoped policy or cohort filter predicates | Qualify every column with its table name (table_name.column_name, never table aliases) and state exact applicability boundaries in intent. |
| Tier 4: Value search queries | value_searches in the context set JSON file |
Fuzzy proper-noun, synonym, or high-cardinality entity resolution on lookup tables | Restrict to lookup or dimension tables (fewer than 100,000 rows) backed by a search index, with an inner derived subquery ORDER BY ... LIMIT 10. Don't use for small closed enums or unindexed fact tables. |
Context types in a context set
At runtime, QueryData combines all three context types in a single pass. For
example, if a user asks:
"Find me homes near good schools in Del Mar for a starter family with an ocean view"
QueryData resolves the request in four coordinated steps:
- A query template provides the core query structure for "homes near good
schools in
$1," applying business rules for distance (within 2 miles) and school ranking (5 or better). - Query facets inject modular filters for "starter family" (3 to 4 bedrooms, 2 or more bathrooms) and "ocean view" (vector similarity search).
- A value search finds
'Del Mar'in thecities.city_namecolumn and verifies its concept type. - Intent explanations combine into one certified explanation returned alongside the query results: "Homes in Del Mar within 2 miles of schools ranked 5 or better, with 3 to 4 bedrooms and an ocean view."
Query templates
Query templates are a curated set of representative natural language questions with corresponding SQL queries. They also include explanations to provide a certified rationale for how a question was interpreted.
For example, if a user asks a real estate application, "Find me homes near good schools in Del Mar," the database schema alone doesn't define what distance counts as "near," what rating makes a school "good," or how to rank matching properties. A query template captures that exact business interpretation, such as properties within 2 miles of a school ranked 5 or better ordered by a weighted score of ranking and proximity, and generalizes it to any city.
The main components of a query template are as follows:
- Example natural language question: A representative question asked in plain English, such as "Find me homes near good schools in Del Mar."
- Example SQL query: The verified SQL query that answers the question according to your business rules.
- Generalized question pattern: An auto-generated pattern with specific values replaced by generic descriptions, such as "Find homes near good schools in a given city," used to match incoming questions across phrasing variations.
- Intent explanation: A certified, plain-English explanation of the business
rules applied by the query, such as "Find homes in
$1within 2 miles of a school with a rank of at least 5." - Parameterized SQL query: The executable SQL query
corresponding to the intent explanation, using parameters such as
$1.
- Strip SQL comments: Remove all
--line comments and/* ... */block comments fromsqlandparameterized_sql, especially before compacting multi-line SQL onto a single JSON line where a--comment would comment out the rest of the statement. - Keep templates focused on structural backbones: Use templates to capture
reusable multi-table join, grouping grain, and aggregation patterns
(typically 8 to 25 templates per context set). Place conditional policy
cutoffs or cohort-specific
WHEREpredicates in query facets rather than hardcoding them into general templates.
Query facets
Query facets are a curated set of representative natural language conditions with corresponding SQL predicates. Facets manage filtering and conditions, which lets query templates perform faceted searches without requiring a separate template for every filter combination.
For example, a user can extend "Find me homes near good schools in Del Mar" with additional conditions:
- "...for a starter family," which maps to a structured SQL filter
such as
properties.bedrooms BETWEEN 3 AND 4 AND properties.bathrooms >= 2.0. - "...with an ocean view," which
uses database AI operators such as
AI.IFor vector similarity search across unstructured columns such aslisting_description,listing_image_embeddings, andcustomer_reviews.
The main components of a query facet are as follows:
- SQL snippet: The reusable SQL filter condition, such
as
properties.bedrooms BETWEEN 3 AND 4 AND properties.bathrooms >= 2.0. To avoid ambiguity, qualify every column name with its full table name—for example,table_name.column_name. Don't use bare column names or table aliases such ast1.column_name. - Generalized condition pattern: The natural language pattern that the facet matches, such as "Suitable for a starter family."
- Intent explanation: A certified explanation of the filter condition, returned as part of the overall answer rationale, including its exact applicability boundaries (for example, which entity cohort, status, or date window the condition applies to).
- Parameterized SQL snippet: The executable SQL fragment corresponding to the intent explanation.
Value search queries
Value search queries
are developer-defined queries that use match functions, such as exact match,
fuzzy trigram similarity, or semantic vector search, to find values and their
context within a database. QueryData uses value linking over these results to
identify which
tables and columns
contain a matching value, understand the value's concept type, correct
misspellings, and detect ambiguity before executing SQL.
For example, if a user asks a real estate application for "Westwod's sold
properties in the last month," a schema-only model might filter by
`WHERE name = 'Westwod'`
and return no results. Value search queries use fuzzy matching to resolve the
misspelling "Westwod" to the database value 'Westwood'. In addition, if
'Westwood' exists across multiple concept types in the database, such as
City, Municipality, and Brokerage, value linking detects the ambiguity so
that QueryData can ask the user to clarify which concept they meant rather
than guessing.
The main components of a value search query are as follows:
- Lookup query: A parameterized SQL query that uses exact match, n-gram similarity, or vector search to find a value within a column.
- Concept type: A semantic label, such as
City,Municipality, orBrokerage, that specifies what the value represents and which column to filter on. - Description: A brief description of the lookup logic.
When designing
value_searchesfor SQL databases, follow these rules to prevent runtime query failures and high-latency table scans:- Place
ORDER BYandLIMITinside a subquery, never at the top level: At runtime,QueryDatacan combine multiplevalue_searchesqueries withUNION ALL. To make sure that each query bounds its own index scan, placeORDER BY ... LIMIT 10inside a derived subquery (SELECT ... FROM (SELECT ... ORDER BY ... LIMIT 10)) rather than at the top level. Spanner GoogleSQL doesn't supportWITHclauses inside parenthesizedUNION ALLsubqueries. - Query indexed lookup tables, never large fact tables or closed enums: Run value searches only against small lookup or dimension tables (fewer than 100,000 rows) backed by a search index. Never run
value_searchesdirectly against multi-million-row fact or log tables, never compute embeddings inline per row on table columns at query time, and omitvalue_searchesfor small closed enums.
What's next
- Learn how to build context sets using the context engineering agent.
- Learn how to create or delete a context set in Spanner Studio.
- Place