Context-aware sql statement generation method and apparatus

By constructing a dynamic augmented ER model and a collaborative engine between knowledge graph and large language model, the problem of insufficient accuracy in SQL statement generation under complex query scenarios is solved. It realizes dynamic representation of entity relationships and accurate capture of user query intent, thereby improving the accuracy and automation of SQL statement generation.

CN121705305BActive Publication Date: 2026-04-28QINGDAO UNIV OF SCI & TECH
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
QINGDAO UNIV OF SCI & TECH
Filing Date
2026-02-24
Publication Date
2026-04-28

AI Technical Summary

Technical Problem

Existing technologies are not accurate enough in generating SQL statements in complex query scenarios. Static ER diagrams cannot dynamically capture the timeliness and scenario dependence of entity relationships. Rule engines lack the ability to perceive the context of user query intent. Text-to-SQL technology based on large language models tends to ignore database domain constraints and generate SQL statements that are logically equivalent but syntactically invalid.

Method used

A dynamically enhanced ER model is constructed, which activates entity association subgraphs through scene keywords, generates SQL statements by combining a collaborative engine of knowledge graph and large language model, parses query intent using a high-level semantic scene activation module, generates context scene snapshots, and optimizes SQL statements through knowledge graph constraints and large language model.

Benefits of technology

It improves the accuracy of SQL statement generation, reduces reliance on predefined rules and manual intervention, enhances semantic understanding capabilities in complex business scenarios, and reduces usage and maintenance costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121705305B_ABST
    Figure CN121705305B_ABST
Patent Text Reader

Abstract

The embodiment of the application relates to the technical field of database query, and particularly relates to a context-aware SQL statement generation method and device. The method comprises the following steps: obtaining an adaptation request, the adaptation request comprising user query text information; parsing query intent information in the user query text information and generating a context scene snapshot, the query intent information comprising a scene keyword; activating a corresponding entity association subgraph in a preset dynamic enhancement E-R model based on the scene keyword; generating an initial SQL statement based on the context scene snapshot, the entity association subgraph and a KG-LLM collaborative engine; and optimizing the initial SQL statement to generate a target SQL statement. The embodiment of the application activates the entity association subgraph by constructing a dynamic enhancement E-R model and using a scene keyword, uses the structured knowledge of a knowledge graph to constrain and guide a large language model, suppresses the pattern hallucination and logical errors in the generation process, and improves the accuracy of SQL statement generation.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of database query technology, and in particular to a method and apparatus for generating context-aware SQL statements. Background Technology

[0002] Intelligent database interaction is a key technology that uses automation to accurately map user natural language requirements to the underlying database schema, generating executable SQL (Structured Query Language) statements. This is crucial for improving database query efficiency and usability. Currently, mainstream technical solutions fall into two categories: one is query generation methods based on static ER diagrams and rule engines, and the other is query generation methods based on large language models using Text-to-SQL technology.

[0003] However, both of these existing solutions have certain limitations: static ER diagrams rely on predefined patterns and cannot dynamically capture the timeliness and scenario dependence of different entity associations, resulting in the inability to migrate entity associations accumulated from historical queries to new scenarios and low data integration efficiency; existing rule engines generally lack context awareness of user query intent, and the semantic mapping process relies on manually preset rules or empirical assumptions, which are prone to generating incorrect SQL statements due to missing pattern information and ambiguity in user semantic expression, resulting in insufficient accuracy in complex query scenarios; although Text-to-SQL technology based on large language models can improve semantic understanding capabilities, it is prone to ignoring database domain constraints or generating logically equivalent but syntactically invalid SQL statements, requiring additional manual intervention for correction, resulting in low fault tolerance and increased user costs. Summary of the Invention

[0004] One objective of this application is to provide a context-aware SQL statement generation method and apparatus to solve the technical problem of insufficient accuracy in generating SQL statements in complex query scenarios in the prior art.

[0005] In a first aspect, embodiments of this application provide a context-aware SQL statement generation method, the method comprising:

[0006] Obtain the adaptation request, which includes user query text information;

[0007] The query intent information in the user's query text is parsed, and a contextual scene snapshot is generated, wherein the query intent information includes scene keywords;

[0008] Based on the scenario keywords, the corresponding entity association subgraph in the preset dynamic augmentation ER model is activated. The dynamic augmentation ER model includes multiple entity association subgraphs, and the entity association subgraphs use association weights to represent the association relationships between multiple entities.

[0009] The initial SQL statement is generated based on the context scene snapshot, the entity association subgraph, and the KG-LLM collaborative engine, which integrates knowledge graph and large language model.

[0010] The initial SQL statement is optimized to generate a target SQL statement that matches the user's query text information.

[0011] Optionally, the method further includes constructing the preset dynamically enhanced ER model, wherein constructing the preset dynamically enhanced ER model includes:

[0012] Multi-source heterogeneous data collection is performed between the business logic layer and the data access layer to obtain the target data set;

[0013] A multi-layer entity association model is constructed based on the target data set. The multi-layer entity association model includes a log layer, which stores historical access logs.

[0014] The preset dynamically enhanced ER model is constructed based on the historical access logs.

[0015] Optionally, the multi-layer entity association model includes a schema layer, an instance layer, and a log layer. The instance layer includes numerical data, character data, and long text data. The construction of the multi-layer entity association model based on the target data set includes:

[0016] In the pattern layer, based on a multi-dimensional similarity discrimination algorithm combined with semantic analysis, similar entities and attributes are rapidly fused.

[0017] In the instance layer, feature vectors of the numerical data and the character data are generated, and a dense vector of the long text data is generated using an autoencoder. Similarity analysis is performed on the feature vectors and the dense vectors to match instances with potential relationships between different entities.

[0018] In the log layer, dynamic equivalence relationships in different historical access logs are analyzed to establish dynamic associations between entities and attributes.

[0019] Optionally, constructing the preset dynamically enhanced ER model based on the historical access logs includes:

[0020] The historical access logs of the log layer are analyzed to identify frequently co-occurring entity pairs and construct an initial association graph. The entity pairs include at least two different entities.

[0021] The association weight between the entity pairs is calculated based on the time window and access frequency.

[0022] Predict potential association paths for different entity pairs based on attention mechanisms and graph neural networks;

[0023] The preset dynamic enhancement ER model is constructed based on the initial association graph, the association weights, and the association paths.

[0024] Optionally, the association weights include time weights and scene weights, and the activation of the corresponding entity association subgraph in the preset dynamic augmented ER model based on the scene keywords includes:

[0025] Calculate the similarity between the scene keywords and the entities in the dynamically enhanced ER model;

[0026] Select the top N entities with the highest similarity to the scenario keywords, activate the corresponding entity association subgraph, and enhance the corresponding time weight or scenario weight.

[0027] Optionally, the contextual scene snapshot includes an entity set, associated edges, and constraints; the query intent information includes implicit scene tags; and parsing the query intent information in the user query text information and generating the contextual scene snapshot includes:

[0028] The preset high-level semantic scene activation module parses the scene keywords and implicit scene tags in the user query text information;

[0029] Based on the scene keywords and the implicit scene tags, the entity set, the associated edges, and the constraints are generated using the preset dynamic augmented ER model.

[0030] Optionally, the step of generating the initial SQL statement based on the context scene snapshot, the entity association subgraph, and the KG-LLM collaborative engine includes:

[0031] Based on the knowledge graph, entities and relationships in the entity association subgraph are extracted to obtain a restricted entity set. The restricted entity set is used to restrict the entities and relationships available when the large language model generates the initial SQL statement.

[0032] The restricted entity set and the context snapshot are input into the large language model so that the large language model generates the initial SQL statement.

[0033] Optionally, optimizing the initial SQL statement to generate a target SQL statement adapted to the user's query text information includes:

[0034] The initial SQL statement is logically equivalent to the KG-LLM collaborative engine. The logical equivalence verification is used to verify whether there is an equivalent optimized substatement in the initial SQL statement.

[0035] In response to the existence of the equivalent optimized sub-statement in the initial SQL statement, the target SQL statement adapted to the user query text information is generated based on the equivalent optimized sub-statement.

[0036] Optionally, the context-aware SQL statement generation method further includes:

[0037] Obtain the SQL statement after the user corrects the target SQL statement, and get feedback information;

