A dynamic query method and system based on a running scenario and an electronic device thereof

By automatically mounting business programs into the enterprise information management system and dynamically tailoring SQL using a large language model and template database, the problem of users having difficulty constructing accurate SQL queries is solved, achieving high-accuracy and low-cost natural language queries, suitable for complex business scenarios and highly stable systems.

CN121614494BActive Publication Date: 2026-05-29ZHEJIANG WEIMENG HOSPITAL MANAGEMENT CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
ZHEJIANG WEIMENG HOSPITAL MANAGEMENT CO LTD
Filing Date
2026-02-02
Publication Date
2026-05-29

AI Technical Summary

Technical Problem

In complex enterprise information management systems, ordinary users find it difficult to directly construct accurate SQL query statements. Existing technologies struggle to automatically and non-intrusively extract real SQL and build high-quality semantic vector libraries, resulting in insufficient accuracy and practicality of natural language queries in complex business scenarios.

Method used

By automatically mounting preset business programs onto the runtime business system, real-time runtime data is obtained. Utilizing a large language model and template database, templates are dynamically pruned and filtered based on location features and conditional features to generate standard SQL statements. Combined with JavaAgent technology, high-frequency SQL is captured non-intrusively, and a high-quality training dataset is constructed to enhance query accuracy and user intent matching.

Benefits of technology

It significantly improves the accuracy and usability of natural language queries in complex business scenarios, reduces the risk of generation errors, lowers maintenance costs, and is suitable for legacy systems that cannot be modified, especially for scenarios with high stability requirements such as finance and telecommunications.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121614494B_ABST
    Figure CN121614494B_ABST
Patent Text Reader

Abstract

The application relates to the technical field of database intelligent query, in particular to a dynamic query method and system based on a running scene and electronic equipment thereof, the method comprises the following steps: generating real-time running data based on business link data and a preset business program after mounting; obtaining a query statement corresponding to a query user, outputting relevant training data based on a query vector combination and a preset vector database; inputting the query statement and the relevant training data into a large language model, and calling a preset parameter mechanism to obtain a structured parameter; positioning an abstract filtering template in a template database based on a positioning feature, and dynamically cutting the abstract filtering template based on a condition feature to obtain an SQL standard statement corresponding to the query statement. The application adopts a template and a dynamic cutting strategy, enhances query accuracy and user intention matching degree, and significantly improves the accuracy and practicability of natural language query in a complex business scene under the premise of guaranteeing correct SQL execution.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the technical field of intelligent database query, and in particular to a dynamic query method, system and electronic device based on operating scenarios. Background Technology

[0002] In modern large-scale enterprise information management systems (such as ERP, CRM, medical consumables SPD, supply chain management, and financial risk control), the business logic is highly complex. The underlying database query statements (SQL) called by the code often contain multi-table joins, nested subqueries, and complex combinations of conditions (such as status enumeration, time windows, and business rule fields). For example, "Query delivery orders within the last 30 days whose delivery status is 'shipped' and billing status is 'unsettled'." Such SQL is often written by professional developers or system analysts, and ordinary users find it difficult to directly construct accurate SQL query statements.

[0003] Existing technical solutions collect business-related SQL query statements through multiple channels, including parsing and extracting database audit logs, reviewing example queries in system design documents, and having domain experts write corresponding SQL statements based on natural language query requirements provided by business personnel. These query samples are then aggregated to provide a wide range of query patterns and structures, ensuring data diversity and comprehensiveness. Data preprocessing techniques are employed to clean and standardize the acquired SQL samples, specifically performing field type identification, query deduplication and normalization, and sensitive information anonymization. The tables and fields involved in each SQL statement and their data types are identified to guide subsequent template filling. Duplicate and inconsistently formatted queries are removed, and SQL statement formats are standardized. Sensitive constant values ​​in the SQL are replaced with generic placeholders, ensuring data accuracy and consistency and providing a high-quality foundation for subsequent data generation and optimization.

[0004] Because complex SQL queries in business scenarios are difficult to understand using simple natural language, and user queries are often presented in simple natural language, existing technical solutions struggle to retrieve the problems and corresponding SQL queries. Therefore, there is an urgent need for a method that can automatically and non-intrusively extract real SQL queries from runtime business systems and build a high-quality semantic vector library based on these real queries. Summary of the Invention

[0005] In order to automatically and non-intrusively extract real SQL from runtime business systems, build a high-quality semantic vector library based on real queries, and combine a dynamic query enhancement mechanism with a large model for accurate slot filling, thereby significantly improving the accuracy and practicality of natural language queries in complex business scenarios while ensuring the correct execution of SQL, this application provides a dynamic query method, system, and electronic device based on runtime scenarios.

[0006] This application provides a dynamic query method based on runtime scenarios, employing the following technical solution:

[0007] A dynamic query method based on runtime scenarios includes the following steps:

[0008] Obtain the preset business program name and the corresponding configuration file data, and mount the preset business program based on the preset business program name and the configuration file data;

[0009] Obtain business link data corresponding to the preset business program, and generate real-time running data based on the business link data and the mounted preset business program;

[0010] Obtain the query statement corresponding to the query user, determine the query vector combination based on the query statement, and output relevant training data based on the query vector combination and a preset vector database;

[0011] The query statement and the relevant training data are input into the large language model, and a preset parameter mechanism is invoked to obtain structured parameters, which include localization features and conditional features.

[0012] Based on the location features, an abstract filter template is located in the template database, and the abstract filter template is dynamically trimmed based on the condition features to obtain the standard SQL statement corresponding to the query statement.

[0013] By adopting the above technical solution, a preset business program is mounted based on the preset business program name and the configuration file data. The preset business program automatically and non-intrusively extracts real SQL data in the runtime business system. An abstract filtering template is located in the template database based on the positioning features, and the abstract filtering template is dynamically trimmed based on the condition features to obtain the standard SQL statement corresponding to the query statement. By adopting template and dynamic trimming strategies, the accuracy of the query and the matching degree of user intent are enhanced. Under the premise of ensuring the correct execution of SQL, the accuracy and practicality of natural language query in complex business scenarios are significantly improved.

