Database query method and device and storage medium

By performing entity recognition and semantic understanding on natural language query requests, and combining the database relationship graph to generate main and extended query statements, the problem of query accuracy in multi-table join scenarios is solved, and efficient and accurate database operations are achieved.

CN121996704APending Publication Date: 2026-05-08WEBANK (CHINA)
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
WEBANK (CHINA)
Filing Date
2026-02-05
Publication Date
2026-05-08

AI Technical Summary

Technical Problem

In complex query scenarios involving multiple table joins, existing technologies cannot effectively discover and utilize implicit business relationships, resulting in generated SQL statements with missing join tables or lengthy and incorrect join paths, affecting query accuracy.

Method used

By performing entity recognition and semantic understanding on natural language query requests, the main query statement is generated. The relationship between tables is automatically discovered using a pre-set database relationship graph, and extended query statements are dynamically generated to optimize the query path and ensure accuracy.

Benefits of technology

It enables efficient and accurate conversion of natural language intent into database operations in complex multi-table query scenarios, improving query accuracy and flexibility and adapting to dynamic business needs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121996704A_ABST
    Figure CN121996704A_ABST
Patent Text Reader

Abstract

The invention discloses a database query method and device and a storage medium, and relates to the technical field of data processing.The disclosed database query method comprises the steps that in response to a received natural language query request of a user, entity recognition and semantic understanding are conducted on the natural language query request, and a to-be-queried service entity and a query intention are obtained; generating a main query statement based on the business entity, the query intention and a preset database relation graph; generating an extended query statement based on the execution result of the main query statement and a database relation graph; and executing the extended query statement to obtain a query result corresponding to the natural language query request. According to the method, the database query accuracy in a multi-table association scene can be improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of data processing technology, and in particular to database query methods, devices and storage media. Background Technology

[0002] With the development of information technology, relational databases are widely used in enterprise data management, and their scale is becoming increasingly large, with the data tables and relationships between them becoming increasingly complex.

[0003] Currently, Natural Language to SQL (Structured Query Language) technology based on Large Language Models (LLM) is maturing. This technology can convert user-inputted database query intent in natural language into standardized SQL statements, which are then executed by the database management system, lowering the barrier for users to query the database. However, in complex queries involving multiple table joins, the join paths between the tables either strictly rely on predefined foreign key constraints in the database, failing to discover and utilize a large number of existing implicit business relationships, or require manually writing a large number of rules or maintaining join mappings. This lack of flexibility and difficulty in adapting to dynamically changing business needs often results in generated SQL statements with missing join tables, lengthy or incorrect join paths, affecting query accuracy.

[0004] In summary, improving the accuracy of database queries in multi-table join scenarios has become a pressing technical problem that needs to be solved in this field. Summary of the Invention

[0005] The main purpose of this application is to provide a database query method, device, and storage medium, which aims to improve the accuracy of database queries in multi-table join scenarios.

[0006] To achieve the above objectives, this application proposes a database query method, which includes: In response to a received user natural language query request, entity recognition and semantic understanding are performed on the natural language query request to obtain the business entity to be queried and the query intent; The main query statement is generated based on the business entity, the query intent, and the preset database relationship graph; An extended query statement is generated based on the execution result of the main query statement and the database relationship graph; Execute the extended query statement to obtain the query results corresponding to the natural language query request. In one embodiment, before the step of generating the main query statement based on the business entity, the query intent, and the preset database relationship graph, the method further includes: Obtain metadata information for each table in the target database; The importance score of each data table is calculated based on the metadata information, and the data tables are then divided into layers according to the importance score. Based on the results of the hierarchical division, the relationships between the data tables are determined according to a preset relationship discovery strategy, wherein the relationship discovery strategy includes a foreign key constraint analysis strategy, an LLM semantic analysis strategy, and a field similarity calculation strategy. The relationships described are verified and optimized, and a database relationship graph is constructed based on the verified and optimized relationships.

[0007] In one embodiment, the step of generating the main query statement based on the business entity, the query intent, and the preset database relationship graph includes: Based on the business entity and the query intent, core data tables are selected from a preset database relationship graph; Based on the core data table and its associations in the database relationship graph, a preset query strategy is used to generate the main query statement.

[0008] In one embodiment, before the step of generating an extended query statement based on the execution result of the main query statement and the database relationship graph, the method further includes: Execute the main query statement; If the main query statement is executed successfully, the execution result of the main query statement is obtained; If the main query statement fails to execute, the main query statement is regenerated based on the failure feedback information.

[0009] In one embodiment, the step of generating an extended query statement based on the execution result of the main query statement and the database relationship graph includes: Determine the target data table corresponding to the execution result of the main query statement; Starting with the target data table as the starting node, a graph traversal search is performed in the database relationship graph to determine the associated data table; Based on the execution result of the main query statement and the associated data table, an extended query statement is generated.

[0010] In one embodiment, the step of performing a graph traversal search in the database relationship graph, starting with the target data table as the starting node, to determine the associated data table includes: Starting with the target data table as the starting node, a breadth-first search algorithm is used to perform a graph traversal search in the database relation graph; During the graph traversal search, the exploration priority of the adjacent nodes is determined based on the confidence of the connecting edges between the starting node and the adjacent nodes. Based on the exploration priority, at least one node is selected as an associated node from the adjacent nodes; The data table corresponding to the associated node is determined as the associated data table.

[0011] In one embodiment, the step of executing the expanded query statement to obtain the query result corresponding to the natural language query request includes: The extended query statement is executed in a streaming manner; If an error occurs during the execution of the extended query statement, an error handling process including a retry mechanism or a path switching mechanism will be triggered. If no error occurs, partial query results are returned in real time, and the query result corresponding to the natural language query request is obtained after the query is completed.

[0012] In one embodiment, after the step of executing the extended query statement to obtain the query result corresponding to the natural language query request, the method further includes: The query results are input into a preset intelligent dialogue agent, which analyzes the query results to obtain analytical conclusions in natural language form. Based on the analysis conclusions, output visualized query results.

[0013] In addition, to achieve the above objectives, this application also proposes an electronic device, which includes: a memory, a processor, and a computer program stored on the memory and executable on the processor, the computer program being configured to implement the steps of the database query method described above.

[0014] In addition, to achieve the above objectives, this application also proposes a storage medium, which is a computer-readable storage medium, on which a computer program is stored, and when the computer program is executed by a processor, it implements the steps of the database query method described above.

[0015] This application proposes a database query method. In response to a received user natural language query request, the method performs entity recognition and semantic understanding on the natural language query request to obtain the business entity to be queried and the query intent; generates a main query statement based on the business entity, the query intent and a preset database relationship graph; generates an extended query statement based on the execution result of the main query statement and the database relationship graph; and executes the extended query statement to obtain the query result corresponding to the natural language query request.

