A query statement generation method and an electronic device
By introducing context analysis and correlation judgment of historical query records during the query statement generation process, candidate data tables are filtered and lightweight verification is performed, which solves the problems of input redundancy and low verification efficiency in the existing technology, and realizes efficient and accurate query statement generation and optimization.
Patent Information
- Application Number
- CN202511558519.6
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-29
- Publication Date
- 2026-03-03
- Estimated Expiration
- 2045-10-29
AI Technical Summary
Existing technologies suffer from problems such as redundant input information, high error rate in generated statements, high overhead, low verification efficiency, and insufficient correction capabilities during query statement generation, especially with serious resource waste during multiple queries.
By introducing contextual analysis of natural language query requests and a correlation judgment mechanism for historical query records, candidate data tables are filtered, and verification and reasoning corrections are performed on lightweight data tables to achieve concise generation and efficient verification of query statements.
It significantly reduces input information redundancy and computational complexity, improves the accuracy of query statement generation and verification efficiency, and achieves efficient optimization in multi-round query scenarios.
Smart Images

Figure CN121029953B_ABST
Abstract
Description
Technical Field
[0001] This application relates to the field of query statement generation technology, and in particular to a query statement generation method and electronic device. Background Technology
[0002] With the development of natural language processing technology and pre-trained language models, users can automatically generate database query statements through natural language input to achieve convenient data access. Existing technologies typically employ a one-time inference generation strategy, which involves directly inputting the natural language query request and all data tables in the database into the language model to generate the statement.
[0003] However, this method of full input and one-time generation has several drawbacks. First, it lacks effective filtering of the target data table, resulting in redundant input information that can easily lead to generated query statements containing irrelevant tables or incorrect fields, thereby reducing the accuracy and executability of the query logic. Second, when performing multiple queries on the same database, it lacks contextual reasoning and memory inheritance capabilities, requiring repeated extraction of data tables and query semantics each time, resulting in significant overhead and resource waste. Furthermore, existing technologies lack reasonable validation of the generated query statements. The validation process is usually performed directly on the full data table, resulting in high computational overhead and low validation efficiency. If the statement is unreasonable, it needs to be re-inputted and re-reasoned, making it difficult to achieve rapid correction and efficient optimization. Summary of the Invention
[0004] This application provides a query statement generation method that can filter candidate data tables based on the query relevance of historical query records and current query requests, thereby simplifying input information and reducing overhead and resource waste caused by repeated input. Furthermore, it extracts a first data table set to achieve lightweight query statement verification and model inference correction, ultimately efficiently and accurately converting natural language query requests into query statements. This method aims to at least solve the problems of redundant input information, high error rate of generated statements, large overhead, low statement verification efficiency, and insufficient correction capabilities in related technologies.
[0005] This application provides a query statement generation method, including:
[0006] In response to receiving a user's natural language query request, the query context information of the natural language query request is obtained, and historical query records are retrieved.
[0007] Determine whether there is a query correlation between the natural language query request and the historical query records. If there is, determine the candidate data table set based on the historical query data table in the historical query records.
[0008] The pre-trained language model is invoked to perform the first inference on the natural language query request and the candidate data table set. Based on the first inference result, an initial query statement is generated, and the initial query statement is executed on the first data table set built based on the candidate data table set to obtain the initial query result.
[0009] Verify whether the query score of the initial query results meets the preset usability standard threshold;
[0010] If the preset availability threshold is met, the initial query statement is determined as the target query statement;
[0011] If the preset availability threshold is not met, the language model is invoked to perform a second inference on the natural language query request, candidate data set, and initial query results. A corrected query statement is generated based on the second inference result, and the corrected query statement is executed on the first data set to obtain the corrected query result. The query score of the corrected query result is verified to see if it meets the preset availability threshold. If it does, the corrected query statement is determined as the target query statement.
[0012] This application also provides an electronic device, including: a memory for storing a computer program; and a processor for implementing any of the above-described query statement generation methods when executing the computer program.
[0013] This application addresses the challenges of incorporating contextual analysis of natural language query requests and a correlation mechanism with historical query records during query statement generation. This allows for the determination of candidate data tables based on historical query records upon receiving a new query request, effectively filtering the target data table during the input phase and reducing irrelevant information input during language model inference. Furthermore, instead of directly performing validation on the full data table after generating the initial query statement, a lightweight first data table set is constructed based on the candidate data table set for validation and query scoring, significantly reducing the scale and complexity of validation computation. Simultaneously, by determining whether secondary inference correction of the language model is triggered based on the query scoring results, a closed-loop optimization of statement generation and validation is achieved. Therefore, this application solves the problems of redundant input information, high error rate in generated statements, high overhead, low validation efficiency, and insufficient correction capabilities inherent in existing technologies, achieving efficient and accurate query statement generation and lightweight, efficient validation optimization in multi-round natural language query scenarios. Attached Figure Description
[0014] To more clearly illustrate the embodiments of this application, the accompanying drawings used in the embodiments 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.
[0015] Figure 1 A schematic diagram of an application environment provided for an embodiment of this application;
[0016] Figure 2 This is a schematic diagram of a query statement generation device provided in an embodiment of this application;
[0017] Figure 3 This is a schematic diagram of a query statement generation method provided in an embodiment of this application;
[0018] Figure 4 This is a schematic diagram illustrating a query statement generation step provided in an embodiment of this application;
[0019] Figure 5 A schematic diagram of a retrieval query statement generation device provided in another embodiment of this application;
[0020] Figure 6 A flowchart illustrating the user database table connection storage process provided in another embodiment of this application;
[0021] Figure 7 A semantic encoding flowchart is provided for another embodiment of this application;
[0022] Figure 8 A flowchart for generating query statements provided in another embodiment of this application;
[0023] Figure 9 This is a schematic diagram of an electronic device provided in an embodiment of this application. Detailed Implementation
[0024] The technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. Obviously, the described embodiments are only some embodiments of this application, and not all embodiments. Based on the embodiments of this application, all other embodiments obtained by those of ordinary skill in the art without creative effort are within the protection scope of this application.
[0025] It should be noted that, in the description of this application, the terms "comprising," "including," or any other variations thereof are intended to cover non-exclusive inclusion, such that a process, method, article, or apparatus that comprises a list of elements includes not only those elements but also other elements not expressly listed, or elements inherent to such a process, method, article, or apparatus. The terms "first," "second," etc., in this application are used to distinguish similar objects and are not used to describe a specific order or sequence.
[0026] To enable those skilled in the art to better understand the present application, the present application will be further described in detail below with reference to the accompanying drawings and specific embodiments.
[0027] In one embodiment, the query statement generation method provided in this application can be applied to, for example... Figure 1 The application environment shown includes a terminal 101 and a server 102, which communicate with each other via a network. The terminal 101 can be, but is not limited to, various types of computing or interactive devices, such as personal computers, laptops, smartphones, tablets, or portable wearable devices, and is used to receive natural language query requests input by the user and send the query requests to the server 102. The terminal 101 can also receive and display the query results returned by the server, realizing a human-computer interaction interface. The server 102 can consist of a single server or a server cluster composed of multiple servers, and is used to process natural language query requests from the terminal 101.
[0028] In one embodiment, such as Figure 2 As shown, a query statement generation device is deployed in the server 102. The query statement generation device may include a language understanding module, a query generation module, a verification and correction module, and a result feedback module. The language understanding module is used to receive natural language query requests transmitted by the dialogue module deployed in the terminal 101 and extract their query context information. The query generation module is used to determine whether there is a query correlation based on the query context and historical query records, and determine the candidate data table set if a correlation exists. The verification and correction module is used to call the pre-trained language model to perform the first inference on the natural language query request and the candidate data table, generate the initial query statement, execute and calculate the query score on the constructed first data table set, and if the preset usability standard is not met, the second inference is triggered, and the initial query result is combined to make corrections and generate a corrected query statement. The result feedback module is used to return the finally determined target query statement or query result to the terminal 101 for display.
[0029] With the above settings, the query statement generation method provided in this application can be deployed and run centrally on the server side, realizing cross-terminal natural language query support. This not only ensures the computational efficiency of language model reasoning and data verification processes, but also facilitates unified updates and optimizations of the model through server-side maintenance, thereby improving the overall query generation accuracy and execution performance of the system.
[0030] In one embodiment, such as Figure 3 As shown, this application provides a query statement generation method, applied to server 102, including:
[0031] Step 201: In response to receiving a user's natural language query request, obtain the query context information of the natural language query request and obtain historical query records;
[0032] Step 202: Determine whether there is a query correlation between the natural language query request and the historical query records. If there is, determine the candidate data table set based on the historical query data table in the historical query records.
[0033] Step 203: Call the pre-trained language model to perform the first inference on the natural language query request and the candidate data table set, generate the initial query statement based on the first inference result, and execute the initial query statement on the first data table set built based on the candidate data table set to obtain the initial query result;
[0034] Step 204: Verify whether the query score of the initial query results meets the preset usability standard threshold;
[0035] Step 205: In response to meeting the preset availability criterion threshold, the initial query statement is determined as the target query statement;
[0036] Step 206: In response to the failure to meet the preset availability standard threshold, the language model is invoked to perform a second inference on the natural language query request, candidate data set, and initial query result. A corrected query statement is generated based on the second inference result, and the corrected query statement is executed on the first data set to obtain the corrected query result. The query score of the corrected query result is verified to meet the preset availability standard threshold. If it meets the threshold, the corrected query statement is determined as the target query statement.
[0037] Specifically, in this embodiment, by introducing a context analysis mechanism for natural language query requests and a correlation judgment mechanism for historical query records during the generation of query statements, a candidate data table set can be determined based on historical query records when a new query request is received. This enables effective filtering of the target data table during the input stage, reducing irrelevant information input during language model inference. Furthermore, since validation is not performed directly on the full data table after the initial query statement is generated, but rather a lightweight first data table set is constructed based on the candidate data table set to validate and score the initial query statement, the scale and complexity of validation computation are significantly reduced. Simultaneously, by determining whether secondary inference correction of the language model is triggered through the query scoring results, a closed-loop optimization of statement generation and validation is achieved. Therefore, this embodiment can solve the problems of redundant input information, high error rate of generated statements, large overhead, low validation efficiency, and insufficient correction capability caused by full input in existing technologies, achieving the technical effect of efficient and accurate generation of query statements and lightweight and efficient validation optimization in multi-round natural language query scenarios.
[0038] It is worth noting that, in one specific embodiment, a natural language query request refers to a query instruction input by a user into the system in natural language (e.g., human-readable sentences such as Chinese and English). This instruction can express the query requirements without using a database-specific query language and typically includes semantic information such as the query topic, target object, and constraints, which is used to represent the user's actual query intent. Query context information refers to semantic background information related to the natural language query request, including but not limited to previous query content, query parameters, query results, or other data that can reflect the user's query context, which is used to help determine the semantic continuity and logical relationship between the current query and historical queries. Historical query records refer to the collection of past query information saved by the system during user-database interactions. This includes historical query statements, involved data tables, execution results, operation types, and their semantic tags. These records are used to provide contextual references for subsequent queries and support the inheritance and optimization of query intent. Query relevance refers to the semantic or database structural relationship between natural language query requests and historical query records. This includes, but is not limited to, situations where the query objects are the same, query fields overlap, query logic is similar, or operation patterns are consistent. Query relevance can be divided into primary relevance (i.e., structural relevance at the object level) and secondary relevance (i.e., behavioral relevance at the operation level).
[0039] The candidate data set refers to a set of data tables that may be referenced by the current query statement, obtained by filtering through feature matching, similarity calculation, or structural aggregation, based on the data tables involved in historical queries, their structural relationships, and field semantic information, given that a query relevance is determined. This set is used to limit the input range when the language model generates the query statement, thereby reducing redundant information and improving generation accuracy. The first data set refers to a lightweight dataset constructed based on the candidate data set through field association parsing, table join merging, field compression, and data sampling. It can significantly reduce the data size while ensuring the integrity of query logic and field dependencies. It is used to execute the initial query statement and generate query results during the verification phase, thereby improving verification efficiency and reducing computational burden.
[0040] A pre-trained language model refers to a deep learning model that has been pre-trained on a large-scale natural language corpus and database structure semantic data. This model has the ability to understand natural language, parse semantics, and generate query statements. It can generate structured query statements based on the input natural language query request and database structure information. The language model in this application can be a large-scale language model (LLM), such as a pre-trained model based on the Transformer architecture.
[0041] The first reasoning refers to the process by which the language model performs semantic understanding and logical generation based on the natural language query request and the candidate data table input, in order to obtain the first reasoning result and generate the initial query statement; the second reasoning refers to the process by which the language model, in combination with the initial query statement, execution result and deviation information feature set, corrects and optimizes the query logic and generates a corrected query statement when the query score of the initial query result does not reach the preset usability standard threshold.
[0042] Query score is a comprehensive indicator used by the system to quantitatively verify the initial query results. It takes into account factors such as the accuracy, consistency and execution performance of the query results. It is obtained by comparing the initial query results with the benchmark values derived from the first data set and is used to evaluate the usability and execution quality of the generated query statements.
[0043] In one embodiment, query relevance includes at least primary and secondary relevance. Determining whether a natural language query request and historical query records have a query relevance includes:
[0044] The natural language query request and the historical query record are parsed separately to obtain the current data object and the historical data object;
[0045] By comparing the identification information of the current data object with the identification information of the historical data object, it is determined whether there is a logical relationship between the current data object and the historical data object at the database structure level.
[0046] If the response is no, it is determined that there is no query relationship between the natural language query request and the historical query records;
[0047] If the response is correct, it is determined that there is a first-level correlation between the natural language query request and the historical query record.
[0048] Specifically, in this embodiment, by parsing the natural language query request and historical query records, the current data object and historical data object are extracted. Based on the logical relationship at the database structure level, it is determined whether there is a first-level relationship. This enables the system to recognize and understand the semantics of the database structure, thereby automatically determining whether the current query has a semantic continuation or structural inheritance relationship with past queries. Furthermore, this mechanism helps to avoid re-extracting and analyzing the entire data table for each query, significantly reducing redundant calculation overhead, improving the coherence of the query context and resource utilization efficiency, and fundamentally solving the problem of redundant operations caused by the lack of context reasoning in the prior art.
[0049] In one embodiment, after determining that there is a primary correlation between the natural language query request and the historical query record, the method further includes:
[0050] The operational features of natural language query requests and historical query records are extracted and compared separately.
[0051] Based on the comparison results of operational features, determine whether there is an operational correlation between natural language query requests and historical query records in terms of query operation methods;
[0052] If so, it is determined that there is a secondary correlation between the natural language query request and the historical query record;
[0053] If not, it is determined that there is no secondary association between the natural language query request and the historical query record, that is, there is only a primary association.
[0054] Specifically, in this embodiment, based on the establishment of primary correlation, the operation features of natural language query requests and historical query records are extracted and compared to determine whether there is secondary correlation at the operation level. This not only considers the consistency of the query object, but also further analyzes the similarity of query operation methods, realizing a two-layer matching of semantic correlation and operation mode. This can more accurately identify historical records that are highly similar to the current query semantics and operation logic, thereby directly inheriting previous operation experience in the generation stage and avoiding repeated semantic extraction and logical reasoning. Furthermore, this correlation identification mechanism significantly improves the model's reasoning efficiency and generation coherence, solving the problem of redundant calculations caused by starting from zero for each query in traditional solutions.
[0055] In one embodiment, determining a candidate data table set based on historical query data tables in historical query records includes:
[0056] If there is at least one level of correlation between a natural language query request and a historical query record, then the structural correlation information of the current data object and the historical data object is extracted from the corresponding database and the correlation path is determined.
[0057] Based on the association path, an intermediate table is extracted from the database and combined with the historical query data table corresponding to the historical data object to generate an initial data table set;
[0058] Based on the metadata information of the current data object, generate a baseline feature vector to characterize the features of the current data object;
[0059] Based on the feature dimension corresponding to the baseline feature vector, multiple table feature vectors are generated for multiple data tables in the initial data table set, and the vector similarity between the multiple table feature vectors and the baseline feature vector is obtained.
[0060] Remove multiple data tables from the initial data table set whose vector similarity is less than a preset table similarity threshold, and use the removed initial data table set as the candidate data table set.
[0061] Specifically, in this embodiment, by utilizing the data tables and their structural association information involved in historical queries, intermediate tables are extracted from the database and association paths are determined. Then, combined with feature vector similarity filtering, a candidate data table set is finally generated. Through structural semantic association + vector similarity calculation, the candidate data tables are accurately filtered, effectively removing data tables irrelevant to the current query. Compared with the traditional full input method, the data dimension and redundant information input to the language model are significantly reduced, lowering the inference complexity and computational cost. At the same time, since the similarity between the candidate table and the query semantics is quantified, the accuracy of the generated statement and the execution success rate are significantly improved, ensuring the efficiency of the generation process and the usability of the results.
[0062] In one embodiment, after determining that there is a secondary association between the natural language query request and the historical query record, the method further includes:
[0063] Parse the natural language query request to obtain the query operation feature vector representing the query intent;
[0064] Identify multiple historical query statements related to the candidate data table set from historical query records, and filter out multiple candidate query statements whose vector similarity with the query operation feature vector is greater than or equal to a preset query operation similarity threshold.
[0065] Extract key constraint information from multiple candidate query statements and perform feature fusion to obtain constraint fusion features;
[0066] Based on constraint fusion features, a preliminary query statement is generated within the data range defined by the candidate data table set, for fusion with subsequent query statements.
[0067] Specifically, in this embodiment, semantic parsing of natural language query requests generates query operation feature vectors. These vectors are then combined with a candidate data table to filter out historical query statements similar to the query operation. These historical query statements are then fused with key constraint information to form constraint fusion features, which are used to generate preliminary query statements. This embodiment utilizes the structural and logical features of historical query statements to guide the current query generation process, enabling the language model to have a clearer operational context during the inference phase, thereby avoiding semantic deviations and logical errors. Furthermore, by inheriting historical operation patterns and constraints, the system can achieve continuity and self-optimization in multi-round query scenarios, significantly reducing the number of repetitive semantic analyses and error corrections, and improving the stability and intelligence level of the generated statements.
[0068] In one embodiment, such as Figure 4 As shown, the method also includes:
[0069] Step 301: If the natural language query request has no query relevance to historical query records, then parse the natural language query request and determine the query semantic elements. The query semantic elements include at least query subject terms, target field terms, and constraint condition terms.
[0070] Step 302: Determine the target database based on the query keywords, and identify multiple data tables in the target database that have field associations with the target keywords;
[0071] Step 303: Based on the constraint words, the identified multiple data tables are aggregated to generate a candidate data table set.
[0072] Specifically, in this embodiment, when there is no query correlation between the natural language query request and the historical query records, the system automatically determines the target database and identifies field relationships by parsing semantic elements such as query subject terms, target field terms, and constraint condition terms. Then, it aggregates data tables through constraints to generate a candidate data table set. This enables the system to independently construct the query semantic structure even without historical context, achieving efficient querying in "cold start" scenarios. Furthermore, the semantically driven table identification and aggregation method can significantly reduce manual configuration and full table scanning, improving the system's adaptability and response efficiency. This effectively solves the problems of high resource consumption and slow construction during the initial query in traditional solutions.
[0073] In one embodiment, a pre-trained language model is invoked to perform a first inference on the natural language query request and candidate data table, and an initial query statement is generated based on the first inference result, including:
[0074] Parse the semantics of natural language query requests and generate a query semantic vector that represents the semantic features of the current query request;
[0075] Extract the structure and field information of the candidate data table;
[0076] The structural information, field information, and query semantic vector are combined in a structured manner based on a preset input template to generate an input suggestion vector;
[0077] The input hint vector is fed into the language model to obtain the first inference result output by the language model. The first inference result includes at least a query logic structure tree to indicate at least the operational relationships between fields, the filtering logic, and the connection path.
[0078] Based on the query logic structure tree, generate an initial query statement that conforms to the syntax specifications of the candidate data table.
[0079] Specifically, in this embodiment, the structure and field information of the candidate data table are extracted and combined with natural language query semantic vectors. After being structured and combined using a preset input template, the data is input into the language model to obtain a query logic structure tree containing field operation relationships and filtering logic. Based on this, an initial query statement is generated. This embodiment achieves interpretability mapping from semantics to syntax by unifying the modeling of natural language semantics and database structure. This effectively avoids problems such as field mismatch and table association errors in traditional models. Furthermore, the generated query logic structure tree not only ensures the correctness of the statement syntax but also improves the transparency and traceability of the logical structure, making the statement generation more stable, standardized, and verifiable, thus significantly improving the quality of query generation.
[0080] In one embodiment, before executing an initial query statement on a first set of data tables constructed based on the candidate data table set, the method further includes:
[0081] Parse the candidate data table set to obtain the join fields and inter-table dependencies between multiple candidate data tables;
[0082] Based on the join fields and inter-table dependencies, multiple candidate data tables that have field join relationships and inter-table dependencies are merged to obtain multiple intermediate data tables with fewer numbers than the candidate data tables.
[0083] The identification fields in multiple intermediate data tables are compressed and merged to obtain multiple compressed data tables. The compression and merging process includes at least deduplication of duplicate identification fields and interval partitioning or encoding of continuous or groupable identification fields to reduce field redundancy and maintain connectivity.
[0084] Based on the frequency and range distribution of the original numerical fields in the candidate data table, data sampling is performed on the numerical fields of multiple compressed data tables to obtain multiple sampled data tables whose distribution deviation from the original numerical fields does not exceed a preset threshold.
[0085] Based on multiple sampled data tables, a first data table set is constructed.
[0086] Specifically, in this embodiment, by parsing and merging the join fields and dependencies of the candidate data tables, and constructing a first data table set through field compression and data sampling, the redundancy of fields and the volume of data are significantly reduced while maintaining the logical relationships between fields. This allows the query statement verification stage to no longer rely on the full data table, but instead to be performed on a compressed and sampled high-efficiency dataset, significantly improving the verification speed and reducing system computational overhead. Furthermore, the structural optimization method provided in this embodiment not only ensures the representativeness and accuracy of the verification results, but also greatly improves the execution efficiency of the verification process, providing a foundation for rapid correction and iterative optimization.
[0087] In one embodiment, verifying whether the query score of the initial query results meets a preset usability standard threshold includes:
[0088] Based on the structural information of the first data set, semantic checks are performed on the field references, join conditions, and aggregation operations contained in the initial query statement to determine whether the initial query statement is consistent with the field definitions, primary and foreign key relationships, and field dependencies in the first data set.
[0089] If an inconsistency is detected, the initial query statement is determined to be unavailable, and the initial query statement is corrected.
[0090] If consistency is required, the accuracy, consistency, and statement execution performance of the initial query results are analyzed, and a query score for the initial query results is generated for comparison with a preset usability standard threshold.
[0091] Specifically, in this embodiment, the initial query statement undergoes semantic consistency checks on field references, join conditions, and aggregation logic before execution to ensure that the statement structure is consistent with the data table definition and dependencies. After verification, a query score is generated based on the accuracy, consistency, and performance of the query results and compared with an availability threshold. This achieves automated quality assessment and adaptive correction control after query statement generation, enabling the detection and correction of logical errors before statement execution and preventing erroneous queries from consuming system resources. Simultaneously, by introducing quantitative scoring standards, the system can achieve dynamic evaluation and continuous optimization of statement quality, thereby significantly improving the reliability of query statement generation, execution performance, and the overall intelligence of the system.
[0092] In a further embodiment, the accuracy, consistency, and statement execution performance of the initial query results are analyzed to generate a query score for the initial query results, including:
[0093] The field output values and statistical feature values of the initial query results are compared with the field output benchmark values and statistical feature benchmark values derived from the field constraints of the first data table set to obtain the field output deviation value and statistical feature deviation value, and to determine the accuracy score. The statistical feature values include, but are not limited to, field mean, variance, and aggregated results, and the statistical feature benchmark values include, but are not limited to, field benchmark mean, benchmark variance, and aggregated reference value.
[0094] The distribution of values of fields in the initial query results is compared with the distribution of values of corresponding fields in the first data table to obtain the distribution difference degree and determine the consistency score. The distribution difference degree can be obtained by mean squared error, KL divergence or other statistical distance measures.
[0095] Obtain the execution parameters of the initial query statement on the first data table set, and determine the execution performance score of the statement based on the execution parameters. The execution parameters include at least: execution time, memory usage, and I / O access count, which can be obtained in real time through query execution plan or database performance monitoring module.
[0096] Based on preset weights, the accuracy score, consistency score, and statement execution performance score are weighted and summed to obtain the query score.
[0097] Specifically, this embodiment, when verifying the initial query results, not only considers the syntactic correctness of the statement but also introduces a multi-dimensional quantitative scoring mechanism based on field output deviation, statistical feature deviation, value distribution differences, and execution performance. This mechanism comprehensively analyzes the accuracy, consistency, and execution performance of the initial query results. Furthermore, by comparing the query output results with the field benchmark values and statistical benchmark values derived from the first data set, the degree of consistency between the query results and the actual data characteristics can be objectively reflected, thereby accurately quantifying the correctness and rationality of the statement execution. Simultaneously, by introducing field distribution difference to assess the deviation of the query results from the global distribution, potential logical deviations can be effectively identified. Moreover, by combining statement execution performance parameters, the executability and resource utilization efficiency of the generated statement can be further evaluated. Thus, the technical effect of quantitative, interpretable, and high-precision evaluation of the generated query statement can be achieved, providing a reliable basis for subsequent statement correction and significantly improving the intelligence and controllability of query verification.
[0098] In one embodiment, in response to a preset availability threshold not being met, a language model is invoked to perform a second inference on the natural language query request, candidate data set, and initial query results. Based on the second inference result, a revised query statement is generated and executed on the first data set to obtain a revised query result, including:
[0099] The initial query statement is semantically parsed to extract query structure information, which includes, but is not limited to: target fields, join paths, aggregation operations, and filtering conditions.
[0100] Extract execution deviation information from the initial query results and construct a deviation information feature set. The execution deviation information includes, but is not limited to, field output deviation, field distribution difference, and statement execution performance indicators.
[0101] Based on the deviation information feature set, the key factors that lead to insufficient query scores are identified, and corresponding error type labels are generated according to the key factors. The error type labels include, but are not limited to: incorrect field reference, incomplete join path, inappropriate selection of aggregate function, or unreasonable setting of filtering conditions.
[0102] The natural language query request, the semantic descriptions of the fields in the candidate data table, and the error type labels are all input into the language model;
[0103] The language model performs the second inference to generate revised planning information, which includes at least the revised field selection, join relationship, aggregation operation expression and filtering conditions.
[0104] Based on the revised planning information, the revised query statement is constructed according to the SQL syntax template. That is, while keeping the overall query goal consistent, the fields, joins and aggregation logic in the initial query statement are structurally adjusted to generate the revised query statement.
[0105] In a further embodiment, verifying whether the query score of the corrected query result meets a preset usability standard threshold, and determining the corrected query statement as the target query statement in response to the threshold, includes:
[0106] Execute the corrected query statement on the first data set, obtain the corrected query results, and calculate the corresponding query score;
[0107] When the query score of the corrected query result meets the preset availability standard threshold, the corrected query statement is determined as the target query statement;
[0108] If the corrected query score still does not meet the preset availability standard threshold, the language model is invoked to perform a third inference on the natural language query request, candidate data set, and corrected query results. A third query statement is generated based on the third inference result. This process continues until the query score of the currently generated query statement meets the preset availability standard threshold or the preset inference limit is reached.
[0109] Specifically, in this embodiment, when the initial query results do not meet the usability criteria, instead of simply regenerating the query statement, the initial query statement undergoes semantic parsing, the query structure information is extracted, and the execution deviation information (including field output deviation, field distribution differences, and performance indicators) in the initial query results is combined to form a deviation information feature set, which is then categorized and labeled. This allows the system to automatically identify specific error sources in the query statement, such as incorrect field references, incomplete join paths, abnormal aggregation logic, or unreasonable filtering conditions. Furthermore, by inputting the natural language query request, the semantic description of the candidate data table fields, and the error type labels into the language model, the language model can combine the semantic context and error labels during the second inference to generate targeted correction planning information. This allows for structured adjustments to field selection, join paths, aggregation functions, and filtering logic, ultimately generating a corrected query statement. Thus, through this semantic reasoning closed-loop mechanism based on deviation information, the system can automatically identify errors in the query statement, intelligently correct query logic, and continuously optimize the quality of the generated statement without manual intervention. This significantly improves the system's self-learning and adaptive capabilities in complex multi-round query scenarios, achieving an integrated closed-loop process for query statement generation and optimization.
[0110] In another embodiment, the query statement generation method of this application can also be combined with a prompt information management mechanism and a retrieval enhancement generation architecture to further improve the accuracy of the generated query statements and the system's adaptability. Specifically:
[0111] like Figure 5 As shown, in this embodiment, the enhanced query statement generation device includes a dialogue client, a dialogue module, a large language model, an encoding model, a vector database, a relational database, and a user database. The dialogue client receives natural language query questions input by the user; the dialogue module, as the central component of the system, coordinates the operation of various functional modules; the large language model generates query statements based on the input natural language and prompts; the encoding model implements semantic vectorization; the vector database stores semantic vector information; the relational database stores system metadata, including database connection information and table structure information; and the user database stores user business data and is the data source for ultimately executing the query statement.
[0112] like Figure 6As shown, in this embodiment, when the device receives a natural language query request, the dialogue module first determines whether the request is a database query. If it is determined to be a query request, the device establishes communication with the user database based on the existing connection information, accesses the target user database through the connection configuration stored in the relational database, and reads the table structure information in the database. The table structure information includes table name, field name, field type, primary and foreign keys, and comments. The device standardizes and converts the table structure information extracted from the user database, organizes it into a unified data structure, and stores it in the table structure information table in the relational database as the basic data for subsequent prompt information management and semantic retrieval.
[0113] like Figure 7 As shown, in order to facilitate semantic retrieval and improve generation efficiency, the device uses an encoding model to semantically encode the table structure information, historical query examples and related metadata stored in the relational database, converting the text content into vector form and storing it in a vector database. Through this process, the device establishes a semantic index of the table structure and historical examples, enabling it to quickly retrieve the database table structure or historical query example most relevant to the question based on semantic similarity when a new natural language question is received.
[0114] like Figure 8 As shown, when the device generates a query statement, the dialogue module first performs semantic encoding on the natural language query request input by the user to obtain a question vector, and then retrieves the most relevant table structure information from the vector database. The device dynamically constructs contextual prompts corresponding to the current question based on the retrieval results, and organizes and generates input prompts for the large language model by combining the user's database type, version, and structural features. The input prompts include the device's instructions, database type descriptions, and compressed table structure descriptions. In order to reduce the input length and improve inference efficiency, the device performs extreme simplification of the table structure content when generating prompts, retaining only the table name, field name, field type, and brief comments. At the same time, it expresses the field type through a unified mapping rule to reduce semantic redundancy. Without affecting semantic understanding, this method significantly reduces the input length, allowing the model to obtain sufficient contextual information even under input constraints.
[0115] Subsequently, the device inputs the above prompts and the user's natural language question into the large language model. The model generates an initial query statement that conforms to the syntax of the target user's database. The generated statement is checked by the syntax and logic verification module for field references, joins, and filtering conditions to ensure that it can be executed correctly in the target user's database. If the statement fails the verification, the device will adaptively correct it based on the execution feedback information and historical query records until the generated statement meets the execution standard and the target query statement is obtained.
[0116] Through the above process, the device realizes automated processing from natural language input to the generation of structured query statements. When the connection is established for the first time, the device automatically extracts and stores table structure information from the user database. In subsequent queries, the device selects the most relevant context from the vector database through semantic retrieval and dynamically constructs prompt information input, thereby maintaining semantic integrity and generation accuracy under limited input conditions.
[0117] Furthermore, this embodiment maintains real-time consistency of prompts when the user database structure changes through an automatic table structure update mechanism and a prompt information optimization mechanism, reducing manual maintenance workload. By combining table structure compression, type mapping, and semantic retrieval technologies, the language model can more accurately understand the user database structure and query intent, resulting in more accurate and executable query statements. Compared to traditional text generation methods based on fixed templates, this embodiment has significant advantages in context construction, prompt management, and adaptive optimization, continuously improving the device's intelligence and generation performance in multi-turn natural language query scenarios.
[0118] Through the above description of the embodiments, those skilled in the art can clearly understand that the methods according to the above embodiments can be implemented by means of software plus necessary general-purpose hardware platforms. Of course, they can also be implemented by hardware, but in many cases the former is a better implementation method.
[0119] like Figure 9 As shown, embodiments of this application also provide an electronic device, including a memory and a processor, wherein the memory stores a computer program, and the processor is configured to run the computer program to perform the steps in any of the above-described query statement generation method embodiments.
[0120] Those skilled in the art will further recognize that the units and algorithm steps of the various examples described in conjunction with the embodiments disclosed herein can be implemented in electronic hardware, computer software, or a combination of both. To clearly illustrate the interchangeability of hardware and software, the components and steps of the various examples have been generally described in terms of functionality in the foregoing description. Whether these functions are implemented in hardware or software depends on the specific application and design constraints of the technical solution. Those skilled in the art can use different methods to implement the described functions for each specific application, but such implementation should not be considered beyond the scope of this application.
[0121] The query statement generation method and electronic device provided in this application have been described in detail above. Specific examples have been used to illustrate the principles and implementation methods of this application. The descriptions of the above embodiments are only intended to help understand the method and core ideas of this application. It should be noted that those skilled in the art can make several improvements and modifications to this application without departing from the principles of this application, and these improvements and modifications also fall within the protection scope of this application.
Claims
1. A method for generating query statements, characterized in that, include: In response to receiving a user's natural language query request, the query context information of the natural language query request is obtained, and historical query records are obtained; Determine whether there is a query correlation between the natural language query request and the historical query record. If there is, determine a candidate data table set based on the historical query data table in the historical query record. The pre-trained language model is invoked to perform a first inference on the natural language query request and candidate data table set. An initial query statement is generated based on the first inference result, and the initial query statement is executed on a first data table set constructed based on the candidate data table set to obtain an initial query result. The first data table set is constructed as follows: the candidate data table set is parsed to obtain the join fields and inter-table dependencies between multiple candidate data tables; based on the join fields and inter-table dependencies, multiple candidate data tables with join fields and inter-table dependencies are merged to obtain a number less than the number of candidates. Based on multiple intermediate data tables, the identifier fields in the intermediate data tables are compressed and merged to obtain multiple compressed data tables. The compression and merging includes at least deduplication of duplicate identifier fields and interval partitioning or encoding of continuously valued or groupable identifier fields to reduce field redundancy and maintain connectivity. Based on the value frequency and value range distribution of the original numerical fields in the candidate data tables, data sampling is performed on the numerical fields in the multiple compressed data tables to obtain multiple sampled data tables whose distribution deviation from the original numerical fields does not exceed a preset threshold. Based on the multiple sampled data tables, the first data table set is constructed. Verify whether the query score of the initial query result meets the preset usability standard threshold; In response to meeting the preset availability criterion threshold, the initial query statement is determined as the target query statement; If the preset availability standard threshold is not met, the language model is invoked to perform a second inference on the natural language query request, the candidate data set, and the initial query result. A corrected query statement is generated based on the second inference result, and the corrected query statement is executed on the first data set to obtain a corrected query result. The query score of the corrected query result is verified to meet the preset availability standard threshold. If it does meet the threshold, the corrected query statement is determined as the target query statement. If the query score of the corrected query result still does not meet the preset usability standard threshold, the language model is invoked to perform a third inference on the natural language query request, the candidate data set, and the corrected query result. A third query statement is generated based on the third inference result, and so on, until the query score of the currently generated query statement meets the preset usability standard threshold or the preset inference count limit is reached.
2. The query statement generation method according to claim 1, characterized in that, The query relevance includes at least primary and secondary relevance, and determining whether there is a query relevance between the natural language query request and the historical query records includes: The natural language query request and the historical query record are parsed to obtain the current data object and the historical data object, respectively. By comparing the identification information of the current data object with the identification information of the historical data object, it is determined whether there is a logical relationship between the current data object and the historical data object at the database structure level; If the response is no, it is determined that the natural language query request and the historical query record are not related. Therefore, it is determined that the natural language query request and the historical query record have the first-level correlation.
3. The query statement generation method according to claim 2, characterized in that, After determining that the natural language query request and the historical query record have the first-level correlation, the method further includes: The operation features of the natural language query requests and the historical query records are extracted and compared respectively. Based on the comparison results of the operation features, it is determined whether there is an operational correlation between the natural language query request and the historical query record in terms of query operation method; If so, it is determined that the natural language query request and the historical query record have the second-level correlation; If not, it is determined that the natural language query request and the historical query record do not have the secondary association.
4. The query statement generation method according to claim 2, characterized in that, The step of determining the candidate data table set based on the historical query data table in the historical query records includes: In response to the fact that the natural language query request and the historical query record have at least the first-level correlation, the structural correlation information of the current data object and the historical data object is extracted from the corresponding database and the correlation path is determined; Based on the association path, an intermediate table is extracted from the database and combined with the historical query data table corresponding to the historical data object to generate an initial data table set; Based on the metadata information of the current data object, a baseline feature vector is generated to characterize the features of the current data object; Based on the feature dimension corresponding to the benchmark feature vector, multiple table feature vectors are generated for multiple data tables in the initial data table set, and the vector similarity between the multiple table feature vectors and the benchmark feature vector is obtained. Multiple data tables whose vector similarity is less than a preset table similarity threshold are removed from the initial data table set, and the removed initial data table set is used as the candidate data table set.
5. The query statement generation method according to claim 3, characterized in that, After determining that the natural language query request and the historical query record have the second-level correlation, the method further includes: Parse the natural language query request to obtain a query operation feature vector representing the query intent; Identify multiple historical query statements related to the candidate data table set from the historical query records, and filter out multiple candidate query statements whose vector similarity with the query operation feature vector is greater than or equal to a preset query operation similarity threshold; Extract key constraint information from multiple candidate query statements and perform feature fusion to obtain constraint fusion features; Based on the constraint fusion features, a preliminary query statement is generated within the data range defined by the candidate data table set, for fusion with subsequent query statements.
6. The query statement generation method according to claim 1, characterized in that, The method further includes: If the natural language query request has no query relevance to the historical query records, then the natural language query request is parsed to determine the query semantic elements. These query semantic elements include at least query subject terms, target field terms, and constraint condition terms. Based on the query keywords, a target database is determined, and multiple data tables in the target database that have field associations with the target keywords are identified. Based on the constraint terms, the identified multiple data tables are aggregated to generate the candidate data table set.
7. The query statement generation method according to claim 1, characterized in that, The process of invoking the pre-trained language model to perform a first inference on the natural language query request and candidate data set, and generating an initial query statement based on the first inference result, includes: The semantics of the natural language query request are parsed to generate a query semantic vector that represents the semantic features of the current query request; Extract the structure and field information of the candidate data set; The structural information, the field information, and the query semantic vector are structurally combined based on a preset input template to generate an input prompt vector; The input prompt vector is input into the language model to obtain the first inference result output by the language model. The first inference result includes at least a query logic structure tree to indicate at least the operational relationship between fields, filtering logic, and connection path. Based on the query logic structure tree, an initial query statement conforming to the syntax rules of the candidate data table set is generated.
8. The query statement generation method according to claim 1, characterized in that, The step of verifying whether the query score of the initial query result meets the preset usability standard threshold includes: Based on the structural information of the first data table set, semantic checks are performed on the field references, join conditions, and aggregation operations contained in the initial query statement to determine whether the initial query statement is consistent with the field definitions, primary and foreign key relationships, and field dependencies in the first data table set. If an inconsistency is detected, the initial query statement is determined to be unavailable, and the initial query statement is corrected. If consistency is achieved, the accuracy, consistency, and statement execution performance of the initial query results are analyzed, and a query score for the initial query results is generated for comparison with the preset usability standard threshold.
9. An electronic device, characterized in that, include: Memory, used to store computer programs; A processor for executing the computer program to implement the query statement generation method as described in any one of claims 1 to 8.
Citation Information
Patent Citations
Structured query statement generation method and device, medium and program product
CN119739734A
Method for generating steel field TEXT2SQL based on LLM enhanced by RAG
CN120296037A