[0014] In some embodiments, obtaining the query statement corresponding to the query user and determining the query vector combination based on the query statement includes the following steps:

[0015] Based on the query statement, determine the query keywords and replacement position information, and based on the query keywords, determine the basic query code;

[0016] The basic query code is inserted into the replacement position information to generate the query target, and the query vector combination is determined based on the query target.

[0017] By adopting the above technical solution, different query keywords are determined based on different operating scenario types, thereby improving the accuracy of obtaining query vector combinations; the replacement position information is determined based on the basic query code and the preset query statement, and the basic query code is inserted at the replacement position to determine the query vector combination.

[0018] In some embodiments, the real-time runtime data includes raw SQL parameters and an abstract filtering template corresponding to the raw SQL parameters. The real-time runtime data is generated based on the business link data and the mounted preset business program. The abstract filtering template generation method includes the following steps:

[0019] The original SQL parameters are generated based on the business link data and the mounted preset business program.

[0020] The original SQL parameters are abstracted to obtain model training parameters, and it is determined whether the model training parameters include a deduplication identifier.

[0021] If the model training parameters do not include a deduplication identifier, then the model training parameters are trained based on a preset training model to generate a corresponding abstract filtering template.

[0022] If the model training parameters include a deduplication identifier, then the corresponding abstract filtering template is obtained from the preset model database based on the model training parameters.

[0023] In some embodiments, the model training parameters are trained based on a preset training model to generate a corresponding abstract screening template, including the following steps:

[0024] Based on the model training parameters, the placeholder type is determined, and the model training parameters are replaced with the corresponding placeholder type in the original SQL parameters to obtain the abstract filtering template.

[0025] In some embodiments, the abstract filtering template is dynamically trimmed based on the conditional features to obtain the standard SQL statement corresponding to the query statement, including the following steps:

[0026] Determine whether the parameter value exists based on the aforementioned conditional features;

[0027] If the parameter value exists, an instantiation signal is generated, and the filling position is determined based on the instantiation signal. The abstract filter template is then filled based on the filling position and the conditional features.

[0028] If the parameter value does not exist, a clipping signal is generated, and the clipping position is determined based on the clipping signal. The abstract filtering template is then clipped based on the clipping position and the conditional features.

[0029] The SQL standard statement is determined based on the abstract filter template after it has been filled and / or cropped.

[0030] In some embodiments, relevant training data is output based on the query vector combination and a preset vector database, wherein the generation of the preset vector database includes the following steps:

[0031] Training data is determined based on an abstract screening template, and the training data is annotated by experts to obtain mapping training parameters;

[0032] A rule document is constructed based on the mapping training parameters, and an example document is determined based on historical running scenario data. A training data set is then determined based on the rule document and the example document.

[0033] The training data set is encoded based on a pre-trained model to generate high-dimensional vectors, and the high-dimensional vectors are stored in a preset vector database.

[0034] In some embodiments, after dynamically trimming the abstract filter template based on the conditional features to obtain the standard SQL statement corresponding to the query statement, the following steps are further included:

[0035] Set a dynamic threshold and count the frequency of calls to the abstract filtering template in real time. Determine a high-frequency query pattern based on the dynamic threshold and the call frequency.

[0036] Monitor user interaction and correction behavior regarding the query results corresponding to standard SQL statements, and parse the newly added query logic in the correction content;

[0037] The newly added logic is converted into structured training data, the training data is semantically vector encoded, and the preset vector database and template database are updated based on the semantic vector encoding.

[0038] The semantic retrieval strategy for standard SQL statements is optimized based on the updated database and high-frequency query patterns.

[0039] In some embodiments, updating the preset vector database and template database based on the semantic vector encoding includes the following steps:

[0040] The preset vector database and template database are automatically updated based on the newly supplemented training data.

[0041] Secondly, this application provides a dynamic query system based on operational scenarios, employing the following technical solution:

[0042] A dynamic query system based on runtime scenarios, executing the dynamic query method based on runtime scenarios described in the first aspect, includes:

[0043] The program processing module is used to obtain the preset business program name and the corresponding configuration file data, and to mount the preset business program based on the preset business program name and the configuration file data.

[0044] The data acquisition module is used to acquire business link data corresponding to the preset business program, and generate real-time running data based on the business link data and the mounted preset business program.

[0045] The semantic vectorization module is used to obtain the query statement corresponding to the query user, determine the query vector combination based on the query statement, and output relevant training data based on the query vector combination and a preset vector database.

[0046] The large language processing module is used to input the query statement and the relevant training data into the large language model, and call the preset parameter mechanism to obtain structured parameters, which include localization features and conditional features.

[0047] The SQL management module is used to locate the abstract filter template in the template database based on the location features, and to dynamically trim the abstract filter template based on the condition features to obtain the standard SQL statement corresponding to the query statement.

[0048] Thirdly, this application provides an electronic device that adopts the following technical solution:

[0049] An electronic device includes a processor and a memory coupled to each other, the memory storing a computer program capable of running on the processor;

[0050] When the computer program is executed by the processor, it implements the dynamic query method based on the running scenario as described in the first aspect.

[0051] In summary, this application includes at least one of the following beneficial technical effects:

[0052] Based on the preset business program name and the configuration file data, the preset business program is mounted, and real SQL data is automatically and non-intrusively extracted in the runtime business system through the preset business program; based on the positioning features, the abstract filtering template is located in the template database, and the abstract filtering template is dynamically trimmed based on the condition features to obtain the SQL standard statement corresponding to the query statement. By adopting the template and dynamic trimming strategy, the accuracy of the query and the matching degree of user intent are enhanced. Under the premise of ensuring the correct execution of SQL, the accuracy and practicality of natural language query in complex business scenarios are significantly improved.