[0016] In summary, this application first performs semantic understanding of natural language to determine the user's query intent and specific business entities. Based on this, it uses a pre-defined database relationship graph to generate the main query statement, enabling the database management system to automatically discover and utilize various inter-table relationships in the database, including implicit associations. Then, it dynamically generates extended query statements based on the actual execution results of the main query statement and the relationship graph. This allows the system to start with the determined entities and data and explore the optimal association path in the relationship graph in a directional manner, avoiding missing associations or path errors in complex multi-table query scenarios. Finally, by executing the optimized extended query, it ensures that the user's complex natural language intent can be efficiently and accurately translated into database operations and returned results, thereby improving the accuracy of database queries. Attached Figure Description

[0017] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this application and, together with the description, serve to explain the principles of this application.

[0018] To more clearly illustrate the technical solutions in the embodiments of this application or the prior art, the drawings used in the description of the embodiments or the prior art will be briefly introduced below. Obviously, for those skilled in the art, other drawings can be obtained based on these drawings without creative effort.

[0019] Figure 1 This is a flowchart illustrating an embodiment of the database query method of this application. Figure 2 This is a schematic diagram of the database relationship graph construction process provided in Embodiment 2 of the database query method of this application; Figure 3 This is a schematic diagram of the hybrid relationship discovery engine provided in Embodiment 2 of the database query method of this application; Figure 4 This is a schematic diagram of the two-stage query planning and execution process provided in Embodiment 2 of the database query method of this application; Figure 5 This is a schematic diagram of the architecture of the streaming execution engine provided in Embodiment 2 of the database query method of this application; Figure 6 This is a schematic diagram of the device structure of the hardware operating environment involved in the database query method in this application embodiment.

[0020] The purpose, features, and advantages of this application will be further explained in conjunction with the embodiments and with reference to the accompanying drawings. Detailed Implementation

[0021] It should be understood that the specific embodiments described herein are merely illustrative of the technical solutions of this application and are not intended to limit this application.

[0022] With the development of information technology, relational databases are widely used in enterprise data management, and their scale is becoming increasingly large, with the data tables and relationships between them becoming increasingly complex.

[0023] Currently, natural language to SQL (NLP) technology based on large language models is maturing. This technology can convert user-inputted database query intent in natural language into standardized SQL statements, which are then executed by the database management system, lowering the barrier for users to query the database. However, in complex queries involving multiple table joins, the join paths between the tables either strictly rely on predefined foreign key constraints in the database, failing to discover and utilize a large number of existing implicit business relationships, or require manually writing a large number of rules or maintaining join mappings. This lack of flexibility and difficulty in adapting to dynamically changing business needs often results in generated SQL statements with missing join tables, lengthy or incorrect join paths, affecting query accuracy.

[0024] In summary, improving the accuracy of database queries in multi-table join scenarios has become a pressing technical problem that needs to be solved in this field.

[0025] This application provides a solution that, in response to a received user natural language query request, performs entity recognition and semantic understanding on the natural language query request to obtain the business entity to be queried and the query intent; generates a main query statement based on the business entity, the query intent, and a preset database relationship graph; generates an extended query statement based on the execution result of the main query statement and the database relationship graph; and executes the extended query statement to obtain the query result corresponding to the natural language query request.

[0026] In summary, this application first performs semantic understanding of natural language to determine the user's query intent and specific business entities. Based on this, it uses a preset database relationship graph to generate a main query statement, enabling the database management system to automatically discover and utilize various inter-table relationships in the database, including implicit associations. Then, it dynamically generates extended query statements based on the actual execution results of the main query statement and the relationship graph. This allows the system to start with the determined entities and data and explore the optimal association path in the relationship graph in a directional manner, avoiding missing associations or path errors in complex multi-table query scenarios. Finally, by executing the optimized extended query, it ensures that the user's complex natural language intent can be efficiently and accurately converted into database operations and returned results, thereby improving the accuracy of database queries.

[0027] It should be noted that the execution subject of this embodiment can be a computing service device with data processing, network communication and program running functions, such as a tablet computer, personal computer, mobile phone, etc., or an electronic device that can realize the above functions.

[0028] Based on this, the embodiments of this application provide a database query method, referring to... Figure 1 , Figure 1 This is a flowchart illustrating the first embodiment of the database query method of this application.

[0029] In this embodiment, the database query method includes steps S10 to S40: Step S10: In response to the received user natural language query request, perform entity recognition and semantic understanding on the natural language query request to obtain the business entity to be queried and the query intent; It should be noted that a user's natural language query request is an unstructured text request issued by the user based on their own data query needs. Its form is flexible and can include mixed Chinese and English expressions, as well as vague descriptions, business term abbreviations, etc.; business entity refers to the query target in the natural language query request; query intent is the purpose of the user's query, used to clarify the direction of the query needs.

[0030] It receives natural language query requests from users, performs entity recognition on the query request based on a preset schema (database architecture) context (including the target database table structure, field comments, and sample data), and extracts the business entities; at the same time, it performs semantic understanding on the query request to clarify the user's query intent; finally, it outputs the identified business entities and the parsed query intent.

[0031] For example, when a user sends a query request "Query user Zhang Wei's order information in 2024", after entity recognition, the business entities "Zhang Wei" and "2024" are obtained, and after semantic understanding, the query intent "Multi-table join query (user table + order table)" is obtained.

[0032] In one feasible implementation, entity recognition can employ specially optimized LLM prompts and context-aware algorithms, specifically optimizing for polyphonic characters and variant characters in Chinese names, abbreviations and alternative names of product names, and ambiguities in business terms, in order to further improve the accuracy of entity recognition.

[0033] Step S20: Generate the main query statement based on the business entity, query intent, and preset database relationship graph; It should be noted that a database relationship graph is a pre-constructed graph structure that describes the relationships between all data tables in a database. Nodes represent data tables, edges represent the relationships between tables, and attributes such as confidence level are attached.

[0034] The system can first filter the most likely related core data tables in the relationship graph based on the semantics of the business entity (e.g., "Zhang Wei") and the query intent (e.g., "query orders"), such as users (user table) and orders (order table). Then, based on the known relationships between these core data tables in the graph (e.g., the users table and the orders table are related through the user_id field), and considering different query strategies, it can generate one or more main query SQL statements aimed at locating the core data. For example, it might generate the main query statement "SELECT..." FROM usersWHERE username = 'Zhang Wei'.

[0035] Step S30: Generate an extended query statement based on the execution result of the main query statement and the database relationship graph; It should be noted that the execution result of the main query statement refers to the basic data in the core data table that matches the business entity; the extended query statement refers to the cross-table query statement generated based on the main query result and the database relationship graph, which is used to obtain supplementary information related to the core data.

