Text-to-sql generation system and intelligent question answering method
By generating business semantic labels and constructing lineage graphs for the property rights database, and combining graph neural networks and large language models, the problems of insufficient semantic understanding and uncontrollable results in property rights data queries are solved, achieving high-quality SQL generation and accurate query results.
Patent Information
- Application Number
- CN202611607840.3
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2026-10-16
- Publication Date
- 2026-11-27
AI Technical Summary
Existing Text-to-SQL technology suffers from insufficient semantic understanding, missing data relationships, uncontrollable result quality, and weak domain adaptability in property rights data queries, resulting in high query thresholds, incorrect JOIN paths, and misleading results from dirty data.
By generating business semantic tags for the property rights database, constructing a lineage graph, and combining graph neural networks and large language models, vector retrieval and self-correction are achieved, generating high-quality SQL statements.
It improves the accuracy of SQL generation, enhances the ability to process complex queries, ensures the quality and reliability of query results, and adapts to the special needs of property rights data.
Smart Images

Figure CN123178577A_ABST
Abstract
Description
Technical Field
[0001] This invention relates to the field of natural language processing technology, specifically to a Text-to-SQL generation system and an intelligent question-answering method. Background Technology
[0002] With the rapid development of big data technology, enterprises have accumulated massive amounts of structured data. This issue is particularly prominent in the field of property rights management: property rights data possesses complex characteristics such as a hierarchical tree structure (enterprise levels 1-5), equity penetration relationships, and multiple-caliber fields (CALIBER), making queries more difficult for non-technical personnel. Text-to-SQL technology can automatically convert natural language queries into executable SQL statements, lowering the query threshold.
[0003] Currently, representative works on Text-to-SQL include DAIL-SQL and WrenAI. DAIL-SQL uses CRP (Comprehensive Schema Representation) to provide a complete database table structure. Through the DAIL mechanism, it selects few-shot examples from the example pool based on the similarity between the question and the SQL, then organizes the Question-SQL pairs according to a specific format, and inputs them along with the user question into an LLM (Large Language Model), which generates the SQL. WrenAI, on the other hand, uses MDL to define the table structure, relationships, and business rules. It stores table descriptions, SQL pairs, and business rules in independent vector sets. During retrieval, it first finds candidate tables through vector similarity, then uses an LLM to refine the necessary columns, and finally inputs the selected context and user question into the LLM to generate the SQL.
[0004] Despite the significant progress made by the above methods, the following drawbacks still exist: (1) Insufficient semantic understanding: Relying on Few-shot examples or manually written metadata descriptions, property data fields often lack business annotations, resulting in limited search results.
[0005] (2) Missing data relationships: Property data involves a large number of multi-table associations and recursive queries (such as the CONNECTBY recursive query of the property tree). The above solution is prone to generating incorrect JOIN paths or missing necessary tables.
[0006] (3) Uncontrollable result quality: The above scheme only checks the correctness of SQL syntax, but does not verify the data quality of the query results returned after SQL execution. Dirty data (missing values, outliers, and inconsistencies between multiple standards) in the property data may lead to misleading results.
[0007] (4) Weak domain adaptability: Due to the complex characteristics of property rights data, general solutions are difficult to handle effectively. Summary of the Invention
[0008] This invention provides a Text-to-SQL generation system and an intelligent question-answering method to solve one of the technical problems existing in the prior art.
[0009] In a first aspect, the present invention provides a Text-to-SQL generation system, which includes a data governance layer, a vector retrieval layer and an SQL generation layer; The data governance layer is used to generate business semantic tags for each field in the property rights database and associate the business semantic tags with the property rights database to obtain an enhanced database. The business semantic tags represent the business interpretation of the fields. The data governance layer is also used to parse historical SQL statements to build a lineage graph, which represents the relationships between tables and fields in the property database; The vector retrieval layer is used to identify the property data features queried by the user and retrieve the contextual information of the user query based on the user query, the enhanced database, and the pedigree map. The SQL generation layer is used to generate SQL statements for user queries based on SQL templates corresponding to context information and property data characteristics, and to perform self-correction based on the SQL statements and their execution results to obtain the generated results.
[0010] This invention generates business semantic tags for each field in the property rights database through a data governance layer, and associates these tags with the property rights database to obtain an enhanced database, enabling the system to understand the business meaning of the fields. The data governance layer also parses historical SQL statements to construct a lineage graph, explicitly modeling the relationships between tables and fields, avoiding the generation of incorrect JOIN paths or the omission of necessary tables. The vector retrieval layer identifies the property rights data characteristics queried by the user, and based on the user query, the enhanced database, and the lineage graph, retrieves the contextual information of the user query. This allows it to determine the property rights scenario to which the user query belongs and retrieve relevant contextual information, providing subsequent generation with both semantic and relational basis. The SQL generation layer generates SQL statements that conform to the structural characteristics of the property rights data based on the contextual information and the SQL templates corresponding to the property rights data characteristics. It also performs self-correction based on the SQL statements and their execution results, improving the quality of generated SQL statements. Overall, the data governance layer provides the foundation for business semantics and associations, the vector retrieval layer identifies query intent and retrieves relevant context, and the SQL generation layer generates and corrects SQL statements based on context and domain templates. The three layers work together to achieve automatic conversion from natural language queries to high-quality SQL statements and achieve domain adaptation for property data.
[0011] In one alternative implementation, the data governance layer includes a semantic annotation engine, which includes a first parsing submodule, a sampling submodule, an annotation submodule, and an association submodule. The first parsing submodule is used to extract metadata from the property rights database; The sampling submodule is used to sample multiple data records from the property rights database, covering multiple business scenarios; The annotation submodule is used to input metadata and multiple data records into the large language model and generate business semantic tags for each field in the metadata; The association submodule is used to associate business semantic tags with the property database to obtain an enhanced database.
[0012] This invention extracts metadata from the property rights database through a first parsing submodule, providing a structural foundation for semantic annotation. A sampling submodule samples multiple data records from the property rights database, covering various business scenarios. An annotation submodule inputs the metadata and multiple data records into a large language model to generate business semantic tags for the fields, addressing the problem of limited retrieval performance when relying on manual annotation or when fields lack business semantics. An association submodule associates the business semantic tags with the property rights database, resulting in an enhanced database. This allows the business semantics of the fields to be used in subsequent retrieval and generation processes, improving the accuracy of subsequent retrieval and SQL generation.
[0013] In one alternative implementation, the data governance layer further includes a lineage tracing engine, which includes a collection submodule, a second parsing submodule, an extraction submodule, and a construction submodule. The data collection submodule is used to retrieve historical SQL statements executed from the property rights database; The second parsing submodule is used to parse historical SQL statements into an abstract syntax tree; The extraction submodule is used to traverse the abstract syntax tree and extract relational information from historical SQL statements; The construction submodule is used to treat the tables and fields in the metadata as nodes, and to build edges between the nodes based on the relationship information and metadata to form a lineage graph.
[0014] This invention acquires historical SQL statements executed on a property database through a collection submodule, serving as the data source for lineage tracing and reflecting how tables and fields are actually associated and used. A second parsing submodule parses the historical SQL statements into an abstract syntax tree, breaking them down into traversable clauses and nodes. An extraction submodule traverses the abstract syntax tree to extract relational information from the historical SQL statements. A construction submodule uses tables and fields from the metadata as nodes, constructing edges between nodes based on relational information and metadata to form a lineage graph. This explicitly models the relationships between tables and fields, enabling the system to determine the correct association path when dealing with multi-table joins or recursive queries, avoiding the generation of incorrect JOIN paths or the omission of necessary tables.
[0015] In one alternative implementation, the data governance layer further includes a quality checker for performing consistency checks on the edges of the lineage graph. The extraction submodule is also used to re-extract relational information from historical SQL statements when consistency checks fail. The submodule is also used to reconstruct the kinship map based on the re-extracted relationship information; The quality checker is also used to perform consistency checks on the edges of the reconstructed lineage graph again, and outputs an error message when the number of checks exceeds the preset number of checks.
[0016] This invention uses a quality checker to perform consistency checks on the edges of the kinship graph. If the check fails, the relationship information is re-extracted and the kinship graph is reconstructed. The quality checker then checks again and outputs an error message when the number of checks exceeds a preset number. This allows erroneous associations in the kinship graph to be detected and corrected in a timely manner, preventing individual erroneous edges from affecting subsequent retrieval and generation. At the same time, the preset number of checks prevents the graph from getting stuck in an infinite loop when it repeatedly fails.
[0017] In one optional implementation, the vector retrieval layer includes an encoding module and a retrieval module; The encoding module is used to embed nodes into the kinship map using a graph neural network. The encoding module is also used to generate edge-level vectors and generate table-level and field-level vectors of the lineage graph based on node embedding, which together form the lineage vector. The field-level vector is obtained by fusing field node embedding with the business semantic tags of the corresponding fields. The retrieval module is used to generate contextual information based on kinship vectors and user queries.
[0018] This invention uses an encoding module to embed nodes into a kinship graph via a graph neural network, converting table nodes and field nodes in the kinship graph into vector representations. The encoding module generates edge-level vectors, field-level vectors, and table-level vectors, which together form a kinship vector. The retrieval module generates context information based on the kinship vector and the user query, ensuring that the context information simultaneously includes tables, fields, and related paths relevant to the user query. This provides a basis for subsequent SQL generation and improves the accuracy of SQL generation.
[0019] In one alternative implementation, the retrieval module is specifically used for: The user query is transformed into a query vector. The first similarity between the query vector and each edge-level vector in the lineage vector is calculated. The edges corresponding to all edge-level vectors are sorted according to the first similarity to determine the edge set. Calculate the second similarity between the query vector and each table-level vector in the lineage vector, sort the tables corresponding to all table-level vectors according to the second similarity, and determine the table set; Calculate the third similarity between the query vector and the kinship vector for each field-level vector, sort the fields corresponding to all field-level vectors according to the third similarity, and determine the field set; Calculate the fourth similarity between the query vector and each example in the sample example library, sort all examples in descending order according to the fourth similarity, and determine the example set. Each example includes the sample user query and its SQL statement. The edge set, table set, field set, and example set are used as context information for user queries.
[0020] This invention transforms user queries into query vectors through a retrieval module. Similarity is calculated between these vectors and the edge-level, table-level, and field-level vectors within the lineage vector. Based on this similarity, the edge set, table set, and field set are determined, ensuring that the retrieval results comprehensively cover data objects similar to the user query from three levels: association path, table, and field. Simultaneously, the retrieval module calculates the similarity between the query vector and each example in the sample example library, determining the example set and providing a writing reference for similar queries. By using the edge set, table set, field set, and example set together as contextual information, subsequent SQL generation has clear table and field bases, correct association paths, and referential example writing, thereby improving the accuracy of SQL generation.
[0021] In one optional implementation, the SQL generation layer includes a generation module and a validation module; The generation module is used to generate SQL statements based on the SQL template corresponding to context information and property data characteristics using a large language model; The validation module is used to perform syntax and logic validation on SQL statements, and to perform quality validation on the execution results of the SQL statements, so as to obtain a comprehensive validation result. The generation module is also used to generate SQL statements as the result when the comprehensive verification result is passed.
[0022] This invention employs a large language model in its generation module to generate SQL statements based on contextual information and SQL templates corresponding to property rights data characteristics, ensuring that the generated SQL is both accurate and adapted to the property rights domain. The validation module performs syntax and logic checks on the SQL statements and quality checks on the execution results. When the overall validation result passes, the generation module uses the SQL statement as the generated result, thus improving the quality of the generated SQL statements.
[0023] In one optional implementation, the SQL generation layer further includes a feedback module and a retry control module; The feedback module is used to send the comprehensive verification result back to the large language model to regenerate the SQL statement when the comprehensive verification result is not passed. The retry control module is used to count the number of times the large language model generates SQL statements. When the number of retry exceeds the preset number of retries, the large language model generates query suggestions as the result.
[0024] This invention uses a feedback module to send the comprehensive verification result back to the large language model when the comprehensive verification fails, allowing the large language model to regenerate the SQL statement. This enables the large language model to make targeted modifications based on the anomalies detected during verification. The retry control module counts the number of times the large language model generates the SQL statement. When the number of retryes exceeds a preset limit, a query suggestion is generated as the final result, preventing the system from falling into endless retries.
[0025] Secondly, the present invention provides an intelligent question-answering method, the method comprising: Get user queries; The generated results of the user query are obtained through the Text-to-SQL generation system of the first aspect or any of its corresponding implementations; When the generated result is an SQL statement, the SQL statement is executed to obtain the query results from the user's query.
[0026] This invention achieves intelligent question answering by acquiring user queries, generating query results through a Text-to-SQL generation system, and executing SQL statements when the generated results are SQL statements to obtain the query results. Furthermore, since the generated results are produced by the Text-to-SQL generation system, the SQL statements have undergone semantic enhancement, lineage tracing, and self-correction, ensuring greater accuracy and reliability of the returned query results and guaranteeing the accuracy of the intelligent question answering.
[0027] In one alternative implementation, the method further includes: When the generated result is a query suggestion, the user query is modified according to the query suggestion, and the process returns to the Text-to-SQL generation system of the first aspect or any of its corresponding implementations to obtain the generated result of the user query.
[0028] This invention improves the success rate of the question-and-answer process and enhances the user experience by modifying the user's query according to the query suggestion when the result is generated as a query suggestion, and then regenerating the result.
[0029] Thirdly, the present invention provides an intelligent question-answering device, the device comprising: The query retrieval module is used to retrieve user queries; The query generation module is used to obtain the generated results of the user query through the Text-to-SQL generation system of the first aspect or any of its corresponding implementations; The query execution module is used to execute SQL statements when the generated result is an SQL statement, and obtain the query results of the user's query.
[0030] Fourthly, the present invention provides an electronic device, comprising: a memory and a processor, wherein the memory and the processor are communicatively connected to each other, the memory stores computer instructions, and the processor executes the computer instructions to perform the intelligent question-answering method of the second aspect above or any corresponding embodiment thereof.
[0031] Fifthly, the present invention provides a computer-readable storage medium storing computer instructions for causing a computer to execute the intelligent question-answering method of the second aspect or any corresponding embodiment thereof. Attached Figure Description
[0032] To more clearly illustrate the specific embodiments of the present invention or the technical solutions in the prior art, the drawings used in the description of the specific embodiments or the prior art will be briefly introduced below. Obviously, the drawings described below are some embodiments of the present invention. For those skilled in the art, other drawings can be obtained from these drawings without creative effort.
[0033] Figure 1 This is a schematic diagram of a Text-to-SQL generation system according to an embodiment of the present invention; Figure 2 This is a flowchart of an intelligent question-answering method according to an embodiment of the present invention; Figure 3 This is a structural block diagram of an intelligent question-answering device according to an embodiment of the present invention; Figure 4 This is a schematic diagram of the hardware structure of an electronic device according to an embodiment of the present invention. Detailed Implementation
[0034] To make the objectives, technical solutions, and advantages of the embodiments of the present invention clearer, the technical solutions of the embodiments of the present invention will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of the present invention, not all embodiments. Based on the embodiments of the present invention, all other embodiments obtained by those skilled in the art without creative effort are within the scope of protection of the present invention.
[0035] It is understood that before using the technical solutions disclosed in the various embodiments of the present invention, users should be informed of the types, scope of use, and usage scenarios of the personal information involved in the present invention and their authorization should be obtained in accordance with relevant laws and regulations through appropriate means.
[0036] The terms "first" and "second" are used for descriptive purposes only and should not be construed as indicating or implying relative importance or implicitly specifying the number of technical features indicated. Thus, a feature defined as "first" or "second" may explicitly or implicitly include one or more of that feature. In the description of this invention, "a plurality of" means two or more, unless otherwise explicitly specified.
[0037] Figure 1 This is a schematic diagram of a Text-to-SQL generation system according to an embodiment of the present invention, such as... Figure 1 As shown, the system includes a data governance layer, a vector retrieval layer, and an SQL generation layer. The data governance layer generates business semantic tags for each field in the property rights database and associates these tags with the database to obtain an enhanced database. The business semantic tags represent the business interpretation of the fields. The data governance layer also parses historical SQL statements to construct a lineage graph, which represents the relationships between tables and fields in the property rights database. The vector retrieval layer identifies the property rights data features queried by the user and retrieves the context information of the user query based on the user query, the enhanced database, and the lineage graph. The SQL generation layer generates the SQL statement for the user query based on the context information and the SQL template corresponding to the property rights data features, and performs self-correction based on the SQL statement and its execution result to obtain the generated result.
[0038] Specifically, the data governance layer generates business semantic tags for fields in the property rights database. These tags include the field's business meaning and common values. The business meaning explains what the field represents in a business context; for example, CALIBER represents statistical caliber, and REG_CAP represents registered capital. Common values describe the actual values the field can have and their meanings; for example, a CALIBER value of 01 represents a consolidated caliber, and a value of 02 represents a parent company caliber. This structured description of the field's business meaning, common values, and their correspondence with business concepts is then applied to the original table structure of the property rights database. These business semantic tags are then linked to form a database structure that includes both technical and business definitions, serving as an enhanced database. The data governance layer also parses historical SQL statements, extracting table relationships and field dependencies to construct a lineage graph, explicitly modeling the relationships between tables and fields in the property rights database.
[0039] After receiving a user query, the vector retrieval layer performs two processes. First, it identifies whether the user query contains preset terms corresponding to property rights data features to determine if the query involves hierarchical features, multi-caliber features, or equity penetration features. Specifically, hierarchical features refer to semantics related to hierarchical relationships within enterprises, corresponding to the tree-like hierarchical structure in property rights data. Preset terms include "subordinate," "subsidiary," and "third-level subsidiary," used to determine whether recursive queries are needed. Multi-caliber features refer to semantics related to statistical calibers, corresponding to the multi-caliber field (CALIBER) in property rights data. Preset terms include "consolidated caliber" and "parent company caliber," used to determine whether caliber filtering conditions need to be added. Equity penetration features refer to semantics related to equity tracing, corresponding to the equity relationship chain in property rights data. Preset terms include "equity penetration," "ultimate controlling party," and "actual controller," used to determine whether recursive tracing along the equity relationship is necessary. By identifying these features, the vector retrieval layer can determine the user's query intent within the property rights data context, providing a basis for subsequently calling the corresponding SQL template. Secondly, by combining the semantic understanding carried by the enhanced database with the data relationships carried by the lineage graph, contextual information related to the user query can be retrieved, enabling the SQL generation process to obtain support from both business semantics and data association.
[0040] Finally, the SQL generation layer generates the SQL statement for the user query based on the context information and the SQL template corresponding to the property data characteristics queried by the user. It also performs self-correction on the SQL statement and its execution result to improve the quality of the generated SQL statement.
[0041] Thus, the data governance layer provides the semantic and data relationship foundation, the vector retrieval layer provides contextual information related to user queries, and the SQL generation layer generates and corrects SQL statements based on this contextual information. The three layers work together to achieve automatic conversion from natural language queries to high-quality SQL statements and achieve property rights domain adaptation.
[0042] In one optional implementation, the data governance layer includes a semantic annotation engine, which comprises a first parsing submodule, a sampling submodule, an annotation submodule, and an association submodule. The first parsing submodule is used to extract metadata from the property rights database. The sampling submodule is used to sample multiple data records from the property rights database, with the multiple data records covering multiple business scenarios. The annotation submodule is used to input the metadata and multiple data records into a large language model to generate business semantic tags for each field in the metadata. The association submodule is used to associate the business semantic tags with the property rights database to obtain an enhanced database.
[0043] Specifically, the first parsing submodule parses the DDL (Data Definition Language) of the property rights database, extracting metadata such as tables, fields, data types, constraints, index information, and partition information. The sampling submodule samples N data records from the property rights database. The company name field in these records needs to have special semantics, special characters, and classic business scenarios, such as a port company (including docks), to ensure the data records are representative. Sampling can employ strategies such as random sampling, hierarchical sampling covering various enumerated values, and extreme value sampling. The annotation submodule inputs the metadata and multiple data records into the large language model according to a preset format, generating business semantic tags for each field. The association submodule associates and stores the generated business semantic tags in JSON format with the original schema of the property rights database, forming an enhanced database that provides a semantic foundation for subsequent vector retrieval and SQL generation.
[0044] Optionally, the annotation submodule can also use a lightweight NLP (Natural Language Processing) model, such as TF-IDF (Term Frequency-Inverse Document Frequency) + keyword matching, to replace the large language model for semantic annotation. This can reduce computational costs and is suitable for cost-sensitive scenarios where database field annotations are relatively complete.
[0045] In one optional implementation, the data governance layer further includes a lineage tracing engine, which comprises a collection submodule, a second parsing submodule, an extraction submodule, and a construction submodule. The collection submodule is used to obtain historical SQL statements executed on the property database. The second parsing submodule is used to parse the historical SQL statements into an abstract syntax tree. The extraction submodule is used to traverse the abstract syntax tree and extract relational information from the historical SQL statements. The construction submodule is used to take the tables and fields in the metadata as nodes, and build edges between the nodes based on the relational information and metadata to form a lineage graph.
[0046] Specifically, the acquisition submodule collects historically executed SQL statements from the audit logs of the property database or application system logs, reflecting how tables and fields in the database are actually related and used, serving as the data source for lineage tracing. The second parsing submodule uses an SQL parser (such as js-sql-parser or antlr4) to parse the historical SQL statements into an Abstract Syntax Tree (AST), thus breaking down the SQL statements into traversable clauses and nodes. The extraction submodule traverses the AST to extract relational information from the historical SQL statements, specifically including: extracting table relationships in the FROM / JOIN clauses, field dependencies in the SELECT clause, filtering conditions in the WHERE clause, and aggregation relationships in the GROUP BY clause.
[0047] The construction submodule treats tables and fields from the metadata as nodes. For relationship information, when two tables are related by a JOIN condition, a table-level edge is created between the corresponding table nodes; when one field depends on another, a field-level edge is created between the corresponding field nodes. For foreign key constraints in the metadata, when a field in one table references the primary key of another table, a foreign key association edge is created between the corresponding field nodes. This results in a lineage graph composed of table nodes, field nodes, and edges.
[0048] Optionally, for each edge, if it is constructed based on relational information, the frequency of this relational information appearing in historical SQL statements is counted, and the edge weight is determined by combining the complexity of the historical user queries corresponding to the historical SQL statements. The more frequently it appears and the more complex the query, the higher the weight. If it is constructed based on foreign key constraints, its weight is uncertain; that is, foreign key related edges do not participate in the weight calculation and only exist as associations in the graph. The complexity is determined by the number of tables involved in the user query, whether it contains JOIN, aggregation, grouping, recursion, subqueries, multi-caliber queries, equity penetration, and other characteristics.
[0049] Optionally, the second parsing submodule can also use predefined rule templates to extract relational information, which is suitable for scenarios where the database is highly stable and changes infrequently.
[0050] In one optional implementation, the data governance layer further includes a quality validator for performing consistency checks on the edges of the lineage graph; an extraction submodule for re-extracting relational information from historical SQL statements when consistency checks fail; a construction submodule for reconstructing the lineage graph based on the re-extracted relational information; and a quality validator for performing consistency checks on the edges of the reconstructed lineage graph again, and outputting an error message when the number of checks exceeds a preset number of checks.
[0051] Specifically, the quality validator performs consistency checks on the edges of the lineage graph. For table-level edges, it checks whether the association between the two tables on both sides of the edge is valid, that is, whether both tables contain the corresponding associated fields in the JOIN condition or foreign key constraint on which the edge is based. For field-level edges, it checks whether the fields on both sides of the edge point to the same business entity, whether the data types match, and whether the business semantic tags are consistent.
[0052] If any edge fails the check, the consistency check of the kinship graph is considered to have failed. The extraction submodule re-extracts the relationship information, and the construction submodule reconstructs the kinship graph based on the re-extracted relationship information. The quality checker then performs consistency check on the edges of the reconstructed kinship graph again, and outputs an error message when the number of checks exceeds the preset number of checks.
[0053] Thus, through the aforementioned closed loop, erroneous associations in the kinship map can be detected and corrected in a timely manner, preventing erroneous edges from affecting subsequent retrieval and generation.
[0054] In one optional implementation, the vector retrieval layer includes an encoding module and a retrieval module; the encoding module is used to embed nodes into the lineage graph through a graph neural network; the encoding module is also used to generate edge-level vectors, and generate table-level vectors and field-level vectors of the lineage graph based on node embedding, which together form the lineage vector, and the field-level vector is obtained by fusing field node embedding with the business semantic tags of the corresponding fields; the retrieval module is used to generate context information based on the lineage vector and user query.
[0055] Specifically, the encoding module uses a Graph Neural Network (GNN), preferably employing GraphSAGE or GAT models for node embedding, to convert nodes in the lineage graph into vector representations. For field node embeddings, the encoded results are fused with the business semantic labels of that field node to obtain field-level vectors, which simultaneously possess structural information and business semantics, enabling field matching based on business meaning during retrieval. The encoded results of the business semantic labels are obtained using a BERT-like pre-trained model. Table-level vectors are generated by fusing table node embeddings with the pooling results of all field node embeddings within that table, resulting in vectors representing the field information contained in the entire table. Edge-level vectors are generated by using an MLP (Multilayer Perceptron) / attention mapping to determine the association paths between tables or between fields during retrieval. The field-level vectors, table-level vectors, and edge-level vectors are combined to form the lineage vector.
[0056] The retrieval module performs a search based on the lineage vector and the user query to obtain contextual information related to the user query.
[0057] In one optional implementation, the retrieval module is specifically configured to: convert the user query into a query vector; calculate the first similarity between the query vector and each edge-level vector in the lineage vector; sort the edges corresponding to all edge-level vectors according to the first similarity to determine the edge set; calculate the second similarity between the query vector and each table-level vector in the lineage vector; sort the tables corresponding to all table-level vectors according to the second similarity to determine the table set; calculate the third similarity between the query vector and each field-level vector in the lineage vector; sort the fields corresponding to all field-level vectors according to the third similarity to determine the field set; calculate the fourth similarity between the query vector and each example in the sample example library; sort all examples in descending order according to the fourth similarity to determine the example set, where each example includes the sample user query and its SQL statement; and use the edge set, table set, field set, and example set as context information for the user query.
[0058] Specifically, the user query is transformed into a query vector, and the first similarity between the query vector and each edge-level vector in the lineage vector is calculated. The higher the similarity, the more relevant the association represented by the edge is to the user query. The edges corresponding to all edge-level vectors are sorted according to the first similarity, and the top a edges are taken to form an edge set, which is used to determine the association path between tables and between fields, so as to avoid missing necessary tables or using the wrong JOIN path when generating SQL.
[0059] Calculate the second similarity between the query vector and each table-level vector in the lineage vector. The higher the similarity, the more relevant the table is to the user query. Sort all tables corresponding to the table-level vectors according to the second similarity, and take the top b tables to form a table set to determine which tables the user query involves, providing a basis for table selection in subsequent SQL generation.
[0060] The third similarity is calculated between the query vector and each field-level vector in the lineage vector. The higher the similarity, the more relevant the field is to the user's query. All fields corresponding to the field-level vectors are sorted according to the third similarity, and the top c fields are selected to form a field set. The field-level vectors are generated by fusing field node embeddings with business semantic tags. They represent both the structural position of the field in the lineage graph and the business meaning of the field, used to accurately match the fields involved in the user's query.
[0061] The sample example library is a collection of reference examples selected from historical queries, manually verified as correct, and relevant to the property rights field. Each example includes a sample user query and its corresponding sample SQL statement, for example: Q: Does a certain power plant belong to a certain group? SQL: SELECT CASE WHEN COUNT(1)>0 THEN 'Yes' ELSE 'No' END FROM power_plant p JOIN equity_relation e ON p.plant_id = e.subsidiary_id JOIN company c ON e.parent_company_id = c.company_id WHERE p.plant_name = 'a certain power plant' AND c.company_name = 'a certain group' Each example in the sample example library is transformed into an example vector. The cosine similarity between the query vector and each example vector is calculated as the fourth similarity. All examples are sorted in descending order according to the fourth similarity, and the top d examples are taken to form an example set. These examples are most similar to the current query, and the SQL statement for the current query can be generated by referring to the SQL statements of these examples.
[0062] Using the edge set, table set, field set, and example set as context information for user queries, this context information simultaneously includes semantic field information, lineage-level association information, and example-level writing references. This ensures that the generated SQL has clear table and field basis, correct association paths, and writing examples for similar problems, thereby improving the accuracy of SQL generation.
[0063] In one optional implementation, the SQL generation layer includes a generation module and a verification module; the generation module is used to generate SQL statements using a large language model and based on SQL templates corresponding to context information and property data characteristics; the verification module is used to perform syntax verification and logic verification on the SQL statements, and to perform quality verification on the execution results obtained by executing the SQL statements to obtain a comprehensive verification result; the generation module is also used to use the SQL statement as the generation result when the comprehensive verification result is passed.
[0064] Specifically, property rights data possesses unique structures such as tree-like hierarchies, multiple definitions, and equity penetration, making it difficult to handle correctly with general syntax. Only by selecting a template corresponding to the user's query can SQL be generated that conforms to the characteristics of the property rights data. If the property rights data queried by the user has hierarchical characteristics, a preset recursive SQL template is used; if the property rights data has multiple definitions, a preset multi-definition template is used, including WHERE conditions; if the property rights data has equity penetration characteristics, a preset equity penetration recursive template is used, supporting step-by-step tracing along equity relationships to identify the ultimate controlling party. The generation module uses a large language model, generating SQL statements based on contextual information within the SQL template writing framework.
[0065] The validation module performs syntax and logic checks on SQL statements. Syntax validation uses the SQL parser to check the syntactic correctness of the SQL statement; if syntax errors are found, the error information is included in the validation result. Logic validation verifies the logical rationality of the SQL statement using the EXPLAIN execution plan, specifically detecting performance issues such as full table scans and Cartesian products; if logical problems are found, they are also included in the validation result. Furthermore, even syntactically and logically correct SQL statements may still produce misleading results due to dirty data in the database (missing values, outliers, inconsistencies between different definitions). Therefore, the validation module also executes the SQL statement and performs quality checks on the execution result, specifically including integrity checks, validity checks, consistency checks, and distribution rationality checks. The integrity check includes checking the proportion of non-nullable key fields and the absence of missing required fields. Key and required fields are preset fields related to core business attributes, such as property rights codes and company names. The validity check includes checking data type matching, format compliance (such as unified social credit code format verification and date format verification), and correct value range. The consistency check includes checking the consistency of cross-table join fields. The distribution rationality check includes checking the normality of numerical distribution and outlier detection. If any quality check fails, the results are combined into a single check result. The results of the above three checks are then combined into a comprehensive check result.
[0066] If the overall verification result is passed, it means that no anomalies were found in the three verifications. The generation module will use the SQL statement as the generation result to ensure that the final output SQL statement can be directly executed and the result is reliable.
[0067] In one optional implementation, the SQL generation layer further includes a feedback module and a retry control module; the feedback module is used to feed back the comprehensive verification result to the large language model to regenerate the SQL statement when the comprehensive verification result is not passed; the retry control module is used to count the number of times the large language model generates the SQL statement, and when the number of times exceeds the preset number of retries, the query suggestion generated by the large language model is used as the generation result.
[0068] Specifically, if the comprehensive verification result fails, the feedback module sends the result back to the large language model, allowing it to use the anomaly information in the result for iterative optimization and regenerate the SQL statement for verification again. The retry control module counts the number of times the large language model generates the SQL statement. If this number exceeds the preset retry count (e.g., 3), the large language model generates a query suggestion based on the latest generated SQL statement, which is then used as the result to prevent the system from getting stuck in endless retries when it cannot generate correct SQL.
[0069] This invention generates business semantic tags for each field in the property rights database through a data governance layer, and associates these tags with the property rights database to obtain an enhanced database, enabling the system to understand the business meaning of the fields. The data governance layer also parses historical SQL statements to construct a lineage graph, explicitly modeling the relationships between tables and fields, avoiding the generation of incorrect JOIN paths or the omission of necessary tables. The vector retrieval layer identifies the property rights data characteristics queried by the user, and based on the user query, the enhanced database, and the lineage graph, retrieves the contextual information of the user query. This allows it to determine the property rights scenario to which the user query belongs and retrieve relevant contextual information, providing subsequent generation with both semantic and relational basis. The SQL generation layer generates SQL statements that conform to the structural characteristics of the property rights data based on the contextual information and the SQL templates corresponding to the property rights data characteristics. It also performs self-correction based on the SQL statements and their execution results, improving the quality of generated SQL statements. Overall, the data governance layer provides the foundation for business semantics and associations, the vector retrieval layer identifies query intent and retrieves relevant context, and the SQL generation layer generates and corrects SQL statements based on context and domain templates. The three layers work together to achieve automatic conversion from natural language queries to high-quality SQL statements and achieve domain adaptation for property data.
[0070] The present invention has the following beneficial effects: (1) Significantly improved SQL generation accuracy: In the case of property data, the SQL generation accuracy is greatly improved.
[0071] (2) Enhanced ability to process complex queries: Through the lineage tracing mechanism, the accuracy of multi-table join queries is greatly improved, effectively solving the problem of table selection in complex JOIN scenarios.
[0072] (3) High self-correction success rate: The built-in self-correction mechanism enables errors to be corrected within retries, greatly reducing the need for manual intervention.
[0073] (4) Guaranteed quality of query results: Multidimensional verification enables erroneous results to be detected and processed in a timely manner, greatly improving the credibility of query results.
[0074] (5) Good vertical domain adaptability: It is specially optimized for the special needs of property rights data and can directly handle complex business scenarios such as tree structure, equity penetration, and multiple calibers.
[0075] (6) High interpretability: Through lineage mapping and semantic tags, the system’s decision-making process is more transparent and easier for business personnel to understand and verify.
[0076] This embodiment provides an intelligent question-answering method. Figure 2 This is a flowchart of an intelligent question-answering method according to an embodiment of the present invention, such as... Figure 2 As shown, the process includes the following steps: Step S201: Obtain user query.
[0077] Specifically, it obtains natural language queries input by the user, such as "What is the registered capital of a certain company?"
[0078] Step S202: Obtain the generated results of the user query through the Text-to-SQL generation system.
[0079] Specifically, the user's query is input into the Text-to-SQL generation system, which then generates the corresponding results.
[0080] Step S203: When the generated result is an SQL statement, execute the SQL statement to obtain the query result of the user query.
[0081] Specifically, when the generated result is an SQL statement, the SQL statement is executed directly to obtain the query result corresponding to the user's query.
[0082] Step S204: When the generated result is a query suggestion, modify the user query according to the query suggestion and return to the Text-to-SQL generation system to obtain the generated result of the user query.
[0083] Specifically, when the generated result is a query suggestion, the user query is adjusted according to the query suggestion. The modified user query is then re-entered into the Text-to-SQL generation system, and step S202 is executed again to generate a new result, thereby improving the question-answering success rate.
[0084] This invention achieves intelligent question answering by acquiring user queries, generating query results through a Text-to-SQL generation system, and executing SQL statements when the generated results are SQL statements to obtain the query results. Furthermore, since the generated results are produced by the Text-to-SQL generation system, the SQL statements have undergone semantic enhancement, lineage tracing, and self-correction, ensuring greater accuracy and reliability of the returned query results and guaranteeing the accuracy of the intelligent question answering.
[0085] This embodiment also provides an intelligent question-answering device for implementing the above embodiments and preferred embodiments; details already described will not be repeated. As used below, the term "module" can refer to a combination of software and / or hardware that performs a predetermined function. Although the device described in the following embodiments is preferably implemented in software, hardware implementation, or a combination of software and hardware, is also possible and contemplated.
[0086] This embodiment provides an intelligent question-answering device, such as... Figure 3 As shown, it includes: The query retrieval module 301 is used to retrieve user queries.
[0087] The query generation module 302 is used to obtain the generated results of the user's query through the Text-to-SQL generation system.
[0088] The query execution module 303 is used to execute the SQL statement when the generated result is an SQL statement, and obtain the query result of the user query.
[0089] In some alternative embodiments, the device further includes: The modification module is used to modify the user query according to the query suggestion when the generated result is a query suggestion, and then return to the Text-to-SQL generation system to obtain the generated result of the user query.
[0090] The intelligent question-answering device provided in this embodiment of the invention can execute the intelligent question-answering method provided in any embodiment of the invention, and has the corresponding functional modules and beneficial effects of the method execution. Further functional descriptions of the various modules and units described above are the same as in the corresponding embodiments described above, and will not be repeated here.
[0091] Figure 4 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present invention.
[0092] The following is a detailed reference. Figure 4 This diagram illustrates a structural schematic suitable for implementing an electronic device according to embodiments of the present invention. The electronic device may include a processor (e.g., a central processing unit, graphics processor, etc.) 401, which can perform various appropriate actions and processes according to a program stored in read-only memory (ROM) 402 or a program loaded from memory 408 into random access memory (RAM) 403. The RAM 403 also stores various programs and data required for the operation of the electronic device. The processor 401, ROM 402, and RAM 403 are interconnected via a bus 404. An input / output (I / O) interface 405 is also connected to the bus 404.
[0093] Typically, the following devices can be connected to I / O interface 405: input devices 406 including, for example, touchscreens, touchpads, keyboards, mice, cameras, microphones, accelerometers, gyroscopes, etc.; output devices 407 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; memory devices 408 including, for example, magnetic tapes, hard disks, etc.; and communication devices 409. Communication device 409 allows electronic devices to communicate wirelessly or wiredly with other devices to exchange data. Although Figure 4 Electronic devices with various devices are shown, but it should be understood that it is not required to implement or have all of the devices shown, and more or fewer devices may be implemented or have instead.
[0094] In particular, according to embodiments of the present invention, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments of the present invention include a computer program product comprising a computer program carried on a non-transitory computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication device 409, or installed from a memory 408, or installed from a ROM 402. When the computer program is executed by the processor 401, it performs the functions defined in the intelligent question-answering method of the embodiments of the present invention.
[0095] Figure 4 The electronic device shown is merely an example and should not be construed as limiting the functionality and scope of the embodiments of the present invention.
[0096] This invention also provides a computer-readable storage medium. The methods described above according to embodiments of the invention can be implemented in hardware or firmware, or implemented as recordable on a storage medium, or implemented as computer code originally stored on a remote storage medium or a non-transitory machine-readable storage medium and subsequently stored on a local storage medium after being downloaded via a network. Thus, the methods described herein can be processed by software stored on a storage medium using a general-purpose computer, a dedicated processor, or programmable or dedicated hardware. The storage medium can be a magnetic disk, optical disk, read-only memory, random access memory, flash memory, hard disk, or solid-state drive, etc.; further, the storage medium can also include combinations of the above types of memory. It is understood that computers, processors, microprocessor controllers, or programmable hardware include storage components capable of storing or receiving software or computer code. When the software or computer code is accessed and executed by the computer, processor, or hardware, the intelligent question-answering method shown in the above embodiments is implemented.
[0097] Although embodiments of the invention have been described in conjunction with the accompanying drawings, those skilled in the art can make various modifications and variations without departing from the spirit and scope of the invention, and such modifications and variations all fall within the scope defined by the appended claims.
Claims
1. A Text-to-SQL generation system, characterized in that, The system includes a data governance layer, a vector retrieval layer, and an SQL generation layer; The data governance layer is used to generate business semantic tags for each field in the property rights database and associate the business semantic tags with the property rights database to obtain an enhanced database. The business semantic tags represent the business interpretation of the fields. The data governance layer is also used to parse historical SQL statements to construct a lineage graph, which represents the relationships between tables and fields in the property rights database; The vector retrieval layer is used to identify the property data features queried by the user, and to retrieve the context information of the user query based on the user query, the enhanced database, and the pedigree chart. The SQL generation layer is used to generate the SQL statement for the user query based on the context information and the SQL template corresponding to the property data characteristics, and to perform self-correction based on the SQL statement and its execution result to obtain the generated result.
2. The system according to claim 1, characterized in that, The data governance layer includes a semantic annotation engine, which includes a first parsing submodule, a sampling submodule, an annotation submodule, and an association submodule. The first parsing submodule is used to extract metadata from the property rights database; The sampling submodule is used to sample multiple data records from the property rights database, and the multiple data records cover multiple business scenarios; The annotation submodule is used to input the metadata and the multiple data records into the large language model to generate business semantic tags for each field in the metadata; The association submodule is used to associate the business semantic tags with the property rights database to obtain the enhanced database.
3. The system according to claim 2, characterized in that, The data governance layer also includes a lineage tracing engine, which includes a collection submodule, a second parsing submodule, an extraction submodule, and a construction submodule. The acquisition submodule is used to obtain historical SQL statements executed on the property rights database; The second parsing submodule is used to parse the historical SQL statements into an abstract syntax tree; The extraction submodule is used to traverse the abstract syntax tree and extract relational information from the historical SQL statements; The construction submodule is used to take the tables and fields in the metadata as nodes, and construct edges between the nodes based on the relationship information and the metadata to form the lineage graph.
4. The system according to claim 3, characterized in that, The data governance layer also includes a quality checker, used to perform consistency checks on the edges of the lineage graph; The extraction submodule is also used to re-extract the relational information from the historical SQL statement when the consistency check fails; The construction submodule is also used to reconstruct the kinship map based on the re-extracted relationship information; The quality checker is also used to perform consistency checks on the edges of the reconstructed lineage graph again, and output an error message when the number of checks exceeds the preset number of checks.
5. The system according to claim 2, characterized in that, The vector retrieval layer includes an encoding module and a retrieval module; The encoding module is used to embed nodes into the kinship map using a graph neural network; The encoding module is also used to generate edge-level vectors and generate table-level vectors and field-level vectors of the lineage graph based on node embedding, which together form the lineage vector. The field-level vector is obtained by fusing field node embedding with the business semantic tags of the corresponding fields. The retrieval module is used to generate the context information based on the bloodline vector and the user query.
6. The system according to claim 5, characterized in that, The retrieval module is specifically used for: The user query is converted into a query vector. The first similarity between the query vector and each edge-level vector in the lineage vector is calculated. The edges corresponding to all edge-level vectors are sorted according to the first similarity to determine the edge set. Calculate the second similarity between the query vector and each table-level vector in the lineage vector, sort the tables corresponding to all table-level vectors according to the second similarity, and determine the table set; Calculate the third similarity between the query vector and each field-level vector in the lineage vector, sort the fields corresponding to all field-level vectors according to the third similarity, and determine the field set; Calculate the fourth similarity between the query vector and each example in the sample example library, sort all examples in descending order according to the fourth similarity, and determine the example set. Each example includes the sample user query and its SQL statement. The edge set, the table set, the field set, and the example set are used as the context information for the user query.
7. The system according to claim 1, characterized in that, The SQL generation layer includes a generation module and a verification module; The generation module is used to generate the SQL statement based on the context information and the SQL template corresponding to the property data features using a large language model; The verification module is used to perform syntax and logic verification on the SQL statement, and to perform quality verification on the execution result obtained by executing the SQL statement, so as to obtain a comprehensive verification result. The generation module is further configured to use the SQL statement as the generation result when the comprehensive verification result is passed.
8. The system according to claim 7, characterized in that, The SQL generation layer also includes a feedback module and a retry control module; The feedback module is used to feed back the comprehensive verification result to the large language model to regenerate the SQL statement when the comprehensive verification result is not passed. The retry control module is used to count the number of times the large language model generates SQL statements. When the number of retry exceeds the preset number of retries, the large language model generates query suggestions as the generated result.
9. An intelligent question-answering method, characterized in that, The method includes: Get user queries; The generated result of the user query is obtained through the Text-to-SQL generation system according to any one of claims 1 to 8; When the generated result is an SQL statement, the SQL statement is executed to obtain the query result of the user's query.
10. The method according to claim 9, characterized in that, The method further includes: When the generated result is a query suggestion, the user query is modified according to the query suggestion, and the process returns to the step of obtaining the generated result of the user query through the Text-to-SQL generation system according to any one of claims 1 to 8.