[0038] The association relationships of entities in the knowledge graph are updated based on the feedback information;

[0039] The feedback information is used as training samples for the large language model to update the large language model.

[0040] Secondly, embodiments of this application provide a context-aware SQL statement generation apparatus, the apparatus comprising:

[0041] The request acquisition module is used to acquire adaptation requests, which include user query text information;

[0042] The high-level semantic scene activation module is used to parse the query intent information in the user query text information and generate a context scene snapshot, wherein the query intent information includes scene keywords;

[0043] The entity association subgraph acquisition module activates the corresponding entity association subgraph in the preset dynamic augmented ER model based on the scene keywords. The dynamic augmented ER model includes multiple entity association subgraphs, and the entity association subgraphs use association weights to represent the association relationships between multiple entities.

[0044] The KG-LLM collaboration module is used to generate an initial SQL statement based on the context scene snapshot, the entity association subgraph, and the KG-LLM collaboration engine. The KG-LLM collaboration engine integrates a knowledge graph and a large language model.

[0045] The SQL statement optimization module is used to optimize the initial SQL statement and generate a target SQL statement that is adapted to the user's query text information.

[0046] The embodiments of this application can achieve the following technical effects: In the context-aware SQL statement generation method provided in the embodiments of this application, the method includes: obtaining an adaptation request, the adaptation request including user query text information; parsing the query intent information in the user query text information and generating a context scene snapshot, the query intent information including scene keywords; activating the corresponding entity association subgraph in a preset dynamic augmented ER model based on the scene keywords, the dynamic augmented ER model including multiple entity association subgraphs, the entity association subgraphs using association weights to represent the association relationships between multiple entities; generating an initial SQL statement based on the context scene snapshot, the entity association subgraphs and the KG-LLM collaborative engine, the KG-LLM collaborative engine integrating knowledge graph and large language model; optimizing the initial SQL statement to generate a target SQL statement adapted to the user query text information.

[0047] This application embodiment constructs a dynamically enhanced ER model and activates the entity association subgraph with scenario keywords to achieve a dynamic and quantitative representation of the relationships between entities. It can focus on data patterns highly relevant to the current query, improving semantic understanding capabilities in complex business scenarios. By generating contextual scenario snapshots and combining them with the KG-LLM collaborative engine, it can more accurately capture user query intent. Simultaneously, by utilizing the structured knowledge of knowledge graphs to constrain and guide large language models, it can suppress pattern illusions and logical errors that may occur during SQL statement generation, improving the accuracy of SQL statement generation. This application embodiment also achieves a high degree of automation and scenario-driven characteristics, reducing reliance on numerous predefined rules or manual intervention, and lowering usage and maintenance costs. Attached Figure Description

[0048] To more clearly illustrate the technical solutions of the embodiments of this application, the drawings used in the description of the embodiments of this application will be briefly introduced below. Obviously, the drawings described below are only some embodiments of this application. For those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0049] Figure 1 This application provides a flowchart illustrating a context-aware SQL statement generation method.

[0050] Figure 2 A schematic diagram of an entity association subgraph provided in an embodiment of this application;

[0051] Figure 3 A schematic diagram illustrating a process for constructing a dynamically enhanced ER model, provided as an embodiment of this application;

[0052] Figure 4A schematic diagram of the structure of a context-aware SQL statement generation device provided in an embodiment of this application;

[0053] Figure 5 A schematic diagram of another context-aware SQL statement generation device provided in an embodiment of this application;

[0054] Figure 6 This is a schematic diagram of the structure of a computer device provided in an embodiment of this application. Detailed Implementation

[0055] To make the objectives, technical solutions, and advantages of this application clearer, the following detailed description is provided in conjunction with the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the scope of this application. All other embodiments obtained by those skilled in the art based on the embodiments in this application without inventive effort are within the scope of protection of this application.

[0056] It should be noted that, unless there is a conflict, the various features in the embodiments of this application can be combined with each other, all of which are within the protection scope of this application. Furthermore, although functional modules are divided in the device schematic diagram and a logical order is shown in the flowchart, in some cases, the steps shown or described can be executed in a different order than the module division in the device or the order in the flowchart. Moreover, the terms "first," "second," and "third" used in this application do not limit the data or execution order, but only distinguish identical or similar items with essentially the same function and effect.

[0057] To facilitate understanding of the context-aware SQL statement generation method provided in the embodiments of this application, the relevant core technical content of the embodiments of this application will be described below.

[0058] LLM (Large Language Model) is a deep learning model (such as GPT and BERT) trained on massive amounts of text, possessing powerful natural language understanding and generation capabilities. In the data space, LLM can directly parse user natural language queries (such as "statistics on unsold goods in North China") and generate SQL statements. However, question-answering environments present risks such as pattern illusion (e.g., confusing "sales revenue" with "sales quantity"), missing domain knowledge (e.g., the business definition of "unsold goods"), and SQL variant errors (syntactically equivalent but inefficiently executed JOIN sequences). Therefore, this application's embodiments incorporate knowledge graphs for constraint correction, ensuring that the generated SQL statements conform to business logic and data patterns.

[0059] A knowledge graph (KG) is a structured semantic network that describes domain knowledge (such as the "product-category-supplier" association rule in the retail industry) through entities, relationships, and attributes. In the data space, KG provides business rule constraints (such as "product price > 0"), semantic disambiguation (clarifying that "North China" corresponds to Region_ID='CN-North' in the database), and relationship supplementation (hinting that "slow-moving products" need to be associated with the inventory and sales tables). The structured knowledge of the knowledge graph can correct SQL statements generated by LLM, avoiding SQL statements that violate domain logic, while improving the semantic accuracy of complex queries.

[0060] Layered multidimensional data acquisition and log-driven mechanisms are data acquisition and modeling methods embedded in the system architecture layer, used to capture patterns, instances, and access behaviors of multi-source heterogeneous data in real time. In a general data space, the system deploys collection points between the business logic layer and the data access layer based on this layered multidimensional data acquisition and log-driven mechanism, acquiring data layer by layer:

[0061] (1) Schema layer: Extract table / field metadata and construct a global data structure topology;

[0062] (2) Instance layer: Classification processing of numerical type (statistical feature vector), character type (TF-IDF feature vector), and long text type (dense vector);

[0063] (3) Log layer: Records access paths and operation sequences (such as the frequently occurring "order ID + logistics status").

[0064] By accessing log data and collecting results from multiple dimensions, the dynamic enhancement of the ER model is driven to address the pain point that static models cannot adapt to data changes.

[0065] T2S (Text-to-SQL) is a technology that converts natural language queries into structured query language (SQL) queries, encompassing semantic parsing, schema linking, and SQL generation. In general data spaces, traditional T2S relies on rule templates or static schema mapping, which struggles to handle: ambiguity of polysemous words (e.g., does "apple" refer to the fruit or the brand); dynamically added entities (e.g., new business tables not predefined); and complex aggregation logic (e.g., "year-on-year slow sales" requires cross-table calculations). This application's embodiment, however, enhances the scenario focus of the dynamically enhanced ER model and collaborates with the KG-LLM engine to accurately map ambiguous semantics to the underlying data schema (e.g., "slow sales" maps to "sales decline > 30%)", improving the robustness of complex queries.

[0066] The dynamically augmented Entity-Relationship (ER) model is an adaptive relational network that incorporates association weights, learning dynamic relationships between entities through historical query behavior. In a general data space, it includes the following three processes:

[0067] (1) Association discovery: Mining new associations based on historical access logs (such as a strong association between “mask sales and logistics delays” caused by a sudden outbreak of the epidemic);

[0068] (2) Weight quantification: Introduce time weight (such as increasing the time weight of frequent recent visits) and scenario weight (such as increasing the scenario weight of "order-product" during the promotion period);

[0069] (3) Scene Focus: Activate the entity association subgraph based on scene keywords (such as "Q4 North China") and dynamically hide irrelevant entities.

[0070] This application embodiment replaces the traditional static ER diagram by constructing a dynamically enhanced ER model, enabling data association to evolve in real time with business scenarios and improving query efficiency.

[0071] The HSSA (High-level Semantic Scene Activation) module is an intent-driven context-aware module that maps high-level semantics into executable context snapshots. In the data space, the HSSA module parses scenario keywords ("North China," "Q4," "slow-moving goods") and implicit scenario tags ("sales analysis") from user queries, and combines this with a dynamically enhanced ER model to generate a context snapshot containing three elements:

[0072] (1) Entity sets (such as product tables, sales tables, and region tables);

[0073] (2) Related edges (e.g., product-sales order, sales order-region);

[0074] (3) Constraints (e.g., time range = October 2023 to December 2023, region = North China, sluggish sales = year-on-year sales decline > 30%).

[0075] The Knowledge Graph-Large Language Model Fusion (KG-LLM Fusion) mechanism is a collaborative mechanism between knowledge graph constraints and the generative capabilities of large language models. It optimizes the output of precise SQL through semantic verification and logical equivalence validation. In the data space, this mechanism comprises four parts:

[0076] (1) Knowledge-driven constraints: KG intercepts invalid SQL generated by LLM (such as "delete product table" violating read-only permission);

[0077] (2) Semantic disambiguation: The fuzzy conditions ("high-selling products recently") output by LLM are transformed into precise thresholds defined by KG ("sales in the last 7 days > 1000").

[0078] (3) Logical equivalence verification: Optimize syntax variants through the logical rule base (e.g., rewrite subqueries as JOIN to improve execution efficiency);

[0079] (4) Feedback learning: The SQL statements manually corrected by the user (such as changing "region table" to "province table") update the association weights of entities in the knowledge graph in reverse.

[0080] This application embodiment, by constructing a KG-LLM Fusion mechanism, can significantly reduce the error rate of SQL statement generation while ensuring business security.

[0081] Please see below. Figure 1 , Figure 1 This is a flowchart illustrating a context-aware SQL statement generation method provided in this application embodiment. The context-aware SQL statement generation method provided in this application embodiment includes steps S11 to S15:

[0082] S11: Obtain the adaptation request, which includes the user query text information.

[0083] In step S11, specifically, the adaptation request is an input request initiated by the user to the system for a query operation. The core part of the adaptation request is the user's query text information. The user's query text information is usually presented in natural language and is used to represent the user's data retrieval intent or business requirement description for the target database. The system receives and parses the adaptation request initiated by the user from the user end (such as a web interface or mobile application) or the business system end through a preset interface gateway, and accurately extracts the user's query text information from it, aiming to fully capture the user's query intent.

[0084] S12: Parse the query intent information in the user's query text information and generate a contextual scene snapshot. The query intent information includes scene keywords.

[0085] In step S12, specifically, the contextual scene snapshot includes entity sets, associated edges, and constraints. The query intent information also includes implicit scene tags. The system parses the scene keywords and implicit scene tags in the user's query text information based on a preset high-level semantic scene activation module. Specifically, the system is configured with a high-level semantic scene activation module, which is an intent-driven context-aware module that can map high-level semantics into an executable contextual scene snapshot. High-level semantics is a natural language description. The high-level semantic scene activation module parses the query intent information in the user's query text information, which includes scene keywords and implicit scene tags. For example, the user's query text information is "Query for unsold goods in North China in Q4," where Q4 represents the fourth quarter. The high-level semantic scene activation module parses this user's query text information and obtains scene keywords (such as "North China," "Q4," and "unsold") and implicit scene tags ("sales analysis").

[0086] The high-level semantic scene activation module generates entity sets, associated edges, and constraints based on scene keywords and implicit scene tags, combined with a pre-defined dynamically enhanced ER model. For example, the high-level semantic scene activation module parses scene keywords ("North China," "Q4," "slow-moving goods") and implicit scene tags ("sales analysis") from the user's query text, and generates a contextual scene snapshot containing three elements using the dynamically enhanced ER model:

[0087] (1) Entity sets (such as product tables, sales tables, and region tables);

[0088] (2) Related edges (e.g., product-sales order, sales order-region);

[0089] (3) Constraints (e.g., time range = October 2023 to December 2023, region = North China, sluggish sales = year-on-year sales decline > 30%).

[0090] It should be noted that user query text information is often expressed in natural language, which can lead to semantic ambiguity, lack of context, and domain-specific terminology ambiguity. For example, if a user enters "check the products that have sold poorly recently," "recently" could refer to the last 7 days or the last 30 days, and "poorly sold" could mean low sales volume, high return rate, or inventory backlog. To address this, this application embodiment uses a high-level semantic scene activation module to parse the user's query intent and generate a contextual scene snapshot. Specifically, the high-level semantic scene activation module uses fuzzy logic reasoning to map the user's natural language query to the underlying data pattern. For example, "poorly sold" is mapped to "sales volume year-on-year decrease >30%", and "recently" is mapped to "the last 7 days", and these are used as scene keywords.

[0091] S13: Activate the corresponding entity association subgraph in the preset dynamic augmentation ER model based on scene keywords. The dynamic augmentation ER model includes multiple entity association subgraphs, and the entity association subgraphs use association weights to represent the association relationship between multiple entities.

[0092] In step S13, specifically, the preset dynamically enhanced ER model (dynamically enhanced entity-relationship model) is an adaptive relationship network that integrates association weights, learning dynamic associations between entities through historical query behavior. It includes the following three processes in the general data space:

[0093] (1) Association discovery: Mining new associations based on historical access logs (such as a strong association between “mask sales and logistics delays” caused by a sudden outbreak of the epidemic);

[0094] (2) Weight quantification: Introduce time weight (such as increasing the time weight of recent visits with high frequency) and scenario weight (such as increasing the scenario weight of "order table - product table" during the promotion period);

[0095] (3) Scene Focus: Activate the corresponding entity association subgraph based on scene keywords (such as "Q4 North China") and dynamically hide irrelevant entities.

[0096] The system calculates the similarity between scenario keywords and entities in the dynamically augmented ER model. Specifically, the system extracts scenario keywords from user query text information (such as "querying unsold goods in North China in Q4"), including entity keywords (such as "goods" and "region") and attribute keywords (such as "North China", "Q4", and "unsold"). The system performs standardized preprocessing on the extracted scenario keywords, mapping attribute keywords to corresponding attribute dimensions in the dynamically augmented ER model (e.g., "North China" maps to "region table, region attribute", "Q4" maps to "sales table, time attribute", and "unsold" maps to "goods table, sales status attribute").

[0097] The system uses preprocessed scenario keywords (entity-based keywords and attribute-based keywords) as the query endpoint and entity nodes in the dynamically enhanced ER model (such as "product table," "sales table," and "region table") and their associated attribute dimensions as the target endpoint. Scenario keywords and entities / attributes in the dynamically enhanced ER model are converted into feature vectors, and cosine similarity is calculated to quantify the semantic matching degree, thus obtaining the semantic similarity between the two. For example, the semantic similarity between the entities "slow-moving goods" and "product table" is calculated to be 0.92, and the semantic similarity between the attributes "North China" and "region table" is calculated to be 0.98.

[0098] The system selects the top N entities with the highest similarity to the scenario keywords, activates the corresponding entity association subgraph, and enhances the corresponding time / scenario weights. Specifically, the system sorts the semantic similarity values ​​of all entities in the dynamically enhanced ER model in descending order and selects the top N entities with the highest values ​​(N is preset according to the complexity of the business scenario; for example, N=3, and in this example, "product table," "sales table," and "region table" are selected). Preset relationships between the top N entities are extracted from the dynamically enhanced ER model (such as the "record sales data" relationship between "product table" and "sales table" and the "bind sales region" relationship between "sales table" and "region table"), and a scenario-focused entity association subgraph is constructed.

[0099] Please see Figure 2 , Figure 2 This is a schematic diagram of an entity association subgraph provided in an embodiment of this application. The system dynamically enhances the ER model attribute dimension (e.g., "sales table, time attribute") corresponding to time-attribute scenario keywords (e.g., "Q4"), thereby increasing the time weight of the corresponding entity and the entity "sales table". The enhanced time weight is equal to the product of the initial time weight of the entity association in the entity association subgraph and the enhancement coefficient. The enhancement coefficient can be set based on the query frequency of the time dimension in historical access logs. In this embodiment, the enhancement coefficient is set to 1.5. For example, if the initial time weight of "sales table - product table" is 0.7, then the enhanced time weight is 0.7 × 1.5 = 1.05.