[0036] The generated main query is executed. If the main query succeeds and obtains the user ID of "Zhang Wei" as 1001, the execution result is ID=1001, and the corresponding data table is the users table. Starting from the users table, the system re-traverses the database relationship graph, performing a graph traversal search to find other high-value data tables related to the users table. For example, if a strong relationship is found between the orders table and the users table, then, combining the execution result of the main query and the found related data tables and their relationships, an extended SQL statement containing a JOIN operation is generated. This extended query statement aims to obtain more complete information that better matches the user's deeper intent.

[0037] First, execute the main query statement and obtain the corresponding execution result; analyze the execution result to determine the target data table and key related fields; determine whether the query intent requires related expansion, and if so, use the target data table as the starting node to filter high-value related data tables in the database relationship graph; finally, combine the main query result with the metadata of the related data tables to generate an extended query statement.

[0038] For example, after the main query is executed, Zhang Wei's user ID is 1001. The target data table corresponding to this result is the users table. If the query intent requires association expansion, the system will start from the users table, re-traverse the database relationship graph, and perform graph traversal search to find other high-value data tables related to the users table. For example, it may find that the orders table has a strong association with the users table. Then, combining the execution result of the main query and the found related data tables and their relationships, it generates an expanded SQL statement containing a JOIN operation, such as "SELECT u.username, o.order_id, o.order_amount FROM users JOIN orders so ON u.id=o.buyer_id WHERE u.id=1001". This statement is a multi-table join query used to retrieve the order information of a specific user (id=1001) from the users and orders tables.

[0039] In one feasible implementation, during the extended query statement generation process, LLM optimizes the SQL statement structure in conjunction with the database's syntax specifications to avoid syntax errors. At the same time, it selects an appropriate join method based on the type of association (such as one-to-one or many-to-many), such as INNERJOIN or LEFTJOIN.

[0040] In one feasible implementation, extended queries support cross-schema queries and recursive queries. When the target data table and the related data table belong to different schemas, a schema identifier is automatically added to the extended query statement. When the query intent involves hierarchical data, the corresponding extended query statement is generated through recursive query logic to meet the needs of complex hierarchical data queries.

[0041] Step S40: Execute the extended query statement to obtain the query results corresponding to the natural language query request.

[0042] The system can load and execute extended query statements through a streaming execution engine; during execution, the query results are processed in real time, including data fusion, deduplication, and sorting; if the query result data volume is large, the amount of data returned is limited according to preset rules, and finally the processed structured query results are output.

[0043] For example, after executing the extended query, the user information in the users table and the order information in the orders table are merged, deduplicated, and sorted by order creation time, returning Zhang Wei's three order details, including fields such as username, order number, order amount, and creation time.

[0044] Therefore, in this embodiment, firstly, semantic understanding of natural language is performed to determine the user's query intent and specific business entities. Based on this, a pre-defined database relationship graph is used to generate the main query statement, enabling the database management system to automatically discover and utilize various inter-table relationships in the database, including implicit associations. Then, based on the actual execution result of the main query statement and the relationship graph, extended query statements are dynamically generated. This allows the system to start with the determined entities and data and explore the optimal association path in the relationship graph in a directional manner, avoiding missing associations or path errors in complex multi-table query scenarios. Finally, by executing the optimized extended query, it is ensured that the user's complex natural language intent can be efficiently and accurately converted into database operations and returned results, thereby improving the accuracy of database queries.

[0045] In one feasible embodiment, steps A10 to A40 may be included before step S20: Step A10: Obtain metadata information for each data table in the target database; It should be noted that metadata information refers to data describing the data tables, specifically including the table name of each data table, the field names and data types of all fields, which fields are defined as primary keys or foreign keys, which indexes are created, and comments on the fields and tables, etc.

[0046] The system obtains this metadata information comprehensively by connecting to the target database and querying its system directory.

[0047] In one feasible implementation, metadata acquisition supports multi-schema databases, meaning that for complex databases containing multiple schemas, the system will scan the metadata of the data tables under each schema separately.

[0048] Step A20: Calculate the importance score of each data table based on metadata information, and divide each data table into layers according to the importance score; It should be noted that the importance score is a quantitative indicator calculated based on the business value and data characteristics of the data table, used to distinguish the priority of the data table; the hierarchical division is to adopt differentiated relationship discovery strategies for data tables of different importance, thereby reducing the overall time complexity of relationship discovery.

[0049] First, weights are assigned based on key dimensions in the metadata information, such as data volume, number of fields, number of foreign keys, number of indexes, and completeness of comments. The weight value of each dimension is calculated, and then the importance score of each data table is obtained by weighted summation. Finally, the data tables are divided into core layer, important layer, general layer, and secondary layer according to the importance score, and corresponding batch processing size and processing strategy are set for different layers.

[0050] For example, the importance score can be calculated as follows: (Data volume weight × 0.4) + (Field number weight × 0.2) + (Foreign key number weight × 0.2) + (Index number weight × 0.1) + (Comment completeness weight × 0.1); where: Data volume weight = min(log10(number of table rows) / 6.0, 1.0); Field number weight = min(number of fields / 50, 1.0); Foreign key number weight = min((number of primary keys + number of foreign keys) / 10, 1.0); Index number weight = min(index number / 20, 1.0); Comment completeness weight = number of fields with comments / total number of fields; Data tables with an importance score ≥ 0.8 are assigned to the core layer, data tables with an importance score ≤ 0.6 and < 0.8 are assigned to the important layer, data tables with an importance score ≤ 0.4 and < 0.6 are assigned to the general layer, and data tables with an importance score < 0.4 are assigned to the minor layer. Corresponding batch sizes and processing strategies are set for different layers.

[0051] Step A30: Based on the results of the hierarchical partitioning, determine the relationships between the data tables according to the preset relationship discovery strategy. The relationship discovery strategy includes foreign key constraint analysis strategy, LLM semantic analysis strategy and field similarity calculation strategy. It should be noted that the relationship refers to the logical correspondence between data tables established through fields, including explicit relationships (such as relationships defined by foreign key constraints) and implicit relationships (such as relationships with the same semantic field but no foreign key constraints). The foreign key constraint analysis strategy directly reads the physical foreign keys defined in the database, which has the highest confidence level. The LLM semantic analysis strategy refers to the system selecting the field names, comments, and sample data of tables that do not have foreign key definitions but may have business relationships, and submitting them to the large language model for analysis. The large language model, based on its semantic understanding ability, determines whether the fields of different tables are semantically matched or related, and outputs a confidence score. The field similarity calculation strategy discovers potential relationships by comparing the string similarity of field names. The three strategies can be executed in parallel to discover data table relationships, including explicit foreign keys and implicit business logic.

