Skip to main content

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.

Current entry point

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:

StageDescription
understandParse the question and identify the data source, schema, tables, metrics and time range
generateGenerate SQL by combining the semantic layer and table structures
executeExecute after read-only validation passes and return a row-limited result
analyzeProduce conclusions, chart suggestions and follow-up questions

Prerequisites​

  • The AI feature is enabled on the platform. spring.ai.enabled is 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​

  1. Select a data source;
  2. Select a schema;
  3. Select one or more tables as the query scope;
  4. Enter a natural-language question;
  5. 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:

RuleDescription
Allowed statementsOnly statements starting with SELECT, WITH or EXPLAIN are allowed
Forbidden statementsWrite operations and stored procedures such as INSERT, UPDATE, DELETE, DROP, ALTER, TRUNCATE, CREATE, CALL and EXEC
Multiple statementsConcatenating multiple statements with semicolons is forbidden
CommentsComments must not be used to hide dangerous keywords
Result rowsAt most 100 rows are returned by default; the excess is truncated
Execution timeout30 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 does not mean risk-free

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:

TypeUse case
Line chartTime trends
Area chartCumulative volume or trend emphasis
Bar chartCategory comparison
Stacked bar chartCategory composition
Horizontal bar chartRankings with long category names
Pie chartProportions
Scatter chartCorrelation between two numeric dimensions
Dual-axis chartComparison 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:

  1. Click "Save as API";
  2. The frontend writes the SQL, data source, schema, table names and question into sessionStorage (the key is ai-sql-draft-{timestamp});
  3. It navigates to script mode in the Workbench and carries aiDraftKey;
  4. Complete the API name, path, parameters and response configuration in the Workbench;
  5. 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​

FieldDescription
Term nameThe business name, such as "deal amount"
SynonymsMultiple synonymous expressions, separated by commas
Term typeTable, field, enum value or description
Data source / schema / target objectThe physical object the term maps to
Enabled statusWhen off, the term is not included in prompts

Metrics​

FieldDescription
Metric nameThe business metric name
Metric codeUnique code
Metric descriptionBusiness meaning
Definition SQLRequired; defines how the metric is calculated
Related tablesTables involved in the metric
Dimension hintsCommonly used dimensions
Example SQLReference query
Data source / schemaScope of application
Enabled statusWhen 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.

Scenario operations is not metric configuration

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​

ItemDefault
AI master switchOff
Maximum returned rows100
Model timeout30 seconds
History turns injected5
Insight sample rows10
Semantic cache60 seconds
Terms injected per prompt30
Regular AI endpoint rate limit10 requests/minute/user
AI assistant rate limit30 requests/minute/user
Model temperature0.2

FAQ​

SymptomCauseResolution
Message that AI is not enabledspring.ai.enabled=falseEnable it in the deployment configuration and restart the service
Cannot select a data sourceThe current project is not authorized, or the data source is not relationalCheck the data source authorization and type
The generated SQL is rejectedIt contains a write operation, multiple statements, comments or a non-read-only prefixChange the question or adjust the SQL manually
The result is emptyFilters are too strict, there is no data in the time range, or the wrong table was selectedAdjust the scope and ask again
The result is truncatedThe 100-row preview limit is exceededAdd aggregation or filter conditions
Answers do not match business definitionsMetrics or synonyms are not configured in the semantic layerAdd terms and metrics in semantic configuration
The draft cannot be found after savingDrafts rely on browser session storageRegenerate it from the Workbench, or check whether the tab was closed