[0053] This solution addresses the challenges of low accuracy, difficult business adaptation, and high maintenance costs in natural language to structured query (NL2SQL) scenarios within complex business environments. It constructs a high-quality training dataset by non-intrusive, real-time capture of real and valid SQL queries in a production environment. Furthermore, it combines vector databases with large language models for collaborative reasoning, achieving high-precision and robust natural language query capabilities.

[0054] By non-intrusively extracting validated SQL queries from real business systems as training and retrieval data, the generated query logic is ensured to be completely consistent with actual business rules. The large model only needs to complete slot value mapping (e.g., mapping "shipped" to delivery_status=2), rather than generating complete SQL end-to-end, which greatly reduces conditional errors, field misuse, or logical omissions caused by biases in understanding business semantics, improving SQL generation accuracy by more than 40%.

[0055] By leveraging JavaAgent to automatically capture high-frequency, high-value SQL queries at runtime, and combining condition parsing and template clustering, a business query knowledge base is dynamically built and updated. Without manual annotation or static schema configuration, the system can automatically learn new query patterns (such as new status codes or new time dimensions) as business evolves, achieving adaptive evolution of query capabilities.

[0056] By embedding and encoding the structured conditions (fields, operators, values) and contextual semantics (such as table names and business descriptions) of historical SQL queries, a high-fidelity business semantic vector space is constructed. When a user asks a question, the system can accurately retrieve the most semantically similar real query template, providing strong contextual constraints for large models and significantly improving the reliability of intent recognition and slot filling.

[0057] The system employs a two-stage generation mechanism of "template + slot filling". The main SQL structure comes from a production-verified template, with only parameter values ​​dynamically replaced. It is executed through parameterized queries (Prepared Statement), fundamentally eliminating the risk of SQL injection. At the same time, it avoids generating SQL with syntax errors or poor performance (such as missing index fields or full table scans) in large models, ensuring database stability.

[0058] The complex task is broken down into two sub-tasks: "retrieval" and "imposition." Vector retrieval is responsible for recalling the correct template, while the main model only needs to complete lightweight semantic mapping. Even if the main model has an ambiguous understanding of some terms, as long as the correct template is recalled during the retrieval phase, an accurate query can still be output. The overall robustness of the system is significantly better than the end-to-end NL2SQL solution.

[0059] JavaAgent-based bytecode enhancement technology can extract SQL in real time in the production environment without modifying business code or restarting the application. It is particularly suitable for legacy systems that cannot be modified or for scenarios with extremely high stability requirements, such as finance and telecommunications. It has low deployment costs and low barriers to entry. Attached Figure Description

[0060] Figure 1 This is a flowchart of a dynamic query method based on a runtime scenario provided in an embodiment of this application;

[0061] Figure 2 This is a flowchart of the intelligent query processing provided in the embodiments of this application;

[0062] Figure 3 This is a schematic diagram of the system structure provided in the embodiments of this application;

[0063] Figure 4 This is a schematic diagram of an electronic device provided in an embodiment of this application.

[0064] Reference numerals: 10, electronic device; 11, processor; 12, memory; 121, computer program. Detailed Implementation

[0065] To better understand the purpose, technical solutions, and advantages of this application, it has been described and illustrated below with reference to the accompanying drawings and embodiments. However, those skilled in the art should understand that this application can be implemented without these details. In some cases, to avoid obscuring various aspects of this application due to unnecessary description, well-known methods, processes, systems, components, and / or circuits already described at a higher level will not be elaborated upon. It will be apparent to those skilled in the art that various modifications can be made to the embodiments disclosed in this application, and the general principles defined in this application can be applied to other embodiments and application scenarios without departing from the principles and scope of this application. Therefore, this application is not limited to the illustrated embodiments, but conforms to the broadest scope consistent with the scope of protection claimed in this application.

[0066] This application discloses a dynamic query method based on a runtime scenario.

[0067] like Figure 1 As shown, the dynamic query method based on the runtime scenario includes the following steps:

[0068] S101, obtain the preset business program name and the corresponding configuration file data, and mount the preset business program based on the preset business program name and configuration file data.

[0069] The preset business application name primarily refers to the program identifier of the target business system in the runtime scenario to be queried. In Java applications, this typically refers to the fully qualified name of the main class (e.g., com.example.OrderApplication), the JAR package name (e.g., order-service-1.0.0.jar), and the process identifier (e.g., PID or service name). Since different business systems correspond to different query base codes, the preset business application name is needed to inform the system which application to retrieve. The system determines how to mount and monitor the preset business application based on the configuration file data. To increase the flexibility of the entire operating system, different configurations can be set for different systems, and the system can determine the corresponding configuration file data based on the preset business application name. The system then executes the mounting operation using the Agent program based on the preset business application name and the configuration file data.

[0070] It's worth noting that the system can automatically identify and locate preset business systems based on their names, without requiring manual process ID specification or complex configuration. Monitoring policies are defined through configuration files, allowing the same agent program to adapt to different business systems and monitoring needs. Dynamic injection and unloading of SQL capture capabilities are achieved without interrupting business services.

[0071] S102, obtain the business link data corresponding to the preset business program, and generate real-time running data based on the business link data and the preset business program after mounting.

[0072] Among them, business link data refers to the entry points for running preset business programs. This business link data includes access links from different test environments. Business link data can be links automatically generated when the preset business program is mounted, or it can be dynamically supplemented during the runtime of the preset business program. Real-time runtime data is operational data generated in real time during the execution of the business system, captured and enhanced by the Agent. Real-time runtime data is a concrete instantiation of business link data.