[0052] First, based on the results of the hierarchical partitioning, starting from the core layer, the data tables are processed in parallel in batches according to the hierarchy; simultaneously, foreign key constraint analysis strategy, LLM semantic analysis strategy, and field similarity calculation strategy are executed to identify the relationships between data tables; a corresponding confidence level is set for the relationships identified by each strategy; finally, the relationships identified by the three strategies are initially merged, and the source strategy and confidence level of each relationship are recorded.

[0053] In one feasible implementation, the relationship discovery strategy also includes a manual field association identification strategy, which allows users to manually input field association pairs through the interface, and the system directly establishes the corresponding association relationship to meet the user's need for rapid configuration of known implicit relationships.

[0054] In one feasible implementation, the field similarity calculation strategy specifically includes edit distance similarity calculation and word segmentation similarity calculation. A comprehensive similarity score is obtained through the two calculation methods, which is used to help verify the association relationship identified by the LLM semantic analysis strategy and further improve the accuracy of implicit relationship discovery.

[0055] Step A40: Verify and optimize each relationship, and construct a database relationship graph based on the verified and optimized relationships.

[0056] Relationship validation and optimization are used to filter out spurious and duplicate associations, improving the reliability of the database relationship graph. Specifically, the initially determined relationships are first validated using SQL and data validation. If validation fails, information on the failed table pairs is collected, and enhanced context is used for a maximum of two retries. If the retry is successful, the confidence of the relationship is reduced; if the retry fails, the relationship is removed. For the validated relationships, deduplication is performed, and the relationships with the highest confidence are retained by grouping them by table pairs. Finally, a graph structure database tool is used to construct the database relationship graph, with data tables as nodes and relationships as edges, storing relationship confidence and field mapping information, and supporting incremental updates of the graph.

[0057] In one feasible implementation, the database relationship graph uses the NetworkX library to construct the graph structure. This library supports functions such as shortest path lookup and relational table query, which can quickly respond to the graph retrieval needs in the subsequent query planning process. At the same time, the graph incremental update triggering conditions include changes in data table structure, updates to field comments, and the addition of new relations. During the update, only the changed data tables and relations are processed, without the need for a full reconstruction of the graph, thus improving update efficiency.

[0058] Based on the first embodiment of this application, in the second embodiment of this application, the content that is the same as or similar to that in the first embodiment described above can be referred to the above description and will not be repeated hereafter. Based on this, step S20 may include steps S201~S202: Step S201: Based on the business entity and query intent, select the core data table from the preset database relationship graph; It should be noted that the purpose of filtering core data tables is to quickly locate a few tables that are highly relevant to the query from the massive amount of data tables in the database, avoiding the problem of excessive token (the basic unit of text processing) consumption and low query efficiency caused by inputting the full schema into the LLM.

[0059] Extract semantic mapping information and query intent keywords corresponding to business entities, traverse the preset database relationship graph, and obtain node information of all data tables; calculate the semantic matching degree, business relevance, and relationship graph connectivity of each data table and the query; finally, sort the results based on the calculation results, select the core data tables that are highly relevant to the query, and filter out irrelevant data tables.

[0060] In one feasible implementation, the core data table filtering process supports user intervention. Users can manually add or remove data tables through a preset user interface to meet query needs in special scenarios and improve the system's flexibility.

[0061] Step S202: Based on the core data table and its relationships in the database relation graph, a main query statement is generated using a preset query strategy.

[0062] It should be noted that the preset query strategies may include exact matching, fuzzy matching, range query, and alternative table query. These strategies are designed to address the ambiguity that user queries may contain. For example, the exact matching strategy will generate a condition such as WHEREname = 'Zhang Wei' for a specific entity; the fuzzy matching strategy will generate a fuzzy condition such as WHEREnameLIKE '%Zhang%'; and the range query strategy can be used to handle queries involving time or numerical ranges.

[0063] Based on the parsed intent, the system selects one or more query strategies and combines the field information of the core data table, primary key and foreign key information, and the association logic in the relational graph to assemble one or more complete main query statements.

[0064] Thus, by filtering the core data table through multi-dimensional matching, the amount of input data for LLM is reduced, and token consumption is reduced; the main query statement is generated in parallel based on the association relationship of the database relationship graph and multiple query strategies, which solves the problem of low hit rate of traditional single query statements and improves the query success rate, especially suitable for accurate data positioning in complex query scenarios.

[0065] In one feasible embodiment, steps B10 to B30 may be included before step S30: Step B10: Execute the main query statement; First, all generated main query statements are submitted to the query execution unit of the streaming execution engine. The query execution unit allocates an independent execution thread to each main query statement and executes all main query statements in parallel. The execution status of each main query statement is monitored in real time. If any main query statement is executed successfully and returns non-empty data, the execution result is immediately locked, and the execution of other unfinished main query statements is terminated.

[0066] Step B20: If the main query statement is executed successfully, the execution result of the main query statement is obtained; Retrieves the returned data of the successfully executed main query statement, and can perform preliminary processing on the returned data, such as filtering null records, removing duplicate data, sorting by primary key or time field, etc., and saves the processed data as the execution result of the main query statement.

[0067] In one feasible implementation, if multiple main query statements are executed successfully, the system will select the optimal execution result as the execution result of the main query statement based on a comprehensive score of the statement's confidence level, the amount of returned data, and data relevance.

[0068] Step B30: If the main query statement fails to execute, the main query statement is regenerated based on the feedback information of the execution failure.

[0069] It should be noted that "main query execution failure" includes situations such as syntax errors, no matching data, and database connection errors. The retry strategy is different for different failure types, and the core goal is to improve the query success rate by intelligently adjusting the query conditions.

[0070] First, collect all failure feedback information for the main query statements, categorize and analyze the reasons for failure, such as syntax errors, no matching data, and database connection errors. Different retry strategies apply to different failure types. Determine if the number of retries is less than 2. If the maximum number of retries has not been reached, construct a failure context containing the failure reason, the original query conditions, and core data table information. Input the failure context into the LLM, requesting the LLM to adjust the query strategy and regenerate alternative main query statements. If the maximum number of retries has been reached and execution still fails, return a "no data" message and suggest that the user adjust the query conditions.

[0071] In one feasible embodiment, step S30 may include steps S301 to S303: Step S301: Determine the target data table corresponding to the execution result of the main query statement; After the main query statement is executed successfully, the system needs to determine which database table(s) the result data specifically comes from. For example, if the main query statement is a SELECT statement... If you use the query FROM usersWHERE username='Zhang Wei', then the target data table corresponding to the execution result is the users table. This information can usually be obtained directly from the FROM clause of the main query statement.

[0072] Step S302: Starting with the target data table as the starting node, perform a graph traversal search in the database relationship graph to determine the associated data table; Once the target data table is determined, the database relationship graph is explored outwards along the edges connected in the graph, starting from the target data table as the starting node. There are various algorithms for graph traversal search, the purpose of which is to systematically access other nodes that are adjacent to or indirectly connected to the starting node, i.e., other data tables.