[0100] The system dynamically enhances the ER model attribute dimensions ("Regional Table, Regional Attribute", "Product Table, Sales Status Attribute") corresponding to scenario keywords (such as "North China" and "Unsold Goods"). This enhances the scenario weights of the corresponding entities and their corresponding "Regional Table" and "Product Table" entities. The enhanced scenario weight is equal to the product of the initial scenario weight in the entity association subgraph and the enhancement coefficient. For example, if the initial scenario weight of "Sales Table - Regional Table" is 0.6, the enhanced scenario weight will be 0.6 × 1.5 = 0.9. The system then updates the enhanced time weight and scenario weight to the entity association subgraph.

[0101] It should be noted that the system activates relevant entity association subgraphs based on the user's query text information, dynamically generating an ER relationship topology focused on the scenario. For example, when a user enters "query unsold goods in North China Q4", the system will activate the entity association subgraph of "product table - sales table - region table" and assign enhanced association weights to "region = North China" and "time = Q4", constructing an entity relationship network highly relevant to the current user's query text information.

[0102] S14: Generates initial SQL statements based on contextual scene snapshots, entity association subgraphs, and the KG-LLM collaborative engine, which integrates knowledge graphs and large language models.

[0103] In step S14, specifically, the system extracts entities and relationships from the entity association subgraph based on the knowledge graph, obtaining a restricted entity set. This restricted entity set is used to limit the entities and relationships available when the large language model generates the initial SQL statement. Specifically, the system performs topological structure parsing on the entity association subgraph based on the knowledge graph, extracting metadata for the <entity-relationship-entity> triple, including the data table it belongs to, attribute dimensions, entity association types, and association fields. The system then converts the restricted entity set into constraint rules that the large language model can parse, explicitly prohibiting the use of entities, attributes, and relationships outside the set.

[0104] The system inputs a restricted entity set and a context snapshot into a large language model, enabling the model to generate an initial SQL statement. Specifically, the system integrates the context snapshot (entity set, associated edges, and constraints), the restricted entity set (constraint rules), and the associated weights of corresponding entities in the knowledge graph to form a structured input dataset. This input dataset is then encapsulated using a structured template. The structured template includes task instructions (generating a syntactically correct SQL statement that matches the query intent, specifying only entity relationships), constraint rule segments (constraint rules for the restricted entity set), scenario information segments (constraints from the context snapshot), and format requirements (output SQL statement). The system inputs this structured template into the large language model, allowing it to parse the query intent, match the restricted set, and generate the initial SQL statement.

[0105] It should be noted that the system combines a knowledge graph (KG) and a large language model (LLM) for semantic disambiguation and SQL statement generation. For example, the KG defines "slow-moving goods" as meeting the criteria of "declining sales and inventory turnover rate lower than the industry average." The LLM then generates an initial SQL statement based on this definition. An example initial SQL statement is shown below:

[0106] SELECT Product Name, Sales Volume, Inventory Quantity

[0107] FROM Product List

[0108] JOIN SalesTable ON ProductTable.ProductID = SalesTable.ProductID

[0109] WHERE region = 'North China'

[0110] AND Sales period: BETWEEN '2023-10-01' AND '2023-12-31'

[0111] AND sales volume decreased by more than 30% year-on-year.

[0112] AND inventory turnover rate < (SELECT AVG(inventory turnover rate) FROM industry standard table).

[0113] S15: Optimize the initial SQL statement to generate a target SQL statement that matches the user's query text information.

[0114] In step S15, specifically, the system performs logical equivalence verification on the initial SQL statement based on the KG-LLM collaborative engine. Logical equivalence verification verifies whether there are equivalent optimized sub-statements in the initial SQL statement. Equivalent optimized sub-statements are query statements with better query methods and equivalent effects. Specifically, the KG-LLM collaborative engine integrates the KG-LLMFusion mechanism. The system loads the SQL semantic equivalence rule base (including rules for index optimization, association optimization, and subquery simplification) from the knowledge graph based on the KG-LLM collaborative engine as the benchmark for logical equivalence verification. Simultaneously, the initial SQL statement is parsed, extracting core metadata such as syntax structure, entity association paths, and query conditions to obtain a structured SQL parsing result of <entity-relationship-query dimension>.

[0115] The system matches the SQL parsing results against the SQL semantic equivalence rule base to search for SQL statements that are more efficient and logically equivalent. It also verifies the reachability of entity association paths in the initial SQL statement through a knowledge graph and verifies the matching degree between the SQL statement semantics and the user's query intent by combining a large language model. Finally, it cross-determines whether there are effective equivalent optimized substatements.

[0116] In response to the presence of an equivalent optimized sub-statement in the initial SQL statement, a target SQL statement adapted to the user's query text information is generated based on the equivalent optimized sub-statement. Specifically, if an equivalent optimized sub-statement is found, the one with the best query efficiency is selected first, and the initial SQL statement is adjusted according to the user's query intent to generate the target SQL statement.

[0117] It's important to note that after generating the initial SQL statement, the system performs logical equivalence verification using the KG-LLM Fusion mechanism. For example, if the SQL statement generated by LLM uses a subquery, but KG indicates that the subquery can be optimized via JOIN, the system automatically rewrites the subquery form in the initial SQL statement into a JOIN form to improve execution efficiency. The system also checks whether the entities and relationships involved in the initial SQL statement have reachable paths in the knowledge graph to avoid erroneous queries caused by schema illusion.

[0118] This application embodiment constructs a dynamically enhanced ER model and activates the entity association subgraph with scenario keywords to achieve a dynamic and quantitative representation of the relationships between entities. This allows for focusing on data patterns highly relevant to the current query, improving semantic understanding capabilities in complex business scenarios. By generating contextual scenario snapshots and combining them with the KG-LLM collaborative engine, it can more accurately capture user query intent. Simultaneously, by utilizing the structured knowledge of knowledge graphs to constrain and guide large language models, it can suppress pattern illusions and logical errors that may occur during SQL statement generation, improving the accuracy of SQL statement generation. This application embodiment also achieves a high degree of automation and scenario-driven characteristics, reducing reliance on numerous predefined rules or manual intervention, and lowering usage and maintenance costs.

[0119] Please see Figure 3 , Figure 3 This is a schematic diagram illustrating a process for constructing a dynamically enhanced ER model according to an embodiment of this application. In some embodiments, constructing a preset dynamically enhanced ER model includes the following steps:

[0120] S31: Collect multi-source heterogeneous data between the business logic layer and the data access layer to obtain the target data set.

[0121] S32: Construct a multi-layer entity association model based on the target data set. The multi-layer entity association model includes a log layer, which stores historical access logs.

[0122] S33: Build a pre-defined, dynamically enhanced ER model based on historical access logs.

[0123] In step S31, specifically, within the general data space, the main data sources include databases, log systems, API interfaces, and user behavior records. Through a layered, multi-dimensional data collection and log-driven mechanism, collection points are deployed between the business logic layer and the data access layer to acquire the following three types of data in real time:

[0124] Schema layer data: includes metadata such as database table structure, field definitions, primary and foreign key relationships, and index information;

[0125] Instance layer data includes the value range distribution, field value frequency, and data type characteristics of the actual data.

[0126] Log layer data includes behavioral data such as user query logs, access paths, query frequency, access time, and co-occurrence relationships.

[0127] The system obtains the target data set by collecting the above three types of data. The layered multidimensional data collection and log-driven mechanism is a data collection and modeling method embedded in the system architecture layer, used to capture patterns, instances, and access behaviors of multi-source heterogeneous data in real time. In the general data space, the system deploys collection points between the business logic layer and the data access layer based on the layered multidimensional data collection and log-driven mechanism, acquiring data layer by layer:

[0128] (1) Schema layer: Extract table / field metadata and construct a global data structure topology;

[0129] (2) Instance layer: Classification processing of numerical type (statistical feature vector), character type (TF-IDF feature vector), and long text type (dense vector);

[0130] (3) Log layer: Records access paths and operation sequences (such as the frequently occurring "order ID + logistics status").

[0131] In step S32, specifically, after data acquisition, the system uses multi-dimensional similarity calculation and semantic analysis to process the data at the schema layer, instance layer, and log layer, respectively, to construct a multi-layer entity association model. At the schema layer, the system uses a multi-dimensional similarity discrimination algorithm combined with semantic analysis to quickly identify and fuse similar entities and attributes from different data sources, forming a global data structure topology view.