[0073] It's important to note that a custom Java Agent (such as mybatis-sql-agent.jar) is loaded when the business system starts. This Agent dynamically modifies the execution logic of JDBC-related classes in the target application (app.jar) using bytecode enhancement technology (Instrumentation), intercepting the PreparedStatement.executeQuery() method. When the business system executes SQL, the Agent can capture its raw SQL text and bound parameters (such as supplier_id=132, delivery_status=0).

[0074] S103: Obtain the query statement corresponding to the query user, determine the query vector combination based on the query statement, and output relevant training data based on the query vector combination and the preset vector database.

[0075] The query statement is a request submitted by the user using natural language. The system retrieves the user's input in natural language, such as: "List all delivery orders received but not invoiced in December 2024." The pre-defined vector database includes several sets of training data, each containing training rules and examples. Relevant training data refers to historical learning materials found in the pre-defined vector database that are most relevant to the current query. Relevant training data includes relevant rules and example documents.

[0076] For example, the training rule is that the delivery status is "in delivery," corresponding to a delivery_status of 0. The corresponding rule vector is generated using `embed("Delivery status is in delivery...")`. The problem in the corresponding training example is to list delivery orders that have been accepted and invoiced by October 2025. Example vectors are generated using `embed("List delivery orders that have been accepted and invoiced by October 2025")`.

[0077] Specifically, when a user's query is "Are there any delivery orders that are being accepted but haven't been invoiced yet?", a pre-trained embedding model (such as qwen3-embedding, bge-m3, etc.) encodes each piece of training data (including rules and examples), generating a high-dimensional vector, which is then stored in a vector database (such as ChromaDB, Faiss). This vector database supports semantic similarity retrieval, providing accurate recall capabilities for subsequent user queries. When a user submits a question through the intelligent question-answering system, such as "Are there any delivery orders that are being accepted but haven't been invoiced yet?", the user's question is encoded into a vector using the embedding model. A similarity retrieval is then performed from the vector database, returning the most relevant training data (including rules and examples), providing contextual support for the larger model. Mapping the user's natural language to business terms "highlights" the key points for the larger model, telling it which business rules to focus on, ensuring that the retrieved templates and rules are truly relevant, and reducing the error rate from the source.

[0078] It should be noted that the relevant training data is obtained based on the similarity between the query vector combination and the preset vector database. Data in the preset vector database that has a certain similarity to the query vector combination can be used as relevant training data. Here, we can set data with a similarity greater than 0.6 as relevant training data.

[0079] S104: Input the query statement and related training data into the large language model, and call the preset parameter mechanism to obtain structured parameters.

[0080] The structured parameters include location features and conditional features, with a default parameter mechanism of Function Call. The user question and search results are input into the Large Language Model (LLM), and the Function Call mechanism is invoked, requiring the LLM to output structured parameters. These structured parameters include sql_template_id set to 1, delivery_status set to 4, bill_status set to 0, start_time set to null, and end_time set to null. When the system receives the user question "Are there any delivery orders that are under acceptance but not yet invoiced?", it breaks down the question into: "Under acceptance" → check business rules → delivery_status=4; "Not yet invoiced" → check business rules → bill_status=0; "Delivery order" → check examples → sql_template_id=1; no time mentioned → start_time=null, end_time=null. The delivery_status parameter is of type integer|null, with allowed values ​​[0, 1, 2, 3, 4]. There is a `bill_status` parameter, of type integer|null, with allowed values ​​[0, 1, 2]. There is also a `sql_template_id` parameter, `const=1`, which is required. The final result is: `sql_template_id`: 1 (required field, fixed value set to 1); `delivery_status`: 4 (mapped from "not yet invoiced"); `bill_status`: 0 (0 is mapped from "not yet invoiced"); `start_time`: null (not mentioned, set to null); and `end_time`: null (not mentioned, set to null).

[0081] S105: Based on the location features, locate the abstract filter template in the template database, and dynamically trim the abstract filter template based on the condition features to obtain the SQL standard statement corresponding to the query statement.

[0082] The abstract filtering template refers to a pre-trained template that only needs to be instantiated. This template includes location placeholders and condition placeholders. Location placeholders enable quick location based on business rules. Location features typically refer to IDs, while location placeholders allow IDs to be set to "?" or {param_name}, which will not be elaborated here. The system contains many abstract filtering templates. The structure of each abstract filtering template (which fields to SELECT, which tables to FROM, JOIN conditions, GROUP BY, etc.) is fixed, correct, and has been validated in a production environment. However, some specific values ​​in the abstract filtering template are left as "empty" (placeholders). For example: SELECT * FROM orders WHERE status = {status} AND create_time >= {start_time}. Users ask a question in natural language, such as, "Help me find all shipped orders." The large model's task is not to generate complete SQL from scratch, but to understand the user's description and fill in the correct words in the corresponding blanks. By analyzing "shipped", combined with the business rules provided by the system ("shipped" corresponds to status=2), then fill in 2 in the {status} blank. The user did not mention the time, so the {start_time} blank is left blank. When the system receives the filled-in test paper, it will perform dynamic trimming. If a blank is not filled (such as {start_time}), the entire condition (AND create_time>={start_time}) will be crossed out (removed) from the test paper to ensure that the SQL logic is correct. Using parameterized query, the filled-in value is safely replaced to generate the final executable SQL: SELECT * FROM orders WHERE status=?, the parameter is [2].

[0083] Reference Figure 2 Specifically, users input their query questions through the front-end interface. First, the user's query is sent to the back-end service for processing. Next, semantic vectorization and vector retrieval are performed, using an embedding model to transform the user's question into vectors. A similarity search is conducted in the vector database, returning the most relevant training data. Then, large-scale model slot filling and parameter extraction are performed, feeding the user's question and retrieval results into a large language model for semantic understanding. The large model outputs structured query conditions (slot values) through a FunctionCall mechanism. SQL template assembly involves retrieving the corresponding SQL template from the database based on `sql_template_id` and replacing placeholders in the template with actual parameter values. Finally, the SQL is executed, using parameterized queries to safely execute the SQL statement. The results are then formatted and returned to the user interface.

