> [!WARNING]
>
> **Preview**
>
>
> This feature is
>
> subject to the "Pre-GA Offerings Terms" in the General Service Terms section of the
> [Service Specific
> Terms](https://docs.cloud.google.com/terms/service-terms#1), and the
> [Additional Terms for Generative AI
> Preview Products](https://cloud.google.com/trustedtester/aitos).
>
> Pre-GA features are available "as is" and might have limited support.
>
> For more information, see the
> [launch stage descriptions](https://cloud.google.com/products/#product-launch-stages).

A context set is the domain knowledge that powers
[QueryData](https://docs.cloud.google.com/gemini/data-agents/querydata/bigtable/data-agent-overview.md.txt).
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](https://docs.cloud.google.com/gemini/data-agents/querydata/bigtable/build-context-sets.md.txt).
The context engineering agent runs a representative golden benchmark through
`QueryData`, scores the results, and iteratively refines
([hill-climbs](https://docs.cloud.google.com/gemini/data-agents/querydata/bigtable/build-context-sets.md.txt#hill-climbing))
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 single-table aggregation, filter, and grain backbones with `?` 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 a single bounded lookup query on a small lookup table (fewer than 100,000 rows). 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:

1. 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).
2. Query facets inject modular filters for "starter family" (3 to 4 bedrooms, 2 or more bathrooms) and "ocean view".
3. A value search finds `'Del Mar'` in the `cities.city_name` column and verifies its concept type.
4. 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 `$1` within 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` or `?`.

When authoring query templates for SQL databases, follow these best practices:

<br />

- **Strip SQL comments** : Remove all `--` line comments and `/* ... */` block comments from `sql` and `parameterized_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 single-table filter, grouping grain, and aggregation patterns (typically 8 to 25 templates per context set). Place conditional policy cutoffs or cohort-specific `WHERE` predicates 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 `CAST(CAST(properties.cf['bedrooms'] AS STRING) AS INT64) BETWEEN 3 AND 4 AND CAST(CAST(properties.cf['bathrooms'] AS STRING) AS FLOAT64) >= 2.0`.
- "...with an ocean view," which matches unstructured text columns such as `listing_description` and `customer_reviews`.

The main components of a query facet are as follows:

- SQL snippet: The reusable SQL filter condition, such as `CAST(CAST(properties.cf['bedrooms'] AS STRING) AS INT64) BETWEEN 3 AND 4 AND CAST(CAST(properties.cf['bathrooms'] AS STRING) AS FLOAT64) >= 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 as `t1.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](https://docs.cloud.google.com/gemini/data-agents/querydata/bigtable/build-context-sets.md.txt#targeted-authoring)
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 to find a value within a column.
- Concept type: A semantic label, such as `City`, `Municipality`, or `Brokerage`, that specifies what the value represents and which column to filter on.
- Description: A brief description of the lookup logic.

> [!NOTE]
> **Note:** GoogleSQL for Bigtable doesn't support set operations (`UNION ALL`), so value linking across multiple value search queries isn't supported. If a context set includes more than one value search query, the `QueryData` request succeeds, but values aren't linked.

When designing `value_searches` for SQL databases, follow these rules to prevent runtime query failures and high-latency table scans:

<br />

- **Keep each `value_searches` query self-contained and bounded** : Because Bigtable GoogleSQL doesn't support CTEs, subqueries, or `UNION ALL`, define a single bounded lookup query using row-key, equality, or `LIMIT` filtering.
- **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). Never run `value_searches` directly against multi-million-row fact or log tables and omit `value_searches` for small closed enums.

## What's next

- Learn how to [build context sets using the context engineering agent](https://docs.cloud.google.com/gemini/data-agents/querydata/bigtable/build-context-sets.md.txt).
- Learn how to [create or delete a context set in Bigtable Studio](https://docs.cloud.google.com/gemini/data-agents/querydata/bigtable/manage-data-agents.md.txt).