AI data query and SQL analysis
AI data query turns natural-language questions into read-only SQL, runs a preview against the data source, and performs chart and insight analysis on the results. It is one of the AI assistant's tool capabilities, and it also keeps a standalone data query interface.
The AI Assistant page shows the "AI assistant" mode by default; the standalone data query mode is not exposed in the mode switcher. When the AI assistant encounters a data query question, it reuses the same data query chain described on this page through the built-in ai_query tool. The underlying capabilities are described below so you can understand the behavior and limits.
Capability overview
Processing is divided into four stages:
| Stage | Description |
|---|---|
| understand | Parse the question and identify the data source, schema, tables, metrics and time range |
| generate | Generate SQL by combining the semantic layer and table structures |
| execute | Execute after read-only validation passes and return a row-limited result |
| analyze | Produce conclusions, chart suggestions and follow-up questions |
Prerequisites
- The AI feature is enabled on the platform.
spring.ai.enabledis off by default, so it must be explicitly enabled and the model configured during deployment; - A relational data source is used (MySQL, PostgreSQL, Oracle, SQL Server, DM and others), and the current project has permission to access the data source;
- A data source, schema and target tables have been selected;
- The model service is reachable, and the key and model name are configured correctly.
Starting a data query
- Select a data source;
- Select a schema;
- Select one or more tables as the query scope;
- Enter a natural-language question;
- Wait for the stage progress to complete, then view the SQL, results and insights.
The query scope is remembered in browser local storage and restored automatically the next time you enter. Switching the data source or schema clears the selected tables.
Example questions
- "Order volume per day over the last 7 days"
- "Sales by region, top 10"
- "Query completed orders and aggregate by month"
- "Compare new users this year and last year"
The more specific the question, the more stable the generated SQL. When business definitions are involved, configure the metrics and terms in the semantic layer first.
SQL security boundaries
Both AI-generated SQL and manually edited SQL go through the same read-only validation:
| Rule | Description |
|---|---|
| Allowed statements | Only statements starting with SELECT, WITH or EXPLAIN are allowed |
| Forbidden statements | Write operations and stored procedures such as INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, CALL and EXEC |
| Multiple statements | Concatenating multiple statements with semicolons is forbidden |
| Comments | Comments must not be used to hide dangerous keywords |
| Result rows | At most 100 rows are returned by default; the excess is truncated |
| Execution timeout | 30 seconds by default |
| SELECT * | The model is prompted to avoid selecting all fields, reducing unnecessary scans |
When validation fails, the SQL is not executed and the page shows the specific security restriction. Re-running the preview after manually editing the SQL triggers validation again.
Read-only queries can still consume significant database resources. In production, use a read-only account, restrict the schemas that can be queried, and combine this with database-side resource governance.
Viewing results
SQL
- Shows the generated SQL with syntax highlighting and expand/collapse support;
- The SQL can be copied;
- You can enter edit mode to modify the SQL and run a read-only preview again;
- Low confidence, automatic corrections or warnings are flagged.
Data table
- Shows column names, types and result rows;
- Supports selecting rows and copying results;
- The number of result rows is constrained by the preview limit.
Charts
Eight chart types are supported:
| Type | Use case |
|---|---|
| Line chart | Time trends |
| Area chart | Cumulative volume or trend emphasis |
| Bar chart | Category comparison |
| Stacked bar chart | Category composition |
| Horizontal bar chart | Rankings with long category names |
| Pie chart | Proportions |
| Scatter chart | Correlation between two numeric dimensions |
| Dual-axis chart | Comparison of two metrics with different units |
Charts infer dimensions and metrics from the result columns automatically, and the type can also be switched manually. When the data does not meet the chart requirements, the reason is shown instead of rendering an empty chart.
Export
Query results can be exported as CSV:
- The file is encoded in UTF-8 with a BOM so that Excel recognizes Chinese correctly;
- Only the current result set is exported; charts are not exported;
- The export is done in the frontend and creates no extra server task.
Result insights
- A summary analysis is performed on a sample of the results, with 10 rows sampled by default;
- Provides trends, anomalies, extremes and possible business explanations;
- Insights are model-generated supporting information and cannot replace manual verification.
Saving as an API draft
A data query result can be turned into an API draft:
- Click "Save as API";
- The frontend writes the SQL, data source, schema, table names and question into
sessionStorage(the key isai-sql-draft-{timestamp}); - It navigates to script mode in the Workbench and carries
aiDraftKey; - Complete the API name, path, parameters and response configuration in the Workbench;
- Publish after testing passes.
The draft contains only the SQL and context; it does not publish the API automatically. Unused drafts are cleared with session storage after the page is closed.
Semantic layer
The semantic layer maps business terms to physical tables and fields to improve generation accuracy.
Terms
| Field | Description |
|---|---|
| Term name | The business name, such as "deal amount" |
| Synonyms | Multiple synonymous expressions, separated by commas |
| Term type | Table, field, enum value or description |
| Data source / schema / target object | The physical object the term maps to |
| Enabled status | When off, the term is not included in prompts |
Metrics
| Field | Description |
|---|---|
| Metric name | The business metric name |
| Metric code | Unique code |
| Metric description | Business meaning |
| Definition SQL | Required; defines how the metric is calculated |
| Related tables | Tables involved in the metric |
| Dimension hints | Commonly used dimensions |
| Example SQL | Reference query |
| Data source / schema | Scope of application |
| Enabled status | When off, the metric is not included in prompts |
Semantic configuration is cached for 60 seconds, so changes take effect within 1 minute. A single prompt injects at most 30 terms to avoid an overly long context.
Scenario and dictionary operations
Scenario operations is used to maintain scenario routing, the synonym dictionary and data query success-rate statistics:
- Scenario definitions determine which processing flow a question enters;
- The synonym dictionary supplements business names;
- Statistics show the scenario code, failure reasons, call volume, success rate, average tokens and average latency;
- Success rates are colored in three bands: ≥90%, ≥70%, and <70%.
Scenario routing degrades step by step in the order "exact dictionary match → scenario affinity → model judgment". When the semantic parsing confidence is below 0.6, the system does not guess the scenario; instead it asks for clarification or falls back to free-form Q&A.
Metrics and terms are maintained in "Semantic configuration"; "Scenario operations" maintains scenarios, dictionaries and statistics. Do not confuse the two.
Multi-turn and follow-ups
- Multi-turn conversations inject the most recent 5 turns of history by default;
- Follow-up suggestions are provided below the results, such as aggregating by month, filtering to a specific value, taking the top 10, or computing the average;
- The session title takes the first 12 characters of the first question;
- The 50 most recent sessions are retained.
Limits and defaults
| Item | Default |
|---|---|
| AI master switch | Off |
| Maximum returned rows | 100 |
| Model timeout | 30 seconds |
| History turns injected | 5 |
| Insight sample rows | 10 |
| Semantic cache | 60 seconds |
| Terms injected per prompt | 30 |
| Regular AI endpoint rate limit | 10 requests/minute/user |
| AI assistant rate limit | 30 requests/minute/user |
| Model temperature | 0.2 |
FAQ
| Symptom | Cause | Resolution |
|---|---|---|
| Message that AI is not enabled | spring.ai.enabled=false | Enable it in the deployment configuration and restart the service |
| Cannot select a data source | The current project is not authorized, or the data source is not relational | Check the data source authorization and type |
| The generated SQL is rejected | It contains a write operation, multiple statements, comments or a non-read-only prefix | Change the question or adjust the SQL manually |
| The result is empty | Filters are too strict, there is no data in the time range, or the wrong table was selected | Adjust the scope and ask again |
| The result is truncated | The 100-row preview limit is exceeded | Add aggregation or filter conditions |
| Answers do not match business definitions | Metrics or synonyms are not configured in the semantic layer | Add terms and metrics in semantic configuration |
| The draft cannot be found after saving | Drafts rely on browser session storage | Regenerate it from the Workbench, or check whether the tab was closed |