[0084] It's important to note that for the template with ID 1, `{delivery_status}` is replaced with 4 and `{bill_status}` with 0. Since `start_time` is null, the condition `ANDgmt_create>={start_time}` is dynamically removed. Real-world runtime SQL is used as training data for NL2SQL. SQL queries that have been validated by business operations are automatically extracted from the production system as the sole reliable source for building semantic mappings and template libraries, solving the problem of user semantic generalization. A closed-loop intelligent query architecture of "extraction—annotation—retrieval—population—execution" is adopted, automatically expanding query capabilities as business evolves, forming an end-to-end, self-learning, and evolvable natural language query enhancement system. Based on non-intrusive real-time SQL capture technology using Java Agent, the MyBatis / JDBC execution chain is dynamically intercepted through JVM bytecode enhancement (Instrumentation), accurately obtaining the original SQL and binding parameters without modifying the business code. The SQL template extraction and MD5 deduplication mechanism converts SQL statements containing specific values ​​into generic templates with placeholders (e.g., delivery_status={delivery_status}), and calculates the MD5 hash of each template as a unique identifier, preventing duplicate collection and training of the same SQL statements from different users / sessions. For semantic understanding and retrieval, a dual-drive approach of rules and examples is adopted, together forming the contextual knowledge base for large-scale model inference. The entire solution requires no modification to existing business logic, making it particularly suitable for highly sensitive systems such as those in finance and healthcare where downtime and code modification are not feasible. As new SQL statements are executed in the production environment, the system automatically incorporates them into the template library, enabling dynamic expansion and optimization of query capabilities without manual intervention.

[0085] In one embodiment, obtaining the query statement corresponding to the query user and determining the query vector combination based on the query statement includes the following steps:

[0086] S106, determine the query keywords and replacement position information based on the query statement, and determine the basic query code based on the query keywords.

[0087] S107, insert the basic query code into the replacement position information to generate the query target, and determine the query vector combination based on the query target.

[0088] Query keywords refer to entity words and condition words with clear business significance extracted from the query statement. These words represent the core filtering conditions and business objects in the user's query intent. Query keywords are the first-level transformation result from natural language to structured query. They convert the user's colloquial expression into standardized business terms that the system can understand, laying the foundation for subsequent code generation and parameter conversion. For example, if the query statement is "find the delivery note that hasn't been settled yet," the identified query keywords are "not settled yet" and "delivery note." Replacement location information is the position in the code framework that identifies the empty positions where specific parameter values ​​need to be inserted. The system determines the replacement location based on the replacement location information.

[0089] The query base code is an executable code snippet corresponding to each query keyword, responsible for converting natural language keywords into specific database query parameter values ​​or conditional expressions. Each base code snippet implements specific conversion logic, such as converting "Beijing" to "region_code=11" and "tertiary hospital" to "hospital_level=1". The query base code "translates" business terms into code instructions that computers can understand and execute, and is the key conversion step that enables natural language queries to ultimately operate on the database.

[0090] Specifically, the process begins by understanding the user's intent (keywords), then generating execution code (base code). Template-driven secure generation ensures all queries are based on validated templates (replacement location information). Business knowledge is encapsulated into code snippets, encapsulating business rules into reusable code fragments. Through semantic parsing of natural language queries, query keywords are extracted, business entities and conditions are identified, template matching is performed, replacement location information is used to determine parameter insertion points in the template, base code is selected, and transformation code is chosen for each keyword. Once the query objective is generated, the code is inserted into the template to form a complete query. Query vectors are then combined to generate semantic vectors for subsequent retrieval.

[0091] In one embodiment, the abstract filtering template is dynamically trimmed based on conditional features to obtain the standard SQL statement corresponding to the query statement, including the following steps:

[0092] S108, determine whether the parameter value exists based on conditional features.

[0093] S109, if the parameter value exists, an instantiation signal is generated, and the filling position is determined based on the instantiation signal. The abstract filtering template is then filled based on the filling position and conditional features.

[0094] S110, if the parameter value does not exist, a clipping signal is generated, and the clipping position is determined based on the clipping signal. The abstract filtering template is clipped based on the clipping position and condition features.

[0095] S111, determine the standard SQL statement based on the filled and / or cropped abstract filter template.

[0096] Specifically, the corresponding SQL template is retrieved from the MySQL database based on `sql_template_id`. Placeholder parameters (e.g., `{delivery_status}=4`) are replaced. If a parameter is empty, the corresponding condition is skipped (e.g., `AND delivery_status={delivery_status}` is omitted). The SQL is executed securely using a parameterized query (Prepared Statement) to avoid SQL injection risks. The execution result is returned to the user.

[0097] It's important to note that the two-stage generation mechanism of "SQL template + Slot filling" means that the large model does not generate complete SQL; it only extracts structured parameters (Slots) from the user's question and fills them into a predefined template. This effectively avoids end-to-end generation risks such as syntax errors, field misuse, and missing logic.

[0098] If a parameter is not mentioned (e.g., no time range is specified), the corresponding WHERE condition is automatically removed instead of being assigned a null value by default, ensuring that the query logic matches the user's true intent. All final SQL statements are executed in a parameterized manner, fundamentally preventing SQL injection attacks and ensuring database security.

[0099] In one embodiment, the real-time runtime data includes raw SQL parameters and an abstract filtering template corresponding to the raw SQL parameters. The real-time runtime data is generated based on business link data and the mounted preset business program. The abstract filtering template generation method includes the following steps:

[0100] S201 generates raw SQL parameters based on business link data and the preset business program after mounting.

[0101] S202 abstracts the original SQL parameters to obtain model training parameters and determines whether the model training parameters include deduplication identifiers.

[0102] S203, if the model training parameters do not include deduplication identifiers, then the model training parameters are trained based on a preset training model to generate the corresponding abstract filtering template.