[0132] At the instance layer, the system calculates statistical feature vectors for numerical data, generates feature vectors for character data using methods such as TF-IDF, and learns dense vector representations for long text data using an autoencoder. Based on similarity analysis of the feature vectors of numerical and character data and the dense vectors of long text data, the system achieves matching of instances with potential relationships between different entities.

[0133] At the log layer, the system continuously analyzes historical access logs to identify frequently co-occurring entities, attribute combinations, and operation sequence patterns, thereby obtaining dynamic equivalence relationships across entities and attributes and establishing preliminary association weights.

[0134] In step S33, specifically, the system analyzes the historical access logs of the log layer to identify frequently co-occurring entity pairs and constructs an initial association graph. Each entity pair includes at least two different entities. The system then calculates the association weights between entity pairs based on time windows and access frequencies, and predicts potential association paths between entity pairs based on attention mechanisms and graph neural networks. Based on the initial association graph, association weights, and association paths, the system constructs a preset dynamically enhanced ER model.

[0135] It's important to note that the system first analyzes historical access logs at the log layer to identify frequently co-occurring entity pairs. It then calculates their association weights based on time windows and access frequency, including time weights and context weights. For example, if the frequency of the "Product ID" field appearing simultaneously in both the "Sales Table" and "Inventory Table" has significantly increased in the past 7 days, the system will increase the time weight of this entity pair ("Sales Table - Inventory Table"). The system utilizes attention mechanisms and graph neural network technology to predict potential entity relationships. For instance, if the "User Table" and "Logistics Table" have no direct relationship in historical data but are frequently indirectly related through the "Order Table" in recent access logs, the system will predict and establish this indirect relationship path.

[0136] In some embodiments, the multi-layer entity association model includes a schema layer, an instance layer, and a log layer. The instance layer includes numerical data, character data, and long text data. The multi-layer entity association model is constructed based on the target data set, including: in the schema layer, rapidly fusing similar entities and attributes based on a multi-dimensional similarity discrimination algorithm combined with semantic analysis; in the instance layer, generating feature vectors for numerical and character data, and using an autoencoder to generate dense vectors for long text data, performing similarity analysis on the feature vectors and dense vectors to match instances with potential associations between different entities; and in the log layer, analyzing dynamic equivalence relationships in different historical access logs to establish dynamic associations between entities and attributes.

[0137] Specifically, after data collection is completed, the system uses multi-dimensional similarity calculation and semantic analysis techniques to process data at the schema layer, instance layer, and log layer, respectively, to construct a multi-layer entity association model. At the schema layer, a multi-dimensional similarity discrimination algorithm combined with semantic analysis techniques is used to quickly identify and merge similar entities and attributes from different data sources, forming a global data structure topology view.

[0138] At the instance layer, the system calculates statistical feature vectors for numerical data, generates feature vectors for character data using methods such as TF-IDF, and learns dense vector representations for long text data using an autoencoder. Based on similarity analysis of the feature vectors of numerical and character data and the dense vectors of long text data, the system achieves matching of instances with potential relationships between different entities.

[0139] At the log layer, the system continuously analyzes historical access logs to identify frequently co-occurring entities, attribute combinations, and operation sequence patterns, thereby obtaining dynamic equivalence relationships across entities and attributes and establishing preliminary association weights.

[0140] In some embodiments, a preset dynamically enhanced ER model is constructed based on historical access logs, including steps S331 to S334:

[0141] S331: Analyze the historical access logs of the log layer, identify frequently co-occurring entity pairs, and construct an initial association graph. Each entity pair includes at least two different entities.

[0142] S332: Calculate the association weight between entity pairs based on time window and access frequency.

[0143] S333: Predicting potential association paths between different entity pairs based on attention mechanisms and graph neural networks.

[0144] S334: Construct a pre-defined dynamic augmentation ER model based on the initial association graph, association weights, and association paths.

[0145] In step S331, specifically, the system extracts all data from the historical access logs in the log layer, including SQL query statements, access timestamps, data tables / fields involved, operation types, and other information; and cleans up invalid access logs (such as queries with syntax errors and test access records).

[0146] The system employs a sliding window co-occurrence analysis algorithm, using a preset time interval (e.g., 1 hour) as the window step size to count the co-occurrence frequency of different entities (data tables, core fields) within the sliding window. A frequency threshold is set to filter out high-frequency co-occurring entity pairs. Each entity pair includes at least two distinct entities, for example, "Sales Table (Product ID) - Inventory Table (Product ID)". The system then constructs an initial association graph structure using all filtered high-frequency co-occurring entity pairs. In the initial association graph, nodes represent entities, and edges represent the co-occurrence relationships between entities.

[0147] In step S332, specifically, the association weights include time weights and scenario weights, with different types of weights used for different entity pairs. For example, the entity pair "Sales Table (Order Time) - Inventory Table (Replenishment Time)" uses a time weight as its association weight; similarly, the entity pair "Member Table (Member Level) - Benefits Table (Redeem Prizes)" uses a scenario weight as its association weight. The system calculates the time weight / scenario weight between entity pairs based on the time window and access frequency, and updates the initial association graph as described above.

[0148] In step S333, specifically, the system transforms the initial association graph with association weights into an entity feature matrix (including entity type and access frequency) and an adjacency matrix (storing association weights). An attention mechanism is used to assign higher initial attention values ​​to entity pairs with high association weights. A Graph Attention Network (GAT) is employed, updating entity embedding vectors through multiple attention layers. The model parameters are optimized using the entity pair co-occurrence prediction accuracy as the loss function. The embedding similarity of entities without direct association is calculated, and highly similar entity pairs are selected. A depth-first search algorithm is used to mine indirect association paths between different entity pairs. The rationality of the association path business is verified by combining domain knowledge from the knowledge graph (such as the business logic rule "users need to associate logistics through orders"), and potential association paths that conform to the business logic are retained.

[0149] In step S334, the initial association graph, association weights, and association paths are integrated to obtain an entity-association network. This integrated entity-association network is then mapped to an ER structure, where nodes correspond to entities in the ER model, and edges correspond to associations in the ER model. Associations between entities can be one-to-one or one-to-many, and association weights characterize the strength of these associations. The system recalculates association weights and predicts association paths according to a preset update cycle, dynamically optimizing the ER model to obtain a preset dynamically enhanced ER model.

[0150] In some embodiments, the contextual scene snapshot includes an entity set, associated edges, and constraints; the query intent information includes implicit scene tags; parsing the query intent information in the user's query text information and generating the contextual scene snapshot includes the following steps:

[0151] S121: Based on the preset high-level semantic scene activation module, the scene keywords and implicit scene tags in the user query text information are parsed.

[0152] S122: Based on scene keywords and implicit scene tags, generate entity sets, associated edges and constraints by combining a preset dynamic augmented ER model.

[0153] In step S121, specifically, the system is configured with a high-level semantic scene activation module. This module is an intent-driven context-aware module that maps high-level semantics to executable context scene snapshots. High-level semantics is a natural language description. The high-level semantic scene activation module parses the query intent information in the user's query text, which includes scene keywords and implicit scene tags. For example, the user's query text is "Query for unsold goods in North China in Q4," where Q4 represents the fourth quarter. The high-level semantic scene activation module parses this query text and obtains scene keywords (such as "North China," "Q4," and "unsold") and implicit scene tags (such as "sales analysis").

[0154] In step S122, the high-level semantic scene activation module generates entity sets, associated edges, and constraints based on scene keywords and implicit scene tags, combined with a preset dynamic augmented ER model. For example, the high-level semantic scene activation module parses scene keywords ("North China", "Q4", "slow-moving goods") and implicit scene tags (such as "sales analysis") in the user's query text information, and generates a contextual scene snapshot containing three elements using the dynamic augmented ER model:

[0155] (1) Entity sets (such as product tables, sales tables, and region tables);

[0156] (2) Related edges (e.g., product-sales order, sales order-region);

[0157] (3) Constraints (e.g., time range = October 2023 to December 2023, region = North China, sluggish sales = year-on-year sales decline > 30%).

[0158] In some embodiments, the association weights include time weights and scene weights, activating the corresponding entity association subgraphs in a preset dynamically enhanced ER model based on scene keywords, including:

[0159] S131: Calculate the similarity between scene keywords and entities in the dynamically enhanced ER model.

[0160] S132: Select the top N entities with the highest similarity to the scene keywords, activate the corresponding entity association subgraph, and enhance the corresponding time weight / scene weight.

[0161] In step S131, specifically, the system extracts scenario keywords from the user's query text information (such as "querying unsold goods in North China in Q4"), including entity keywords (such as "goods" and "region") and attribute keywords (such as "North China", "Q4", and "unsold"). The system performs standardized preprocessing on the extracted scenario keywords, mapping the attribute keywords to the corresponding attribute dimensions in the dynamically enhanced ER model (such as "North China" mapping to "region table, region attribute", "Q4" mapping to "sales table, time attribute", and "unsold" mapping to "goods table, sales status attribute").

[0162] The system uses preprocessed scenario keywords (entity-based keywords and attribute-based keywords) as the query endpoint and entity nodes in the dynamically enhanced ER model (such as "product table," "sales table," and "region table") and their associated attribute dimensions as the target endpoint. Scenario keywords and entities / attributes in the dynamically enhanced ER model are converted into feature vectors, and cosine similarity is calculated to quantify the semantic matching degree, thus obtaining the semantic similarity between the two. For example, the semantic similarity between the entities "slow-moving goods" and "product table" is calculated to be 0.92, and the semantic similarity between the attributes "North China" and "region table" is calculated to be 0.98.

[0163] In step S132, specifically, the system sorts the semantic similarity values ​​of all entities in the dynamically enhanced ER model in descending order and selects the top N entities with the highest values ​​(N is preset according to the complexity of the business scenario, such as N=3, in this example, "product table", "sales table", and "region table" are selected). Preset relationships between the top N entities are extracted from the dynamically enhanced ER model (such as the "record sales data" relationship between "product table" and "sales table" and the "bind sales region" relationship between "sales table" and "region table"), and a scenario-focused entity relationship subgraph is constructed.

[0164] The system dynamically enhances the ER model attribute dimensions (such as "sales table, time attribute") corresponding to time-related scenario keywords (e.g., "Q4"), thereby increasing the time weight of the corresponding entity and the entity "sales table". The enhanced time weight is equal to the product of the initial time weight of the entity association in the entity association subgraph and the enhancement coefficient. The enhancement coefficient can be set based on the query frequency of the time dimension in the historical access logs. In this embodiment, the enhancement coefficient is set to 1.5. For example, if the initial time weight of "sales table - product table" is 0.7, then the enhanced time weight is 0.7 × 1.5 = 1.05.

[0165] The system dynamically enhances the ER model attribute dimensions ("Regional Table, Regional Attribute", "Product Table, Sales Status Attribute") corresponding to scenario keywords (such as "North China" and "Unsold Goods"). This enhances the scenario weights of the corresponding entities and their corresponding "Regional Table" and "Product Table" entities. The enhanced scenario weight is equal to the product of the initial scenario weight in the entity association subgraph and the enhancement coefficient. For example, if the initial scenario weight of "Sales Table - Regional Table" is 0.6, the enhanced scenario weight will be 0.6 × 1.5 = 0.9. The system then updates the enhanced time weight and scenario weight to the entity association subgraph.

[0166] In some embodiments, the initial SQL statement is generated based on the contextual scene snapshot, entity association subgraph, and KG-LLM collaboration engine, including the following steps:

[0167] S141: Extract entities and relationships from the entity association subgraph based on the knowledge graph to obtain a restricted entity set. The restricted entity set is used to limit the entities and relationships available when the large language model generates the initial SQL statement.

[0168] S142: Input the restricted entity set and context snapshot into the large language model so that the large language model can generate the initial SQL statement.

[0169] In step S141, specifically, the system performs topological structure parsing on the entity association subgraph based on the knowledge graph, extracting metadata of the <entity-relationship-entity> triple, including the data table to which it belongs, attribute dimensions, and the relationship type and related fields between entities. The system will convert the restrictive entity set into constraint rules that can be parsed by the large language model, explicitly prohibiting the use of entities, attributes, and relationships outside the set.

[0170] In step S142, specifically, the system integrates the contextual scene snapshot (entity set, associated edges, and constraints), the restricted entity set (constraint rules), and the associated weights of corresponding entities in the knowledge graph to form a structured input dataset, and encapsulates the input dataset using a structured template. The structured template includes task instructions (generating SQL statements that conform to syntax and match the query intent, specifying only entity relationships), constraint rule segments (constraint rules for the restricted entity set), scene information segments (constraints of the contextual scene snapshot), and format requirements (output SQL statements). The system inputs the structured template into the large language model, enabling the large language model to parse the query intent, match the constraint set, and generate the initial SQL statement.

[0171] In some embodiments, the initial SQL statement is optimized to generate a target SQL statement that matches the user's query text information, including:

[0172] S151: Logical equivalence verification is performed on the initial SQL statement based on the KG-LLM collaborative engine. Logical equivalence verification is used to verify whether there are equivalent optimized substatements in the initial SQL statement.

[0173] S152: In response to the existence of an equivalent optimized sub-statement in the initial SQL statement, generate a target SQL statement that matches the user's query text information based on the equivalent optimized sub-statement.

[0174] In step S151, specifically, the equivalent optimized sub-statement is a query statement with a better query method and equivalent effect. The system loads the SQL semantic equivalence rule base (including rules for index optimization, association method optimization, subquery simplification, etc.) from the knowledge graph based on the KG-LLM collaborative engine as the benchmark for logical equivalence verification. At the same time, the initial SQL statement is parsed to extract core metadata such as syntax structure, entity association path, and query conditions, resulting in a structured SQL parsing result of <entity-relationship-query dimension>.

[0175] The system matches the SQL parsing results against the SQL semantic equivalence rule base to search for SQL statements that are more efficient and logically equivalent. It also verifies the reachability of entity association paths in the initial SQL statement through a knowledge graph and verifies the matching degree between the SQL statement semantics and the user's query intent by combining a large language model. Finally, it cross-determines whether there are effective equivalent optimized substatements.

[0176] In step S152, specifically, if an equivalent optimized sub-statement is retrieved, the equivalent optimized sub-statement with the best query efficiency is selected first, and the initial SQL statement is adjusted in combination with the user's query intent to generate the target SQL statement.

[0177] In some embodiments, the system constructs a local SQL caching mechanism. The local SQL caching mechanism saves user query text information, query intent information, entity relationship subgraphs, contextual snapshots, LLM prompt word templates, and generated SQL statements. When a new adaptation request is triggered, the local cache is queried to extract historical data similar to the user query text information of the new adaptation request, and combined with the LLM generation results to generate more accurate SQL statements.

[0178] Specifically, the system captures and saves the following data to the local SQL cache: user query text information (e.g., "Query for slow-moving goods in North China in Q4"), query intent information (e.g., "North China", "Q4", "slow-moving"), entity relationship subgraph (e.g., active entities and their relationships), contextual snapshot (e.g., "declining sales + inventory backlog"), LLM prompt templates, and generated SQL statements (e.g., structured templates and target SQL statements). This data is stored in both raw text and vector formats, forming a cache database and a cache vector library, respectively.

[0179] When a new adaptation request is triggered, the system accesses the cached vector library to calculate the similarity between the user query text information of the new adaptation request and the user query text information in the historical data. For example, if the user query text information of the new adaptation request is "query of unsold goods in South China Q3", the system will calculate its similarity with "unsold goods in North China Q4" in the historical data using cosine similarity. Finding that the two are highly similar in the definition of "unsold" and the time dimension, differing only in region, the system will extract the SQL statement corresponding to "unsold goods in North China Q4" and quickly generate a new SQL statement based on the new region parameters. For example, the new SQL statement is as follows:

[0180] SELECT Product Name, Sales Volume, Inventory Quantity

[0181] FROM Product List

[0182] JOIN SalesTable ON ProductTable.ProductID = SalesTable.ProductID

[0183] WHERE region = 'South China'

[0184] AND Sales period: July 1, 2023 AND September 30, 2023

[0185] AND sales volume decreased by more than 30% year-on-year.

[0186] AND inventory turnover rate < (SELECT AVG(inventory turnover rate) FROM industry standard table).