[0073] For example, the target data table is the users table, and the query intent requires association expansion. The adjacent node orders table is explored in the relationship graph, and the orders table is selected as the associated data table.

[0074] In one feasible implementation, graph algorithms (such as Dijkstra's algorithm) can be used to find the optimal query path during the graph traversal search process. By calculating the path weights between nodes, the associated nodes with the best path weights are selected first, thereby further improving the execution efficiency of extended queries.

[0075] In one feasible embodiment, step S302 may include steps S3021 to S3024: Step S3021: Starting with the target data table as the starting node, perform a graph traversal search in the database relation graph using the breadth-first search algorithm; It's important to note that the breadth-first search algorithm prioritizes exploring all directly adjacent nodes of the starting node, then explores the adjacent nodes of those adjacent nodes, and so on, expanding outwards layer by layer. In the context of a database relational graph, this means the system first identifies all tables directly related to the target table, and then looks for tables directly connected to those related tables, ensuring that no important nodes associated with the target table are overlooked.

[0076] First, add the nodes of the target data table to the search queue and mark them as visited; initialize the result set to store the explored neighboring nodes; retrieve the first node from the search queue, obtain all the associations of that node in the database relationship graph, and find the corresponding neighboring nodes; determine whether the neighboring node has been visited, and if not, add it to the search queue and store the neighboring node and its association information in the result set; repeat the above steps until the search queue is empty or the preset depth has been explored; finally, output all neighboring nodes in the result set.

[0077] Step S3022: During the graph traversal search, the exploration priority of adjacent nodes is determined based on the confidence of the connecting edges between the starting node and adjacent nodes. It should be noted that the confidence level of the connecting edge is the reliability of the association determined in the relationship discovery stage. It is a core indicator for judging the importance of adjacent nodes. The higher the confidence level, the more reliable the association is and the stronger its relevance to the query intent.

[0078] During the graph traversal search, for each neighboring node, the confidence of the edge connecting it to the starting node is extracted; combined with the importance score of the neighboring node itself, the exploration priority score is calculated, for example, priority score = edge confidence × 0.7 + node importance score × 0.3; all neighboring nodes are sorted from high to low according to their priority scores, with higher scores indicating higher exploration priority; a priority queue is used to store neighboring nodes, and they are explored sequentially according to their priority scores.

[0079] Step S3023: Select at least one node from the neighboring nodes as the associated node according to the exploration priority; Due to limited resources, the system will not expand all associations indefinitely. Instead, it will select the top-ranked nodes from the explored nodes based on priority scores and identify them as the association nodes to be associated in this query.

[0080] Step S3024: Determine the data table corresponding to the associated node as the associated data table.

[0081] For each selected associated node, extract the name of the data table and its schema stored in the node; query the metadata archive to verify whether the data table exists and whether the table structure is valid; if the data table is valid, identify it as an associated data table and record its table structure information, field comments, and index information; if the data table is invalid, skip the node and select associated nodes from the remaining adjacent nodes according to priority.

[0082] Therefore, in this embodiment, the breadth-first search algorithm ensures the comprehensiveness of the graph traversal search and avoids missing important related nodes; the priority ranking based on the confidence of the connecting edges and the importance score of the nodes enables the accurate screening of high-value related nodes; the validity verification of the related data tables ensures the feasibility of subsequent extended queries and avoids query failures due to invalid data tables; and by reasonably limiting the number of related data tables, the comprehensiveness of the query results and the execution efficiency are balanced.

[0083] Step S303: Generate an extended query statement based on the execution result of the main query statement and the associated data table.

[0084] The system first extracts core data fields (such as user ID) from the main query execution results, and simultaneously obtains the table structure information of the related data table and the field mapping relationship with the target data table. Then, it inputs the target data table information, related data table information, core data fields, and field mapping relationships into the LLM to generate an extended query statement containing table join logic. Finally, it automatically verifies the syntax correctness of the extended query statement. If there are syntax errors, it feeds them back to the LLM for correction and adds query restrictions and sorting conditions.

[0085] For example, extract the core data field "user_id=1001" from the main query result, obtain the structure information of the orders table and the field mapping relationship "users.id=orders.buyer_id", and generate the extended query statement "SELECT u.username,o.order_id,o.order_amount FROM usersu JOIN orderso ON u.id=o.buyer_id WHERE u.id=1001".

[0086] In one feasible implementation, when generating extended query statements, database performance optimization rules (such as prioritizing indexed fields as join conditions) are incorporated to improve the execution efficiency of extended query statements.

[0087] In one feasible embodiment, step S40 may include steps S401 to S403: Step S401: Execute the extended query statement in a streaming manner; It should be noted that streaming mode refers to returning results while the query statement is being executed, rather than waiting for all the data to be processed before returning all the results at once. This can significantly improve the user's real-time interactive experience and is especially suitable for query scenarios with large amounts of data.

[0088] First, the extended query statement is submitted to the real-time query execution unit of the streaming execution engine. The real-time query execution unit parses the query statement, generates an execution plan, and executes the query in batches according to the data shards. After each data shard is executed, the query results of that shard are immediately preliminarily processed (duplicated and sorted) and returned to the user or intelligent dialogue agent in real time. While returning the results, the query progress is updated in real time. When all data shards have been executed, the fully processed query results are returned and the query is marked as complete.

[0089] For example, the extended query statement involves 1000 order data entries, divided into 5 shards of 200 entries each. After the first shard is executed, 200 order data entries are returned immediately, and the progress is updated to "200 entries returned, approximately 1000 entries in total", until all 5 shards are executed.

[0090] In one feasible implementation, the streaming execution process allows users to pause, resume, or terminate queries. If a user pauses a query, the system saves the current execution progress, which can be resumed later, improving the flexibility of user interaction.

[0091] In one feasible implementation, the streaming execution engine includes a query limiting mechanism, which returns a maximum of 500 records by default. If the user needs to obtain more data, the limit can be adjusted or pagination can be used through the interface to avoid response delays caused by excessive data volume.

[0092] Step S402: If an error occurs during the execution of the extended query statement, an error handling process including a retry mechanism or a path switching mechanism is triggered. It should be noted that errors that may occur during execution include database connection interruption, non-existent fields, lock conflicts, timeouts, etc. Different error types correspond to different error handling mechanisms to ensure the continuity and stability of queries.

[0093] The system monitors the execution status of extended query statements in real time. If an error is detected, execution is immediately paused and the error type and information are recorded. Based on the error type, the corresponding error handling process is triggered: if it is a recoverable error, a retry mechanism is triggered, employing an exponential backoff strategy to retrace up to 3 times. After a successful retry, the query continues to execute; if it is an unrecoverable error, a path switching mechanism is triggered, re-selecting related data tables based on the database relationship graph, generating a new extended query statement, and executing it; if all error handling mechanisms fail, an error log is recorded, and an error message is returned to the user.

[0094] In step S403, if no error occurs, partial query results are returned in real time, and the query results corresponding to the natural language query request are obtained after the query is completed.

[0095] If no errors occur during the execution of the extended query statement, partial query results are returned in real time according to data shards. The results of each shard include data content, shard number, and estimated amount of remaining data. While returning partial results, real-time statistical analysis is performed on the returned data and displayed to the user. After the full data is executed, all shard results are integrated, and finally, the integrated structured data is used as the final query result and fed back to the user. Users can also export or generate intelligent reports.

[0096] Therefore, in this embodiment, the first return time of query results is significantly shortened by using a streaming execution method, which improves the real-time interactive experience for users; the error handling process, which includes a retry mechanism and a path switching mechanism, solves the problem of unrecoverable errors in the traditional query execution process, and enhances the stability and fault tolerance of the system; the combination of real-time return of partial results and full data integration ensures both the user's rapid perception and the accuracy and completeness of the final query results.

[0097] In one feasible implementation, a streaming execution engine can monitor and record the access frequency of each data table in real time, thereby dynamically identifying business hotspot tables, such as the order table that is frequently accessed during promotions. Based on this monitoring data, the system will proactively preload some or all of the data from the identified high-frequency access core tables into the server memory cache. When subsequent query requests need to access these cached tables, the execution engine can directly read the data from memory, reducing the response time of common queries.

[0098] In one feasible embodiment, steps S50-S60 may be included after step S40: Step S50: Input the query results into the preset intelligent dialogue agent so that the intelligent dialogue agent can analyze the query results and obtain the analysis conclusions in natural language form. It should be noted that the intelligent dialogue agent is an intelligent data assistant built on the LangChain framework (a development framework for developing applications based on large language models). It has capabilities such as tool integration, context management, and intent recognition, and can convert structured query results into natural language analysis conclusions that are easy for users to understand.

[0099] First, the final query results and the user's original natural language query request are input into the intelligent dialogue agent. The intelligent dialogue agent records the user's dialogue history and query context, and reconfirms the user's core query needs. Based on the query intent, the agent automatically selects the corresponding data analysis tool and performs in-depth analysis of the query results. Finally, the agent converts the data analysis results into analytical conclusions in natural language form and supports multi-round continuous dialogue to answer the user's subsequent questions.

[0100] In one feasible implementation, the intelligent dialogue agent also supports user-defined analysis dimensions. Users can specify the indicators to be analyzed through natural language, and the agent will automatically adjust the analysis logic and return the corresponding analysis conclusions.

[0101] Step S60: Output the visualized query results based on the analysis conclusions.

[0102] The intelligent dialogue agent transmits the analysis conclusions and structured query results to the visualization module. The visualization module selects an appropriate visualization format based on the data type and analysis conclusions, and outputs visualization interpolation results. For example, bar charts and pie charts are used for numerical statistical data, line charts are used for trend data, structured tables are used for detailed data lists, and relationship graphs are used for relational data visualization.

[0103] Thus, the intelligent dialogue agent enables in-depth analysis and natural language interpretation of query results, reducing users' reliance on professional data analysis knowledge and allowing non-professional users to quickly understand the query results.

[0104] For example, in order to help understand the implementation process of the database query method obtained by combining this embodiment with the above embodiment one, the following will be described in detail with the example of an e-commerce sales database. The e-commerce sales database contains data tables such as users (user table), orders (order table), products (product table) and order_details (order details table). The natural language query request entered by the user is "query the order information of user Zhang Wei".

[0105] Before the system can perform intelligent queries, a database relationship graph needs to be built in advance. First, such as Figure 2 As shown, the system performs a full schema scan of the target database, obtaining metadata for all tables, including table names, fields, primary and foreign keys, etc., and then calculates table importance scores. The scores are based on multiple dimensions such as data volume, number of fields, and number of foreign keys, and a comprehensive score is derived according to a preset formula. Subsequently, the system stratifies the tables according to their scores. For example, the highest-scoring users and orders tables are placed in the "core layer," while the products and order_details tables may be placed in the "important layer" or "general layer," and some log or temporary tables are placed in the "secondary layer." After stratification, the system activates a hybrid relationship discovery engine, the structure of which is shown below. Figure 3As shown, this hybrid relation discovery engine executes multiple relation discovery strategies in parallel according to hierarchical batches (e.g., the core layer processes 3 tables per batch, and the secondary layer processes 12 tables per batch). This hybrid relation discovery engine includes an LLM semantic analysis unit, a foreign key constraint analysis unit, a field similarity calculation unit, and a relation verification unit. The foreign key constraint analysis unit directly reads the physical foreign keys already defined in the database. For example, it discovers that the `buyer_id` field in the `orders` table is a foreign key to the `user_id` field in the `users` table, thus establishing a highly confident association. The LLM semantic analysis unit constructs a context containing table names, field names, and their annotations. The generation of prompt words calls the Large Language Model API (Application Programming Interface) to analyze the semantic similarity between fields. For example, even without foreign key definitions, LLM can infer that the `order_ref` field in the `order_details` table is semantically equivalent to the `order_id` field in the `orders` table by analyzing field names and business logic, thus generating a candidate semantic association and assigning it a confidence score. The field similarity calculation unit uses methods such as calculating the edit distance of field names and word segmentation similarity as auxiliary discovery methods. All discovered relationships, whether from foreign keys, LLM, or similarity calculation, enter the relationship verification unit for relationship verification and optimization. Finally, all verified and optimized relationships are used to construct a database relationship graph based on the NetworkX graph library (a core library for creating, manipulating, and analyzing complex networks). In this graph, data tables are used as nodes, and relationships are used as edges with confidence weights.

[0106] Once the system receives the request to "query user Zhang Wei's order information" and completes intent parsing, it enters a two-stage query planning and execution process, such as... Figure 4As shown, in the first stage, the system first performs enhanced table filtering, that is, combining the parsed user entities and order intentions, it quickly filters out the most relevant small number of core data tables from the pre-built relationship graph, such as precisely locating the users and orders tables, to reduce data processing complexity and the cost of calling large models. Then, based on the filtered core tables and their known relationships in the graph, the system uses a multi-master query strategy to generate multiple SQL statements in parallel, i.e., the master query language. Specifically, the query strategy may include exact match SQL, fuzzy / range SQL, and alternative table SQL. The main query statement generated by the query strategy is sent to the parallel execution engine for simultaneous execution. If the execution of a main query statement is successful and returns data, such as finding the user "Zhang Wei" with a user_id of 1001, the system locks this result and determines that the main query is successful, proceeding to the next stage. If none of the main queries return data, the system will trigger an intelligent retry mechanism, combining the feedback information of no results with the original query, reconstructing the prompt words to request the large language model to adjust the strategy, such as relaxing the matching conditions or checking other tables, and generating a new main query statement for retry, repeating up to two times to improve the hit rate.

[0107] Once the main query succeeds and yields a concrete execution result such as user_id=1001, and the query intent is identified as requiring related information, the system automatically enters the second stage, namely the extended join query. In this stage, the system first uses the data table hit by the main query result (i.e., the users table) as the starting node and performs a breadth-first search in the database relational graph. The search process utilizes a priority queue, determining the priority of exploring adjacent nodes based on the confidence level of edges in the graph, thereby efficiently discovering high-value join tables. In this example, the graph explicitly indicates that the users table is associated with the orders table through a high-confidence edge. Subsequently, the system submits the concrete execution result of the main query (user_id=1001) along with the found join table (orders) and its relationship (users.id = orders.user_id) to the large language model, which then generates an extended JOIN query statement, such as: SELECT u. , o. The extended query `FROM usersuJOINordersoONu.id = o.user_idWHERE u.id= 1001` retrieves all order details for that user.

[0108] Next, the streaming execution engine is responsible for executing this expanded query statement. The architecture of this streaming execution engine is as follows: Figure 5As shown, the streaming execution engine includes a result analysis unit, a real-time query execution unit, and an error recovery unit. During execution, the real-time query execution unit is responsible for retrieving data from the database in batches and returning it immediately; the result analysis unit synchronously performs real-time statistics and summaries on the returned data; and the error recovery unit continuously monitors the status. If a temporary error is encountered, a retry based on an exponential backoff strategy is triggered. If it is determined that the query path is incorrect, an alternative query path is generated using the relational graph, thereby ensuring the high availability of the query task.

[0109] Finally, once the complete query results are generated, the system can analyze them through an intelligent dialogue agent. This agent includes a context management unit, a dialogue connection unit, and a tool integration unit. The intelligent dialogue agent receives the query results, performs statistical analysis and trend insights on the data using its integrated analysis tools, and automatically generates natural language text summaries containing key conclusions and visual chart suggestions. Through the context management unit, it engages in coherent multi-turn dialogues with the user, ultimately presenting a visualized query results report that integrates data, analysis, and insights. This completes the end-to-end intelligent service, transforming a simple natural language query into a comprehensive data insight report.

[0110] It should be noted that the above examples are only for understanding this application and do not constitute a limitation on the database query method of this application. Any simple modifications based on this technical concept are within the protection scope of this application.

[0111] This application provides an electronic device, which includes: at least one processor; and a memory communicatively connected to the at least one processor; wherein the memory stores instructions executable by the at least one processor, which are executed by the at least one processor to enable the at least one processor to perform the database query method in the first embodiment described above.

[0112] The following is for reference. Figure 6 The diagram illustrates a structural schematic of an electronic device suitable for implementing embodiments of this application. The electronic devices in these embodiments may include, but are not limited to, mobile terminals such as laptops, digital broadcast receivers, PDAs (Personal Digital Assistants), PADs (Portable Application Description), PMPs (Portable Media Players), in-vehicle terminals (e.g., in-vehicle navigation terminals), and fixed terminals such as digital TVs and desktop computers. Figure 6 The electronic device shown is merely an example and should not impose any limitation on the functionality and scope of use of the embodiments of this application.

[0113] like Figure 6 As shown, the electronic device may include a processing unit 1001 (e.g., a central processing unit, a graphics processing unit, etc.), which can perform various appropriate actions and processes according to a program stored in a read-only memory 1002 or a program loaded from a storage device 1003 into a random access memory 1004. The random access memory 1004 also stores various programs and data required for the operation of the electronic device. The processing unit 1001, the read-only memory 1002, and the random access memory 1004 are interconnected via a bus 1005. An input / output interface 1006 is also connected to the bus. Typically, the following systems can be connected to the input / output interface 1006: input devices 1007 including, for example, touchscreens, touchpads, keyboards, mice, image sensors, microphones, accelerometers, gyroscopes, etc.; output devices 1008 including, for example, liquid crystal displays (LCDs), speakers, vibrators, etc.; storage devices 1003 including, for example, magnetic tapes, hard disks, etc.; and communication devices 1009. The communication device 1009 allows the electronic device to exchange data with other devices wirelessly or via wired communication. Although the diagrams show electronic devices with various systems, it should be understood that it is not required to implement or have all of the systems shown. More or fewer systems may be implemented alternatively.

[0114] Specifically, according to the embodiments disclosed in this application, the processes described above with reference to the flowcharts can be implemented as computer software programs. For example, embodiments disclosed in this application include a computer program product comprising a computer program carried on a computer-readable medium, the computer program containing program code for performing the methods shown in the flowcharts. In such embodiments, the computer program can be downloaded and installed from a network via a communication device, or installed from storage device 1003, or installed from read-only memory 1002. When the computer program is executed by processing device 1001, it performs the functions defined in the methods of the embodiments disclosed in this application.

[0115] The electronic device provided in this application, employing the database query method described in the above embodiments, can improve the accuracy of database queries in multi-table join scenarios. Compared with the prior art, the beneficial effects of the electronic device provided in this application are the same as those of the database query method provided in the above embodiments, and other technical features of the electronic device are the same as those disclosed in the database query method of the previous embodiment, and will not be repeated here.

[0116] It should be understood that the various parts disclosed in the embodiments of this application can be implemented using hardware, software, firmware, or a combination thereof. In the description of the above embodiments, specific features, structures, materials, or characteristics can be combined in any suitable manner in one or more embodiments or examples.

[0117] The above are merely specific embodiments of this application, but the scope of protection of this application is not limited thereto. Any variations or substitutions that can be easily conceived by those skilled in the art within the scope of the technology disclosed in this application should be included within the scope of protection of this application. Therefore, the scope of protection of this application should be determined by the scope of the claims.

[0118] This application provides a computer-readable storage medium having computer-readable program instructions (i.e., a computer program) stored thereon, which are used to execute the database query method in the above embodiments.

[0119] The computer-readable storage medium provided in this application embodiment may be, for example, a USB flash drive, but is not limited to, electrical, magnetic, optical, electromagnetic, infrared, or semiconductor systems or devices, or any combination thereof. More specific examples of computer-readable storage media may include, but are not limited to: electrical connections having one or more wires, portable computer disks, hard disks, random access memory (RAM), read-only memory (ROM), erasable programmable read-only memory (EPROM or flash memory), optical fibers, portable compact disk read-only memory (CD-ROM), optical storage devices, magnetic storage devices, or any suitable combination thereof. In this embodiment, the computer-readable storage medium may be any tangible medium containing or storing a program that can be used by or in conjunction with an instruction execution system or device. The program code contained on the computer-readable storage medium may be transmitted using any suitable medium, including but not limited to: wires, optical cables, RF (Radio Frequency), etc., or any suitable combination thereof.

[0120] The aforementioned computer-readable storage medium may be included in an electronic device or may exist independently without being assembled into an electronic device.

[0121] The aforementioned computer-readable storage medium carries one or more programs. When the aforementioned one or more programs are executed by an electronic device, the electronic device: responds to a received user natural language query request by performing entity recognition and semantic understanding on the natural language query request to obtain the business entity to be queried and the query intent; generates a main query statement based on the business entity, the query intent, and a preset database relationship graph; generates an extended query statement based on the execution result of the main query statement and the database relationship graph; and executes the extended query statement to obtain the query result corresponding to the natural language query request.

[0122] Computer program code for performing the operations of the embodiments of this application can be written in one or more programming languages ​​or a combination thereof. These programming languages ​​include object-oriented programming languages—such as Java, Smalltalk, and C++—and conventional procedural programming languages—such as the "C" language or similar programming languages. The program code can be executed entirely on the user's computer, partially on the user's computer, as a standalone software package, partially on the user's computer and partially on a remote computer, or entirely on a remote computer or server. In cases involving remote computers, the remote computer can be connected to the user's computer via any type of network—including a local area network (LAN) or a wide area network (WAN)—or can be connected to an external computer (e.g., via the Internet using an Internet service provider).

[0123] The flowcharts and block diagrams in the accompanying drawings illustrate the architecture, functionality, and operation of possible implementations of systems, methods, and computer program products according to various embodiments of this application. In this regard, each block in a flowchart or block diagram may represent a module, segment, or portion of code containing one or more executable instructions for implementing a specified logical function. It should also be noted that in some alternative implementations, the functions indicated in the blocks may occur in a different order than those indicated in the drawings. For example, two consecutively indicated blocks may actually be executed substantially in parallel, and they may sometimes be executed in reverse order, depending on the functions involved. It should also be noted that each block in the block diagrams and / or flowcharts, and combinations of blocks in the block diagrams and / or flowcharts, can be implemented using a dedicated hardware-based system that performs the specified function or operation, or using a combination of dedicated hardware and computer instructions.

[0124] The modules described in the embodiments of this application can be implemented in software or hardware. The names of the modules do not necessarily limit the functionality of the unit itself.

[0125] The readable storage medium provided in this application embodiment is a computer-readable storage medium that stores computer-readable program instructions (i.e., a computer program) for executing the above-described database query method, which can improve the accuracy of database queries in multi-table join scenarios. Compared with the prior art, the beneficial effects of the computer-readable storage medium provided in this application embodiment are the same as the beneficial effects of the database query method provided in the above embodiments, and will not be repeated here.

[0126] The above are only some embodiments of this application and do not limit the patent scope of this application. All equivalent structural transformations made under the technical concept of this application and using the contents of the specification and drawings of this application, or direct / indirect applications in other related technical fields, are included in the patent protection scope of this application.

Claims

1. A database query method, characterized in that, The database query method includes: In response to a received user natural language query request, entity recognition and semantic understanding are performed on the natural language query request to obtain the business entity to be queried and the query intent; The main query statement is generated based on the business entity, the query intent, and the preset database relationship graph; An extended query statement is generated based on the execution result of the main query statement and the database relationship graph; Execute the extended query statement to obtain the query results corresponding to the natural language query request.

2. The database query method as described in claim 1, characterized in that, Before the step of generating the main query statement based on the business entity, the query intent, and the preset database relationship graph, the method further includes: Obtain metadata information for each table in the target database; The importance score of each data table is calculated based on the metadata information, and the data tables are then divided into layers according to the importance score. Based on the results of the hierarchical division, the association between each data table is determined based on a preset relationship discovery strategy, wherein the relationship discovery strategy includes a foreign key constraint analysis strategy, an LLM semantic analysis strategy, and a field similarity calculation strategy. The relationships described are verified and optimized, and a database relationship graph is constructed based on the verified and optimized relationships.

3. The database query method as described in claim 1, characterized in that, The step of generating the main query statement based on the business entity, the query intent, and the preset database relationship graph includes: Based on the business entity and the query intent, core data tables are selected from a preset database relationship graph; Based on the core data table and its associations in the database relationship graph, a preset query strategy is used to generate the main query statement.

4. The database query method as described in claim 1, characterized in that, Before the step of generating an extended query statement based on the execution result of the main query statement and the database relationship graph, the method further includes: Execute the main query statement; If the main query statement is executed successfully, the execution result of the main query statement is obtained; If the main query statement fails to execute, the main query statement is regenerated based on the failure feedback information.

5. The database query method as described in claim 1, characterized in that, The step of generating an extended query statement based on the execution result of the main query statement and the database relationship graph includes: Determine the target data table corresponding to the execution result of the main query statement; Starting with the target data table as the starting node, a graph traversal search is performed in the database relationship graph to determine the associated data table; Based on the execution result of the main query statement and the associated data table, an extended query statement is generated.

6. The database query method as described in claim 5, characterized in that, The step of using the target data table as the starting node and performing a graph traversal search in the database relationship graph to determine the associated data table includes: Starting with the target data table as the starting node, a breadth-first search algorithm is used to perform a graph traversal search in the database relation graph; During the graph traversal search, the exploration priority of the adjacent nodes is determined based on the confidence of the connecting edges between the starting node and the adjacent nodes. Based on the exploration priority, at least one node is selected as an associated node from the adjacent nodes; The data table corresponding to the associated node is determined as the associated data table.

7. The database query method as described in claim 1, characterized in that, The step of executing the extended query statement to obtain the query result corresponding to the natural language query request includes: The extended query statement is executed in a streaming manner; If an error occurs during the execution of the extended query statement, an error handling process including a retry mechanism or a path switching mechanism will be triggered. If no error occurs, partial query results are returned in real time, and the query result corresponding to the natural language query request is obtained after the query is completed.

8. The database query method as described in any one of claims 1 to 7, characterized in that, After the step of executing the extended query statement to obtain the query result corresponding to the natural language query request, the method further includes: The query results are input into a preset intelligent dialogue agent, which analyzes the query results to obtain analytical conclusions in natural language form. Based on the analysis conclusions, output visualized query results.

9. An electronic device, characterized in that, The electronic device includes: a memory, a processor, and a computer program stored in the memory and executable on the processor, the computer program being configured to implement the steps of the database query method as described in any one of claims 1 to 8.

10. A storage medium, characterized in that, The storage medium is a computer-readable storage medium, and a computer program is stored on the storage medium. When the computer program is executed by a processor, it implements the steps of the database query method as described in any one of claims 1 to 8.