[0103] S204, if the model training parameters include a deduplication identifier, then obtain the corresponding abstract filtering template from the preset model database based on the model training parameters.

[0104] The deduplication identifier refers to the MD5 hash value. Specific parameter values ​​in the original SQL are replaced with uniform placeholders (such as {delivery_status}) to generate a parameterized SQL template. The MD5 hash value of the SQL template is calculated as a unique identifier. If the MD5 value already exists in the template library, storage is skipped; otherwise, the template and its metadata are stored in the SQL template table of the relational database.

[0105] Specifically, the captured raw SQL is parsed and standardized, replacing parameter values ​​with placeholders (such as ? or {param_name}) to generate a general SQL template. The MD5 hash of the template is extracted as a unique identifier for subsequent deduplication and version control. Information such as the original SQL, SQL template, MD5 hash, and execution context (such as user ID and timestamp) is retained. For example, if the original SQL contains `bill_status=0`, after processing, the template is generated as: `ANDspd_order_delivery.bill_status={bill_status}`. A corresponding deduplication identifier MD5 is also generated: `7fa6f43b47ff5d476aa2259c67254476`, preventing duplicate training of the same function.

[0106] In one embodiment, the model training parameters are trained based on a preset training model to generate a corresponding abstract screening template, including the following steps:

[0107] S205: Determine the placeholder type based on the model training parameters, and replace the model training parameters with the corresponding placeholder type in the original SQL parameters to obtain the abstract filtering template.

[0108] In one embodiment, relevant training data is output based on a combination of query vectors and a preset vector database. The preset vector database is generated by the following steps:

[0109] S301, determine the training data based on the abstract screening template, and perform expert annotation on the training data to obtain the mapping training parameters.

[0110] S302, construct a rule document based on the mapping training parameters, determine an example document based on historical running scenario data, and determine a training data set based on the rule document and the example document.

[0111] S303 encodes the training data set based on the pre-trained model to generate high-dimensional vectors, and stores the high-dimensional vectors in a preset vector database.

[0112] Semantic mapping annotation involves domain experts or semi-automatic systems establishing mapping rules for each condition field in the SQL template, from "natural language description to database value". For example, "shipped" → delivery_status=2; "not invoiced" → bill_status=0.

[0113] Two types of training documents are constructed: rule-based documents, which store the semantic mapping rules for fields, and example documents, which store typical user questions and their corresponding parameter filling results. Vectorization encoding and storage are performed using pre-trained embedding models (such as BGE or Qwen-Embedding) to encode each training document into a high-dimensional semantic vector. All vectors are stored in a vector database (such as ChromaDB or Faiss), and an index is built to support approximate nearest neighbor retrieval.

[0114] In one embodiment, after dynamically trimming the abstract filter template based on conditional features to obtain the standard SQL statement corresponding to the query statement, the following steps are also included:

[0115] S401: Set a dynamic threshold and count the call frequency of the abstract filtering template in real time. Determine the high-frequency query mode based on the dynamic threshold and the call frequency.

[0116] S402 monitors user interaction and correction behavior on the query results corresponding to standard SQL statements, and parses the newly added query logic in the correction content.

[0117] S403 transforms the parsed new logic into structured training data, performs semantic vector encoding on the training data, and updates the preset vector database and template database based on the semantic vector encoding.

[0118] S404 is a semantic retrieval strategy for standard SQL statements that optimizes based on the updated database and high-frequency query patterns.

[0119] This invention updates the knowledge base through online incremental learning, avoiding the impact of full-data retraining on online services. The dynamic threshold is adaptively calculated based on the statistical characteristics of historical call data and supports manual calibration. User correction operations include, but are not limited to, one or more of the following: condition supplementation, parameter adjustment, and range change. To address the technical problems of high maintenance costs and poor adaptability in existing intelligent query systems, this invention proposes a closed-loop self-evolution mechanism based on user feedback. This mechanism automatically identifies high-frequency query patterns and correction intentions by sensing user behavior in real time; automatically extracts incremental knowledge and transforms user corrections into structured training data; updates the knowledge base online, learning only from newly added content to avoid full-data retraining; and dynamically optimizes retrieval strategies to improve query efficiency and accuracy based on the updated knowledge base.

[0120] In one embodiment, updating the preset vector database and template database based on semantic vector encoding includes the following steps:

[0121] S405 automatically updates the preset vector database and template database based on the newly supplemented training data.

[0122] This continuous, non-intrusive SQL interception mechanism loads a pre-configured JavaAgent program upon startup of the target business system. Through bytecode enhancement technology, it dynamically modifies the method logic of SQL execution-related classes in the JDBC driver or ORM framework, enabling runtime interception of `PreparedStatement.executeQuery()` and similar methods. It captures the original SQL and its parameters. When the business system executes a database query, the interceptor captures in real-time: the original SQL text and bound parameter values ​​(e.g., `delivery_status=2`), the execution context (user ID, timestamp, application module); and SQL template and deduplication. It replaces specific parameter values ​​in the original SQL with uniform placeholders (e.g., `{delivery_status}`), generates a parameterized SQL template, and calculates the MD5 hash value of the SQL template as a unique identifier. If the MD5 value already exists in the template library, storage is skipped; otherwise, the template and its metadata are stored in the "SQL Template Table" of a relational database. As the business system runs, this automatically accumulates to form an SQL template knowledge base composed of real production queries.

[0123] This application also discloses a dynamic query system based on operating scenarios.