[0187] In some embodiments, the context-aware SQL statement generation method further includes: obtaining the SQL statement after the user corrects the target SQL statement and obtaining feedback information; updating the entity relationships in the knowledge graph based on the feedback information; and using the feedback information as training samples for the large language model to update the large language model.

[0188] Specifically, the system will acquire the user's manual adjustment behavior after the system generates the target SQL statement, and use the user's correction of the target SQL statement as feedback information to update the entity relationships in the knowledge graph, LLM training samples, and historical records in the cached vector library.

[0189] For example, if a user manually adjusts "inventory turnover rate < industry average" in the aforementioned SQL statement to "inventory turnover rate < industry average × 0.8", the system will record this correction and use it as a training sample to update the LLM model. This will enable the model to prioritize the use of a stricter inventory turnover rate threshold in subsequent similar queries, generating more accurate SQL statements. Simultaneously, the system will feed this correction back to the knowledge graph, adjusting the weight of inventory turnover rate in the definition of "slow-moving goods," and updating the target SQL statement for this query in the cached vector library, thus enabling continuous learning and optimization of the system.

[0190] It should be noted that in the above embodiments, there is no necessarily a certain order between the steps. Those skilled in the art can understand from the description of the embodiments of this application that the above steps may have different execution orders in different embodiments, that is, they may be executed in parallel or in turn, etc.

[0191] As another aspect of the embodiments of this application, this application provides a context-aware SQL statement generation apparatus. The context-aware SQL statement generation apparatus can be a software module, which includes several instructions stored in a memory. A processor can access the memory and execute the instructions to complete the context-aware SQL statement generation method described in the various embodiments above.

[0192] In some implementations, the context-aware SQL statement generation device can also be built from hardware devices. For example, the context-aware SQL statement generation device can be built from one or more chips, and the chips can work together to complete the context-aware SQL statement generation method described in the various implementations above. As another example, the context-aware SQL statement generation device can also be built from various logic devices, such as general-purpose processors, digital signal processors (DSPs), application-specific integrated circuits (ASICs), field-programmable gate arrays (FPGAs), microcontrollers, ARM (Acorn RISC Machine) or other programmable logic devices, discrete gate or transistor logic, discrete hardware components, or any combination of these components.

[0193] Please see Figure 4 , Figure 4 This is a schematic diagram of the structure of a context-aware SQL statement generation device provided in an embodiment of this application. The context-aware SQL statement generation device 400 provided in this embodiment includes a request acquisition module 401, a high-level semantic scene activation module 402, an entity association subgraph acquisition module 403, a KG-LLM collaboration module 404, and an SQL statement optimization module 405.

[0194] The request acquisition module 401 is used to acquire the adaptation request, which includes user query text information; the high-level semantic scene activation module 402 is used to parse the query intent information in the user query text information and generate a context scene snapshot, which includes scene keywords; the entity association subgraph acquisition module 403 activates the corresponding entity association subgraph in the preset dynamic augmented ER model based on the scene keywords. The dynamic augmented ER model includes multiple entity association subgraphs, and the entity association subgraphs use association weights to represent the association relationships between multiple entities; the KG-LLM collaboration module 404 is used to generate an initial SQL statement based on the context scene snapshot, entity association subgraphs, and the KG-LLM collaboration engine. The KG-LLM collaboration engine integrates knowledge graphs and large language models; the SQL statement optimization module 405 is used to optimize the initial SQL statement and generate a target SQL statement that adapts to the user query text information.

[0195] Please see Figure 5 , Figure 5 This is a schematic diagram of another context-aware SQL statement generation device provided in this application embodiment. The context-aware SQL statement generation device 400 also includes a dynamic ER model construction module 406.

[0196] The dynamic ER model building module 406 is used to: collect multi-source heterogeneous data between the business logic layer and the data access layer to obtain the target data set; build a multi-layer entity association model based on the target data set, which includes a log layer that stores historical access logs; and build a preset dynamic enhanced ER model based on the historical access logs.

[0197] The multi-layer entity association model includes a schema layer, an instance layer, and a log layer. The instance layer includes numerical data, character data, and long text data. The dynamic ER model construction module 406 is specifically used for: in the schema layer, rapidly fusing similar entities and attributes based on a multi-dimensional similarity discrimination algorithm combined with semantic analysis; in the instance layer, generating feature vectors for numerical and character data, and using an autoencoder to generate dense vectors for long text data, performing similarity analysis on the feature vectors and dense vectors to match instances with potential associations between different entities; and in the log layer, analyzing dynamic equivalence relations in different historical access logs to establish dynamic associations between entities and attributes.

[0198] The dynamic ER model construction module 406 is also specifically used for: analyzing historical access logs of the log layer, identifying frequently co-occurring entity pairs, constructing an initial association graph, wherein each entity pair includes at least two different entities; calculating the association weights between entity pairs based on time windows and access frequencies; predicting potential association paths for different entity pairs based on attention mechanisms and graph neural networks; and constructing a preset dynamic enhancement ER model based on the initial association graph, association weights, and association paths.

[0199] The association weights include time weights and scene weights. The entity association subgraph acquisition module 403 is also specifically used to: calculate the similarity between scene keywords and entities in the dynamically enhanced ER model; select the top N entities with the highest similarity to scene keywords, activate the corresponding entity association subgraphs, and enhance the corresponding time weights / scene weights.

[0200] The contextual scene snapshot includes entity sets, associated edges, and constraints. The query intent information includes implicit scene tags. The high-level semantic scene activation module 402 is also specifically used to: parse scene keywords and implicit scene tags in the user query text information based on the preset high-level semantic scene activation module; and generate entity sets, associated edges, and constraints based on scene keywords and implicit scene tags, combined with the preset dynamic enhancement ER model.

[0201] The KG-LLM collaboration module 404 is also specifically used for: extracting entities and relationships from the entity association subgraph based on the knowledge graph to obtain a restricted entity set, which is used to restrict the entities and relationships available when the large language model generates the initial SQL statement; and inputting the restricted entity set and the context scene snapshot into the large language model so that the large language model can generate the initial SQL statement.

[0202] The SQL statement optimization module 405 is also specifically used for: performing logical equivalence verification on the initial SQL statement based on the KG-LLM collaborative engine. The logical equivalence verification is used to verify whether there is an equivalent optimized substatement in the initial SQL statement. The equivalent optimized substatement is a query statement with a better query method and the same effect. In response to the existence of an equivalent optimized substatement in the initial SQL statement, a target SQL statement that is adapted to the user's query text information is generated based on the equivalent optimized substatement.

[0203] Please continue reading. Figure 5 The context-aware SQL statement generation device 400 also includes a correction feedback module 407, which is specifically used for: obtaining the SQL statement after the user corrects the target SQL statement and obtaining feedback information; updating the relationship between entities in the knowledge graph based on the feedback information; and using the feedback information as a training sample for the large language model to update the large language model.

[0204] It should be noted that the aforementioned context-aware SQL statement generation device can execute the context-aware SQL statement generation method provided in the embodiments of this application, and has the corresponding functional modules and beneficial effects of the execution method. Technical details not described in detail in the embodiments of the context-aware SQL statement generation device can be found in the context-aware SQL statement generation method provided in the embodiments of this application.

[0205] See Figure 6 , Figure 6 This is a schematic diagram of the structure of a computer device provided in an embodiment of this application. The computer device includes one or more processors 61 and a memory 62. The memory 62 is connected to one or more processors 61, for example, via a bus.

[0206] Processor 61 is configured to support the computer device in performing the corresponding functions in the methods described in the above method embodiments. Processor 61 may be a central processing unit (CPU), a network processor (NP), a hardware chip, or any combination thereof. The aforementioned hardware chip may be an application-specific integrated circuit (ASIC), a programmable logic device (PLD), or a combination thereof. The aforementioned PLD may be a complex programmable logic device (CPLD), a field-programmable gate array (FPGA), a generic array logic (GAL), or any combination thereof.

[0207] Memory 62 is used to store program code, etc. Memory 62 may include volatile memory (VM), such as random access memory (RAM); memory 62 may also include non-volatile memory (NVM), such as read-only memory (ROM), flash memory, hard disk drive (HDD), or solid-state drive (SSD); memory 62 may also include combinations of the above types of memory.