[0124] The dynamic query system based on runtime scenarios includes a program processing module, a data acquisition module, a semantic vectorization module, a large language processing module, and an SQL management module. The program processing module acquires the names of preset business programs and their corresponding configuration files, and then mounts the preset business programs based on these names and files. The data acquisition module acquires the business link data corresponding to the preset business programs and generates real-time runtime data based on this data and the mounted preset business programs. The semantic vectorization module acquires the query statement corresponding to the query user, determines the query vector combination based on the query statement, and outputs relevant training data based on the query vector combination and a preset vector database. The large language processing module inputs the query statement and relevant training data into a large language model and calls a preset parameter mechanism to obtain structured parameters, including location features and conditional features. The SQL management module locates abstract filtering templates in the template database based on location features and dynamically trims these templates based on conditional features to obtain the standard SQL statement corresponding to the query statement.

[0125] The other functions executed in the above-mentioned program processing module, data acquisition module, semantic vectorization module, large language processing module, and SQL management module, as well as the technical details of each function, are the same as or similar to the corresponding features in the dynamic query method based on the running scenario described above, so they will not be repeated here.

[0126] It should be noted here that the reference Figure 3 The system also includes a data training layer, which non-intrusively captures SQL queries in real time during business system operation, parses and extracts SQL templates, and updates them to the SQL template management service. A user interface layer provides a user interface for easy question input. An application service layer API gateway receives user requests and distributes them to available backend services. A natural language processing service preprocesses user input, including word segmentation and semantic transformation. A semantic vectorization service uses an embedding model to convert user questions into vector representations. A vector database service stores semantic vectors from training data and provides similarity retrieval functionality. A large language model service is used for semantic analysis and understanding, executing function calls to extract structured parameters. An SQL template management service manages and maintains SQL templates, metadata, SQL template MD5 values, and manually labeled training data. A data storage layer, a relational database, stores key information such as SQL templates and metadata. A vector database stores semantic vectors from training data processed by the embedding model to support fast similarity retrieval. The external interface layer integrates with other internal enterprise systems (such as SPD, ERP, CRM, etc.) to provide cross-system data access capabilities.

[0127] This application also discloses an electronic device.

[0128] Reference Figure 4 The electronic device includes a processor 11 and a memory 12 coupled to each other, and the memory 12 stores a computer program 121 that can run on the processor 11.

[0129] When computer program 121 is executed by processor 11, it implements a dynamic query method based on the running scenario.

[0130] The memory 12 may be a ROM or other type of static storage device capable of storing static information and instructions, a random access memory, or other type of dynamic storage device capable of storing information and instructions. It may also be an electrically erasable programmable read-only memory, a read-only optical disc or other optical disc storage, optical disc storage (including compressed optical discs, laser discs, optical discs, digital universal optical discs, Blu-ray discs, etc.), a magnetic disk storage medium, or other magnetic storage device. It may be any other medium capable of carrying or storing desired program code in the form of instructions or data structures and accessible by a computer, but is not limited thereto. In some embodiments, the memory 12 may be an internal storage unit.

[0131] Processor 11 can be a central processing unit, a general-purpose processor, a data signal processor, an application-specific integrated circuit, a field-programmable gate array, or other programmable logic devices, transistor logic devices, hardware components, or any combination thereof. It is used to run program code stored in memory 12 or process data.

[0132] Processor 11 and memory 12 are connected via a bus. The bus may include a pathway for transmitting information between the components. The bus may be a peripheral interconnect standard bus or an extended industry standard structure bus, etc. The bus can be divided into address bus, data bus, control bus, etc. For ease of representation, Figure 4 The bus is represented by a single thick line, but this does not mean that there is only one bus or one type of bus.

[0133] Figure 4 Only an electronic device 10 with memory 12, processor 11, and bus is shown. Those skilled in the art will understand that... Figure 4 The structure shown does not constitute a limitation on the electronic device 10. It can be a bus topology or a star topology. The electronic device 10 may also include more or fewer components than shown, or combine certain components, or deploy different components. Other existing or future electronic devices are applicable and should be included within the scope of protection, and are incorporated herein by reference.

[0134] The implementation principle is as follows:

[0135] The system receives natural language questions from users via an intelligent question-answering interface, such as "List all delivery orders accepted but not invoiced in December 2024." The user questions are encoded into vectors using the same embedding model. A similarity search is performed in the vector database, returning the Top-K most relevant rules and example documents as contextual knowledge. The user questions and the retrieved contextual knowledge are input into the large language model, requesting the model to output a structured parameter object via a predefined Function Call interface. The model only needs to identify and populate the following information: `sql_template_id`: the matching SQL template number; the values ​​of each condition field (e.g., `delivery_status=1`, `bill_status=0`); and dynamic parameters such as the time range. The corresponding SQL template is retrieved from the template library based on `sql_template_id`. The parameter values ​​output by the model replace the placeholders in the template; if a parameter value is empty, the entire condition clause corresponding to that parameter is automatically removed (dynamic condition pruning). The assembled SQL is parameterized and encapsulated to generate a `PreparedStatement`. Parameterized queries are executed through a database connection pool to eliminate the risk of SQL injection. Retrieve the query result set, convert it into a user-friendly format (such as JSON or a table), and return the results to the user interface.

[0136] It should be understood that although the steps in the flowcharts in the accompanying drawings are shown sequentially as indicated by the arrows, these steps are not necessarily performed in the order indicated by the arrows. Unless otherwise expressly stated herein, there is no strict order in which these steps are performed, and they may be performed in other orders.

[0137] The above are all preferred embodiments of this application, and are not intended to limit the scope of protection of this application. Therefore, all equivalent changes made in accordance with the structure, shape and principle of this application should be covered within the scope of protection of this application.

Claims

1. A dynamic query method based on runtime scenarios, characterized in that, Includes the following steps: Obtain the preset business program name and the corresponding configuration file data, and mount the preset business program based on the preset business program name and the configuration file data; Obtain business link data corresponding to the preset business program, and generate real-time running data based on the business link data and the mounted preset business program. The real-time running data includes original SQL parameters and an abstract filter template corresponding to the original SQL parameters. The abstract filter template is generated by the following steps: The original SQL parameters are generated based on the business link data and the mounted preset business program. The original SQL parameters are abstracted to obtain model training parameters, and it is determined whether the model training parameters include a deduplication identifier in order to determine the abstract filtering template. Obtain the query statement corresponding to the query user, determine the query vector combination based on the query statement, and output relevant training data based on the query vector combination and the preset vector database. The relevant training data refers to the historical learning materials found in the preset vector database that are most relevant to the current query. The query statement and the relevant training data are input into the large language model, and a preset parameter mechanism is invoked to obtain structured parameters, including localization features and conditional features. The preset parameter mechanism refers to the Function Call mechanism. Based on the location features, an abstract filter template is located in the template database, and the abstract filter template is dynamically trimmed based on the condition features to obtain the SQL standard statement corresponding to the query statement. The location feature refers to the ID value. The ID value is filtered in the template database to obtain templates with the same location feature as the abstract filtering template. The abstract filtering template is dynamically trimmed based on the conditional features to obtain the standard SQL statement corresponding to the query statement, including the following steps: Determine whether the parameter value exists based on the aforementioned conditional features; If the parameter value exists, an instantiation signal is generated, and the filling position is determined based on the instantiation signal. The abstract filter template is then filled based on the filling position and the conditional features. If the parameter value does not exist, a clipping signal is generated, and the clipping position is determined based on the clipping signal. The abstract filtering template is then clipped based on the clipping position and the conditional features. The SQL standard statement is determined based on the abstract filter template after it has been filled and / or cropped.

2. The dynamic query method based on operational scenarios according to claim 1, characterized in that, Obtain the query statement corresponding to the query user, and determine the query vector combination based on the query statement, including the following steps: Based on the query statement, the query keywords and replacement position information are determined, and the query base code is determined based on the query keywords. The replacement position information is the position in the code framework, which identifies the empty position where specific parameter values ​​need to be inserted. The query base code is an executable code segment corresponding to each query keyword, which is responsible for converting natural language keywords into specific database query parameter values ​​or conditional expressions. The basic query code is inserted into the replacement position information to generate the query target, and the query vector combination is determined based on the query target.

3. The dynamic query method based on runtime scenarios according to claim 1, characterized in that, Determining whether the model training parameters include deduplication identifiers to determine the abstract filtering template includes the following steps: Determine whether the model training parameters include a deduplication identifier; If the model training parameters do not include a deduplication identifier, then the model training parameters are trained based on a preset training model to generate a corresponding abstract filtering template. If the model training parameters include a deduplication identifier, then the corresponding abstract filtering template is obtained from the preset template database based on the model training parameters.

4. The dynamic query method based on runtime scenarios according to claim 3, characterized in that, The model training parameters are trained based on a preset training model to generate a corresponding abstract screening template, including the following steps: Based on the model training parameters, the placeholder type is determined, and the model training parameters are replaced with the corresponding placeholder type in the original SQL parameters to obtain the abstract filtering template.

5. The dynamic query method based on operational scenarios according to claim 1, characterized in that, Based on the query vector combination and the preset vector database, relevant training data is output. The generation of the preset vector database includes the following steps: Training data is determined based on an abstract screening template, and the training data is annotated by experts to obtain mapping training parameters; A rule document is constructed based on the mapping training parameters, and an example document is determined based on historical running scenario data. A training data set is determined based on the rule document and the example document. The rule document is used to store field semantic mapping rules, and the example document is used to store typical user questions and their corresponding parameter filling results. The training data set is encoded based on a pre-trained model to generate high-dimensional vectors, and the high-dimensional vectors are stored in a preset vector database.

6. The dynamic query method based on runtime scenarios according to claim 1, characterized in that, After dynamically trimming the abstract filtering template based on the conditional features to obtain the standard SQL statement corresponding to the query statement, the following steps are also included: Set a dynamic threshold and count the frequency of calls to the abstract filtering template in real time. Determine a high-frequency query pattern based on the dynamic threshold and the call frequency. Monitor user interaction and correction behavior regarding the query results corresponding to standard SQL statements, and parse the newly added query logic in the correction content; The newly added logic is converted into structured training data, the structured training data is semantically vector encoded, and the preset vector database and template database are updated based on the semantic vector encoding. The semantic retrieval strategy for standard SQL statements is optimized based on the updated database and high-frequency query patterns.

7. The dynamic query method based on runtime scenarios according to claim 6, characterized in that, Updating the preset vector database and template database based on the semantic vector encoding includes the following steps: The preset vector database and template database are automatically updated based on the newly supplemented training data.

8. A dynamic query system based on operational scenarios, characterized in that, Executing the dynamic query method based on a runtime scenario as described in any one of claims 1-7 includes: The program processing module is used to obtain the preset business program name and the corresponding configuration file data, and to mount the preset business program based on the preset business program name and the configuration file data. The data acquisition module is used to acquire business link data corresponding to the preset business program, and generate real-time running data based on the business link data and the mounted preset business program. The semantic vectorization module is used to obtain the query statement corresponding to the query user, determine the query vector combination based on the query statement, and output relevant training data based on the query vector combination and a preset vector database. The large language processing module is used to input the query statement and the relevant training data into the large language model, and call the preset parameter mechanism to obtain structured parameters, which include localization features and conditional features. The SQL management module is used to locate the abstract filter template in the template database based on the location features, and to dynamically trim the abstract filter template based on the condition features to obtain the standard SQL statement corresponding to the query statement.

9. An electronic device, characterized in that, The electronic device includes a processor and a memory coupled to each other, wherein the memory stores a computer program that can run on the processor; When the computer program is executed by the processor, it implements the dynamic query method based on the running scenario as described in any one of claims 1-7.

Citation Information

Patent Citations

  • Text-to-structured query language conversion method based on large language model

    CN119415546A

  • Large model Text-to-SQL conditional clause improvement method and system based on fuzzy recall field value enhancement

    CN120277103A