[0208] The memory 62 can be used to store non-volatile software programs, non-volatile computer-executable programs, and modules, such as the program instructions / modules corresponding to the context-aware SQL statement generation method in the embodiments of this application. The processor 61 executes various functional applications and data processing of the context-aware SQL statement generation method and the context-aware SQL statement generation device by running the non-volatile software programs, instructions, and modules stored in the memory, that is, it realizes the functions of each module or unit of the context-aware SQL statement generation method and the context-aware SQL statement generation device provided in the above method embodiments.

[0209] The memory 62 may include a stored program area and a stored data area, wherein the stored program area may store the operating system and applications required for at least one function. The stored data area may store data created based on the use of the context-aware SQL statement generation device, etc. In some embodiments, the memory 62 may optionally include memory remotely located relative to the processor, which can be connected to the context-aware SQL statement generation device via a network. Examples of such networks include, but are not limited to, the Internet, corporate intranets, local area networks, mobile communication networks, and combinations thereof.

[0210] The one or more modules are stored in the memory 62. When executed by the one or more processors 61, they execute the context-aware SQL statement generation method in any of the above method embodiments. For example, they execute the method steps described in the above method embodiments to realize the functions of the modules described in the above device embodiments.

[0211] This application also provides a computer-readable storage medium storing a computer program, the computer program including program instructions, which, when executed by a computer device, cause the computer device to perform the method described in the foregoing embodiments.

[0212] Those skilled in the art will understand that all or part of the processes in the above embodiments can be implemented by a computer program instructing related hardware. The program can be stored in a computer-readable storage medium, and when executed, it can include the processes of the embodiments of the above methods. The storage medium can be a magnetic disk, optical disk, read-only memory (ROM), or random access memory (RAM), etc.

[0213] The above-disclosed embodiments are merely preferred embodiments of this application and should not be construed as limiting the scope of this application. Therefore, any equivalent variations made in accordance with the claims of this application shall still fall within the scope of this application.

Claims

1. A context-aware SQL statement generation method, characterized in that, include: Obtain the adaptation request, which includes user query text information; Parsing the query intent information in the user's query text and generating a contextual scene snapshot, wherein the query intent information includes scene keywords, the contextual scene snapshot includes entity sets, associated edges and constraints, and the query intent information also includes implicit scene tags, the process of parsing the query intent information in the user's query text and generating a contextual scene snapshot includes: The preset high-level semantic scene activation module parses the scene keywords and implicit scene tags in the user query text information; based on the scene keywords and implicit scene tags, and combined with the preset dynamic enhanced ER model, the entity set, the associated edges and the constraints are generated. The entity association subgraph in the preset dynamic augmented ER model is activated based on the scene keywords. The dynamic augmented ER model includes multiple entity association subgraphs. Each entity association subgraph uses association weights to represent the association relationships between multiple entities. The association weights include time weights and scene weights. The entity association subgraph in the preset dynamic augmented ER model is activated based on the scene keywords, including: Calculate the similarity between the scene keywords and the entities in the dynamically enhanced ER model; select the top N entities with the highest similarity to the scene keywords, activate the corresponding entity association subgraph, and enhance the corresponding time weight or scene weight; The initial SQL statement is generated based on the contextual scene snapshot, the entity association subgraph, and the KG-LLM collaborative engine. The KG-LLM collaborative engine integrates knowledge graphs and large language models. The generation of the initial SQL statement based on the contextual scene snapshot, the entity association subgraph, and the KG-LLM collaborative engine includes: Based on the knowledge graph, entities and relationships are extracted from the entity association subgraph to obtain a restricted entity set. The restricted entity set is used to restrict the entities and relationships available when the large language model generates the initial SQL statement. The restricted entity set and the context scene snapshot are input into the large language model to enable the large language model to generate the initial SQL statement. The initial SQL statement is optimized to generate a target SQL statement that matches the user's query text information.

2. The method according to claim 1, characterized in that, It also includes constructing the preset dynamically enhanced ER model, wherein constructing the preset dynamically enhanced ER model includes: Multi-source heterogeneous data collection is performed between the business logic layer and the data access layer to obtain the target data set; A multi-layer entity association model is constructed based on the target data set. The multi-layer entity association model includes a log layer, which stores historical access logs. The preset dynamically enhanced ER model is constructed based on the historical access logs.

3. The method according to claim 2, characterized in that, The multi-layer entity association model includes a schema layer, an instance layer, and a log layer. The instance layer includes numerical data, character data, and long text data. The construction of the multi-layer entity association model based on the target data set includes: In the pattern layer, based on a multi-dimensional similarity discrimination algorithm combined with semantic analysis, similar entities and attributes are rapidly fused. In the instance layer, feature vectors of the numerical data and the character data are generated, and a dense vector of the long text data is generated using an autoencoder. Similarity analysis is performed on the feature vectors and the dense vectors to match instances with potential relationships between different entities. In the log layer, dynamic equivalence relationships in different historical access logs are analyzed to establish dynamic associations between entities and attributes.

4. The method according to claim 2, characterized in that, The step of constructing the preset dynamically enhanced ER model based on the historical access logs includes: The historical access logs of the log layer are analyzed to identify frequently co-occurring entity pairs and construct an initial association graph. The entity pairs include at least two different entities. The association weight between the entity pairs is calculated based on the time window and access frequency. Predict potential association paths for different entity pairs based on attention mechanisms and graph neural networks; The preset dynamic enhancement ER model is constructed based on the initial association graph, the association weights, and the association paths.

5. The method according to claim 1, characterized in that, The optimization of the initial SQL statement to generate a target SQL statement adapted to the user's query text information includes: The initial SQL statement is logically equivalent to the KG-LLM collaborative engine. The logical equivalence verification is used to verify whether there is an equivalent optimized substatement in the initial SQL statement. In response to the existence of the equivalent optimized sub-statement in the initial SQL statement, the target SQL statement adapted to the user query text information is generated based on the equivalent optimized sub-statement.

6. The method according to claim 1, characterized in that, Also includes: Obtain the SQL statement after the user corrects the target SQL statement, and get feedback information; The association relationships of entities in the knowledge graph are updated based on the feedback information; The feedback information is used as training samples for the large language model to update the large language model.

7. A context-aware SQL statement generation device, characterized in that, include: The request acquisition module is used to acquire adaptation requests, which include user query text information; A high-level semantic scene activation module is used to parse the query intent information in the user query text information and generate a context scene snapshot. The query intent information includes scene keywords, and the context scene snapshot includes entity sets, association edges, and constraints. The query intent information also includes implicit scene tags. Parsing the query intent information in the user query text information and generating a context scene snapshot includes: parsing the scene keywords and implicit scene tags in the user query text information based on a preset high-level semantic scene activation module; and generating the entity set, association edges, and constraints based on the scene keywords and implicit scene tags, combined with a preset dynamic augmented ER model. The entity association subgraph acquisition module activates the corresponding entity association subgraph in a preset dynamic augmented ER model based on the scene keywords. The dynamic augmented ER model includes multiple entity association subgraphs, and the entity association subgraphs use association weights to represent the association relationships between multiple entities. The association weights include time weights and scene weights. The step of activating the corresponding entity association subgraph in the preset dynamic augmented ER model based on the scene keywords includes: calculating the similarity between the scene keywords and the entities in the dynamic augmented ER model; selecting the top N entities with the highest similarity to the scene keywords, activating the corresponding entity association subgraphs, and enhancing the corresponding time weights or scene weights. The KG-LLM collaboration module is used to generate an initial SQL statement based on the contextual snapshot, the entity association subgraph, and the KG-LLM collaboration engine. The KG-LLM collaboration engine integrates a knowledge graph and a large language model. Generating the initial SQL statement based on the contextual snapshot, the entity association subgraph, and the KG-LLM collaboration engine includes: extracting entities and relationships from the entity association subgraph based on the knowledge graph to obtain a restricted entity set, which restricts the entities and relationships available when the large language model generates the initial SQL statement; and inputting the restricted entity set and the contextual snapshot into the large language model to enable the large language model to generate the initial SQL statement. The SQL statement optimization module is used to optimize the initial SQL statement and generate a target SQL statement that is adapted to the user's query text information.

Citation Information

Patent Citations

  • Query generation method in Text2SQL (Structured Query Language) task based on large language model

    CN119938698A

  • Database query statement generation method and device, equipment, medium and product

    CN121009212A