Graph database self-loop dynamic pruning optimization method and device, equipment and medium

CN122946601APending Publication Date: 2026-10-20CHINA MERCHANTS BANK
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611175033.9
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-04
Publication Date
2026-10-20

AI Technical Summary

Technical Problem

[0005]本申请的主要目的在于提供一种图数据库自循环动态剪枝优化方法、装置、设备及介质,旨在解决现有技术中如何提供一套能够兼顾构图可执行性、查询准确性及优化收敛性的图数据库闭环优化方案的技术问题

Benefits of technology

[0016]本申请提出的一个或多个技术方案,至少具有以下技术效果:本申请通过获取目标图数据库的构建请求、查询请求和优化请求,以响应图数据库在构图、查图和优化阶段的不同处理需求;由于基于构建请求与自循环框架对图结构与建图语句进行迭代评估,因此在反复的客观评价与反馈中能够有效纠正生成偏差,从而输出高质量的可执行图谱;在此基础上,由于针对可执行图谱与查询请求进行查询意图解析并获取目标图谱知识,因此能够在保留关键查询语义的同时排除冗余图数据,从而有效降低大模型在生成图查询语句时的语义幻觉;进一步地,由于对优化请求所涉及的候选优化方案进行执行代价评估并获得可量化的执行代价值,进而基于该代价值对查询路径进行迭代优化,因此能够为慢查询的调整提供明确的优化基准与反馈信号,最终保证优化过程逼近最优查询路径。综上,本发明实现了从构图、查询到优化的全链路自洽闭环,有效提升了图数据库在自动化构建、自然语言查询转换及性能优化方面的整体处理能力。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure FT_1
    Figure FT_1
  • Figure FT_2
    Figure FT_2
  • Figure FT_3
    Figure FT_3
Patent Text Reader

Abstract

This application relates to the field of graph database technology, and particularly to a method, apparatus, device, and medium for self-looping dynamic pruning optimization of graph databases. This application constructs a dual-loop self-consistent evaluation framework to iteratively generate executable graphs through the graph data construction, querying, and optimization stages. In the querying process, dynamic pruning filters graph knowledge and injects it into a large model to generate graph query statements. In the optimization process, a quantitative feedback mechanism based on execution cost is constructed to improve query efficiency. This scheme, through the dual-loop evaluation framework, effectively standardizes the graph structure and the generation of graph construction statements, ensuring the executability of the construction results. Dynamic pruning significantly simplifies the input knowledge of the large model, reducing the probability of semantic illusions, thereby improving the accuracy of query transformations. The quantitative feedback mechanism of execution cost guides the adjustment of the query path through multiple iterations, ensuring the stability and convergence of the system during the optimization process.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of graph database technology, and in particular to a method, apparatus, equipment and medium for self-looping dynamic pruning optimization of graph databases. Background Technology

[0002] Graph databases, as an important carrier of data analysis, have broad application prospects, but they also suffer from a high barrier to entry. To reduce the operational difficulty, technical challenges are typically addressed in three areas: graph construction, query parsing, and performance optimization.

[0003] Existing solutions generally rely directly on general-purpose large language models, but they face many limitations. In the construction phase, the graphs generated by large models lack rule verification, resulting in poor executability. In the query phase, direct inference of query statements has low accuracy, fine-tuning training is costly, and inputting full graph knowledge can easily lead to semantic illusions. In the optimization phase, the lack of a quantitative evaluation mechanism for graph traversal features and execution costs makes it difficult to guarantee optimization results.

[0004] Therefore, how to provide a closed-loop optimization scheme for graph databases that can balance graph construction feasibility, query accuracy, and optimization convergence is a technical problem that urgently needs to be solved in this field. Summary of the Invention

[0005] The main objective of this application is to provide a method, apparatus, device, and medium for self-loop dynamic pruning optimization of graph databases, aiming to solve the technical problem of how to provide a closed-loop optimization scheme for graph databases that can take into account the executability of graph construction, the accuracy of query, and the convergence of optimization in the prior art.

[0006] To achieve the above objectives, this application provides a self-looping dynamic pruning optimization method for graph databases. This method includes the following steps: obtaining the construction request, query request, and optimization request of the target graph database; iteratively evaluating the graph structure and construction statement based on the construction request and the self-looping framework to obtain an executable graph; parsing the query intent based on the executable graph and the query request to obtain target graph knowledge; generating a graph query statement based on the target graph knowledge; evaluating the execution cost of candidate optimization schemes based on the graph query statement and the optimization request to obtain the execution cost value; and iteratively optimizing the query path based on the execution cost value to obtain the optimized query path.

[0007] Optionally, the above-mentioned iterative evaluation of the graph structure and graph construction statements based on the construction request and the self-looping framework to obtain an executable graph includes: constructing a self-looping framework consisting of an outer loop and an inner loop, wherein the inner loop includes a graph structure design agent and a graph construction statement design agent; generating a graph structure design through the graph structure design agent; generating graph construction statements through the graph construction statement design agent; evaluating the graph structure design and graph construction statements to obtain an evaluation result; if the evaluation result does not meet the preset conditions, restarting the inner loop through the outer loop; if the number of restarts reaches a preset threshold, stopping the loop to obtain an executable graph.

[0008] Optionally, the above-mentioned generation of graph structure design through a graph structure design agent includes: obtaining an objective score for the graph structure design based on its conformity with preset rules, wherein the preset rules include semantic consistency, data integrity, and connectivity analysis rules; obtaining a subjective comprehensive score by performing quality evaluation through a large model based on the quality of the graph structure design; obtaining a graph structure design score based on the objective score and the subjective comprehensive score; if the graph structure design score is less than a preset score threshold, then re-executing the graph structure design through an outer loop; if the graph structure design score is greater than the preset score threshold, then ending the loop and determining the current graph structure design as the final graph structure design.

[0009] Optionally, if the score of the above-mentioned graph structure design is less than a preset score threshold, the inner loop is restarted through the outer loop, including: obtaining the number of restarts of the inner loop from the outer loop; if the number of restarts is less than a first preset number, the preset score threshold is maintained; if the number of restarts is greater than or equal to the first preset number and less than the second preset number, the preset score threshold is reduced; if the number of restarts is greater than or equal to the second preset number, the loop is stopped and an executable graph is obtained.

[0010] Optionally, the above-mentioned parsing of query intent to obtain target graph knowledge includes: performing intent recognition and masking processing on the query request to obtain masked word segmentation, wherein the masking processing includes replacing named entities with entity types; extracting key entity words from the masked word segmentation; performing field matching between key entity words and graph knowledge to obtain a first matching result; performing similarity matching between key entity words and graph knowledge to obtain a second matching result; obtaining mandatory business fields in the query request; and pruning the graph knowledge based on the first matching result, the second matching result, and the mandatory business fields to obtain target graph knowledge.

[0011] Optionally, the above-mentioned evaluation of the execution cost of candidate optimization schemes to obtain execution cost value includes: executing candidate optimization schemes in a sandbox environment to obtain execution time, number of traversed nodes and memory usage; and calculating execution cost value based on execution time, number of traversed nodes and memory usage, as well as the corresponding weights determined based on graph data types.

[0012] Optionally, the above calculation of execution cost based on execution time, number of traversed nodes, memory usage, and corresponding weights determined based on graph data types includes: calculating the cost reduction of the current optimization scheme relative to the historical best scheme; using the cost reduction as a reward signal; inputting the current optimization strategy and reward signal into the optimization model; generating the next round of optimization scheme based on the optimization model; and stopping the iteration if the cost of the next round of optimization scheme reaches the preset convergence condition, thus obtaining the optimized query path.

[0013] Furthermore, to achieve the above objectives, this application also proposes a graph database self-looping dynamic pruning optimization device, which includes: an instruction receiving module, a graph construction module, a query module, a cost evaluation module, and an iterative optimization module. Specifically, The instruction receiving module is used to obtain the construction request, query request, and optimization request of the target graph database; The graph construction module is used to iteratively evaluate the graph structure and graph construction statements based on the construction request and the self-looping framework to obtain an executable graph. The query module is used to parse the query intent based on the executable graph and the query request to obtain the target graph knowledge, and to generate graph query statements based on the target graph knowledge. The cost evaluation module is used to evaluate the execution cost of candidate optimization solutions based on graph query statements and optimization requests, and obtain the execution cost value. The iterative optimization module is used to iteratively optimize the query path based on the execution cost, and obtain the optimized query path.

[0014] Furthermore, to achieve the above objectives, this application also proposes a graph database self-looping dynamic pruning optimization device, which includes: a memory, a processor, and a graph database self-looping dynamic pruning optimization program stored in the memory and executable on the processor. The graph database self-looping dynamic pruning optimization program is configured to implement the steps of the graph database self-looping dynamic pruning optimization method described above.

[0015] In addition, to achieve the above objectives, this application also proposes a storage medium storing a graph database self-loop dynamic pruning optimization program, which, when executed by a processor, implements the steps of the graph database self-loop dynamic pruning optimization method as described above.

[0016] The present application proposes one or more technical solutions, which have at least the following technical effects: This application responds to the different processing needs of the graph database in the graph construction, query, and optimization stages by acquiring the construction request, query request, and optimization request of the target graph database; because iterative evaluation of the graph structure and graph construction statement is performed based on the construction request and a self-loop framework, generation deviations can be effectively corrected through repeated objective evaluation and feedback, thereby outputting a high-quality executable graph; furthermore, because query intent is parsed for the executable graph and query request and target graph knowledge is obtained, redundant graph data can be eliminated while retaining key query semantics, thereby effectively reducing semantic illusions when large models generate graph query statements; further still, because the execution cost of candidate optimization schemes involved in the optimization request is evaluated and a quantifiable execution cost is obtained, and then the query path is iteratively optimized based on this cost, a clear optimization benchmark and feedback signal can be provided for adjusting slow queries, ultimately ensuring that the optimization process approaches the optimal query path. In summary, this invention achieves a self-consistent closed loop across the entire chain from graph construction and query to optimization, effectively improving the overall processing capabilities of graph databases in automated construction, natural language query conversion, and performance optimization. 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 A flowchart illustrating the graph database self-looping dynamic pruning optimization method provided in this application embodiment. Figure 1 ; Figure 2 A flowchart illustrating the graph database self-looping dynamic pruning optimization method provided in this application embodiment. Figure 2 ; Figure 3 A flowchart illustrating the graph database self-looping dynamic pruning optimization method provided in this application embodiment. Figure 3 ; Figure 4 This is a schematic diagram of the structure of the graph database self-looping dynamic pruning optimization device provided in the embodiments of this application; Figure 5 This is a schematic diagram of the structure of the graph database self-looping dynamic pruning optimization device provided in the embodiments of this application. Detailed Implementation

[0020] 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.

[0021] To better understand the technical solution of this application, a detailed description will be provided below in conjunction with the accompanying drawings and specific implementation methods.

[0022] As mentioned in the background section, how to provide a closed-loop optimization scheme for graph databases that can balance graph construction feasibility, query accuracy, and optimization convergence is a technical problem that urgently needs to be solved.

[0023] In view of this, this application provides a self-looping dynamic pruning optimization method for graph databases. By constructing a dual-loop self-consistent evaluation framework for the graph data construction, querying, and optimization stages, an executable graph is iteratively generated. During the querying process, dynamic pruning filters graph knowledge and injects it into the large model to generate graph query statements. During optimization, a quantitative feedback mechanism based on execution cost is constructed to improve query efficiency. This scheme effectively standardizes the graph structure and graph construction statement generation through the dual-loop evaluation framework, ensuring the executability of the construction results. Dynamic pruning significantly simplifies the input knowledge of the large model, reducing the probability of semantic illusion and thus improving the accuracy of query transformation. The quantitative feedback mechanism of execution cost guides the adjustment of the query path through multiple iterations, ensuring the stability and convergence of the system during the optimization process.

[0024] The execution subject of this application embodiment can be a graph database self-looping dynamic pruning optimization device, or a computing service device with data processing, network communication, and program execution functions, such as a tablet computer, personal computer, or mobile phone, or a thermal management device capable of implementing the above functions of the graph database self-looping dynamic pruning optimization device, etc. This embodiment does not specifically limit it in this way. The following uses the graph database self-looping dynamic pruning optimization device as the execution subject as an example to describe this embodiment and the following embodiments.

[0025] Reference Figure 1 The graph database self-looping dynamic pruning optimization method provided in this application includes steps S10 to S60: Step S10: Obtain the build request, query request, and optimization request of the target graph database.

[0026] It should be noted that a build request refers to input containing unstructured text such as data source descriptions and business entity relationship descriptions, used to instruct the system to automatically construct the graph structure of the graph database. A query request refers to a data query question described in natural language, such as "statistics on companies whose addresses are in Shenzhen and whose names contain China Energy". An optimization request refers to performance optimization requirements for generated graph query statements or for slow queries identified by the system. These three types of requests can be triggered independently at different stages, or they can be issued sequentially in the same task flow through a unified interface.

[0027] Understandably, to lower the barrier to entry for graph databases, this application incorporates graph construction, natural language querying, and query optimization into a unified processing framework. Therefore, it first needs to acquire the requests corresponding to these three stages. The purpose of acquiring these three types of requests is to perceive the different processing needs of users in the three stages of graph construction, graph querying, and optimization, and to provide trigger signals and raw inputs for subsequent end-to-end automated closed-loop processing. For example, in financial risk control, business personnel may first initiate a "build a graph of enterprise relationships" request. After the graph is generated, they may then use natural language to query "find the ultimate beneficiaries of a company's multiple layers of upstream and downstream businesses," and finally initiate an optimization request for the slow query returned by the system.

[0028] It should be understood that the aforementioned methods of obtaining requests should not be construed as limiting the scope of protection of this application. Build requests, query requests, and optimization requests can be manually entered through a user interface, pushed in batches by external systems via application programming interfaces (APIs), or automatically generated by internal scheduled inspection tasks. In actual deployment, it is advisable to design a unified data format or message body for different types of requests to reduce the parsing overhead of subsequent modules. Simultaneously, when obtaining requests, sufficient contextual identification information should be included to correctly associate requests with corresponding intermediate results in distributed or asynchronous execution scenarios.

[0029] Step S20: Based on the build request and the self-looping framework, iteratively evaluate the graph structure and graph building statements to obtain an executable graph.

[0030] It should be noted that the self-looping framework refers to a closed-loop evaluation structure consisting of nested outer and inner loops. The inner loop includes a graph structure design agent and a graph construction statement design agent, used for micro-loop iterations of "generation-evaluation-optimization" within a specific domain. The outer loop is responsible for rescheduling the execution of the inner loop when necessary to improve overall fault tolerance. Graph structure design refers to the logical definition of graph elements such as entity node types, attribute fields, and relationships between entities. Graph construction statements refer to the conversion of the graph structure design into executable DDL statements for a specific graph database, such as commands to create node tables or relationship tables. An executable graph refers to an initial graph database schema that includes both a logically correct graph structure design and graph construction statements that have been validated in a sandbox and confirmed to be successfully executable.

[0031] Understandably, traditional solutions that directly generate graph structures or graph construction statements from large models are prone to semantic inconsistencies, syntax errors, or structural disconnections, resulting in graphs that cannot run on real-world graph databases. This step introduces a self-looping framework, incorporating the large model generation process into a closed-loop control system of iterative evaluation and feedback. The role of iterative evaluation is to perform objective rule checks and subjective quality assessments on the generated results in each loop, continuously correcting deviations through scoring and retry mechanisms, ultimately outputting a high-quality graph that can be directly executed on the target graph database. For example, in the construction of a supply chain graph, evaluation experts identified a missing element during connectivity analysis and provided feedback for revision, thereby ensuring the integrity of the graph.

[0032] It should be understood that special attention should be paid to the isolation of the sandbox environment during the iterative evaluation process. Each execution of the graph-building statement should use a completely new or resettable sandbox instance to avoid residual state from previous failures interfering with subsequent evaluations. Simultaneously, when the outer loop restarts the inner loop, the evaluation results and error information from the previous inner loop should be passed as feedback context to the agent to guide it in targeted problem correction, rather than simply performing random retries. This can significantly improve convergence speed. Furthermore, after obtaining the executable graph, it is advisable to manage it in a versioned manner, recording the scoring history and iteration count during the generation process to facilitate problem tracing and contextual association for subsequent query stages.

[0033] Step S30: Based on the executable graph and query request, parse the query intent to obtain the target graph knowledge.

[0034] It should be noted that query intent parsing refers to the process of identifying the query type, key entity names, and hard business constraints from the user's natural language query request, and then filtering and pruning the full graph knowledge of the graph database accordingly. Target graph knowledge refers to the minimal set of graph structure metadata that is highly relevant to the current query intent and is retained after pruning, such as table names, field names, relation types, and necessary attribute constraints.

[0035] Understandably, in the task of converting natural language to graph queries, using the entire graph knowledge as the input context for a large language model not only consumes a large amount of token resources but also easily leads to semantic illusions, causing the model to incorrectly associate the query with irrelevant graph elements. This step parses the query intent first and then prunes the graph knowledge. The aim is to remove graph information irrelevant to the current query before injecting the knowledge into the large model, retaining only the most relevant parts. This significantly reduces the input length and computational cost of subsequent generation steps and improves the accuracy of query generation by narrowing the model's attention scope.

[0036] It should be understood that the accuracy of query intent parsing directly determines the relevance of the pruned knowledge. In implementation, the intent parsing module should ideally be implemented using a lightweight, small model to reduce latency and resource consumption. Furthermore, the key entity terms extracted from the parsing results may be ambiguous; for example, "address" might correspond to "registered address" or "office address" in the graph. Therefore, pruning should retain a moderate level of redundancy to avoid over-pruning that could lead to the omission of potentially relevant fields. Additionally, if the query request itself is semantically ambiguous and the confidence level of the parsing results is low, the system can verify the parsing results or prompt the user for clarification based on the structural characteristics of the executable graph.

[0037] Step S40: Generate a graph query statement based on the target graph knowledge.

[0038] It should be noted that a graph query statement refers to a query command that conforms to the syntax of a specific graph database, or a query instruction that conforms to the general GQL standard, such as a Cypher statement for the Neo4j graph database (e.g., MATCH(n:Company)-[:INVEST_IN]->(m)WHEREEn.name='A'RETURNm). During the generation process, the system uses the target graph knowledge as structural constraints and semantic context, and assembles it together with the user's original query request into prompt words, which are then input into the large language model. The large language model generates a graph query statement that can be directly executed based on the simplified knowledge.

[0039] Understandably, this step combines pruned graph knowledge with natural language query requests to provide a schema context for the large language model. Since the injected knowledge has been filtered, the large model can accurately map to specific nodes and relationships in the graph when performing schema binding, relation linking, and condition generation, thus significantly reducing illusions or grammatical errors caused by knowledge redundancy. For example, when the target graph knowledge explicitly indicates the existence of a Company node, a REGISTERED_AT relationship, and an Address node, and the query request is "find companies registered in Shenzhen," the model can generate MATCH(c:Company)-[:REGISTERED_AT]->(a:Address)WHERE a.city='Shenzhen'RETURNc.

[0040] It should be understood that although the input knowledge has been streamlined, large language models still possess a certain degree of randomness. Therefore, the generated graph query statements should undergo syntax and semantic validation in subsequent optimization stages or in a sandbox environment. If the graph database supports the EXPLAIN command, it can be executed immediately after generation to check the rationality of the query plan. Furthermore, in some complex scenarios, a single generation may not cover all intents; the system should support interactive user correction, gradually approaching a perfect query through human-computer collaboration.

[0041] Step S50: Based on the graph query statement and optimization request, evaluate the execution cost of the candidate optimization solutions to obtain the execution cost value.

[0042] It should be noted that candidate optimization schemes refer to multiple alternative query statements generated by the optimization model or large model generator, which are rewritten or optimized from the original graph query statement. Execution cost is a quantitative evaluation value calculated using a preset cost function, based on the performance metrics of the graph query statement during actual execution in a sandbox environment. This value measures the execution efficiency of the query scheme. The cost function typically considers key performance indicators specific to graph databases, such as execution time, total number of traversed nodes, and memory usage.

[0043] Understandably, in the field of graph databases, the cost of query execution is closely related to the number of nodes traversed and the path length. Traditional cost models based on disk I / O cannot accurately reflect the true overhead of graph queries. This step involves actually executing candidate optimization schemes and collecting multi-dimensional performance metrics to construct a quantitative evaluation system that can truly reflect the query complexity of graph databases. By using quantified execution costs as a unified metric, the system can objectively compare the merits of different optimization schemes, providing a clear direction and baseline for subsequent iterative optimization and avoiding blind optimization based solely on experience or rules.

[0044] It should be understood that all cost evaluation operations must be performed in an isolated sandbox environment to prevent unverified candidate optimization solutions from impacting the performance or posing data risks to the production graph database. The sandbox environment should have the same data statistical characteristics as the production environment but be of manageable size. Furthermore, the metrics in the cost function are affected by the current load of the sandbox environment. To obtain stable comparison results, the sandbox state should be ensured to be consistent before each evaluation, and the impact of occasional fluctuations can be mitigated by performing multiple evaluations and averaging the results.

[0045] In one embodiment, the above-mentioned evaluation of the execution cost of candidate optimization schemes to obtain the execution cost value includes: executing the candidate optimization schemes in a sandbox environment to obtain the execution time, number of traversed nodes, and memory usage; and calculating the execution cost value based on the execution time, number of traversed nodes, and memory usage, as well as the corresponding weights determined based on the graph data type.

[0046] It should be noted that execution time refers to the time elapsed from the start of execution of a graph query statement to the return of the result, which can be obtained through the PROFILE or EXPLAIN ANALYZE command of the graph database. The number of nodes traversed refers to the total number of nodes visited during the execution of the query within the graph database, and is a core indicator for measuring the scale of graph traversal. Memory usage refers to the peak usage of JVM (Java Virtual Machine) heap memory during query execution, reflecting the pressure of the query on system resources. The corresponding weights determined based on the graph data type refer to the fact that, for different types of graph database application scenarios (such as financial transaction graphs emphasizing path accuracy, social network graphs emphasizing anti-fan-out capability, and geographic graphs emphasizing spatial indexing efficiency), adaptive algorithms are used to assign differentiated weight coefficients w1, w2, and w3 to the three dimensions of execution time, number of traversals, and memory usage, thereby constructing a cost function highly coupled with the business scenario, for example, Cost=w1. T+w2 N+w3 M.

[0047] Understandably, using a single performance metric (such as execution time) cannot accurately reflect the optimization focus for different graph types. For example, queries in financial risk control relationship graphs often involve multi-hop path searches, and their performance bottleneck lies in the excessive number of traversed nodes; therefore, a higher weight should be given to the traversal node count metric. Conversely, supernodes in social network graphs may experience a sudden surge in traversals, leading to memory overflow; in this case, a higher weight should be given to memory usage. This step, through adaptive weight adjustment, ensures that the cost model can dynamically adjust the evaluation criteria according to the characteristics of graph data types, enabling the optimization process to accurately locate and suppress the true performance bottlenecks of this type of graph.

[0048] It should be understood that when collecting these metrics in a sandbox environment, it is essential to ensure that the graph database has detailed performance profiling capabilities enabled to obtain accurate internal execution data. For determining weights based on graph data types, simple meta-learning or heuristic rules can be introduced, such as dynamically calculating weights based on statistical characteristics like the complexity of relationship directions and the average degree of nodes in the graph schema. These weight configurations should be recorded and saved along with the optimization plan to facilitate subsequent analysis of the intrinsic relationship between optimization strategies and business scenarios.

[0049] In one embodiment, the above-mentioned calculation of execution cost based on execution time, number of traversed nodes, memory usage, and corresponding weights determined based on graph data types includes: calculating the cost reduction of the current optimization scheme relative to the historical best scheme; using the cost reduction as a reward signal; inputting the current optimization strategy and reward signal into the optimization model; generating the next round of optimization scheme based on the optimization model; and stopping the iteration if the cost of the next round of optimization scheme reaches a preset convergence condition, thus obtaining the optimized query path.

[0050] It should be noted that the reduction in cost value refers to the decrease in the cost of the current optimization solution compared to the cost value of the best solution in the historical records. If the current solution is better, the value is positive; otherwise, it is zero or negative. The reward signal is a feedback scalar constructed based on reinforcement learning theory, used to incentivize the optimization model to update in the direction of reducing cost value. The optimization model is a large language model with built-in adversarial thinking and iterative memory functions. It can actively explore new query rewriting strategies based on the accumulated optimization context and reward signals. The preset convergence condition refers to the rule for terminating the iteration, which usually includes the cost value reduction being less than a certain minimum threshold for several consecutive periods, or the number of iterations reaching a preset upper limit.

[0051] Understandably, this embodiment draws on the adversarial generative idea of ​​GANs (Generative Adversarial Networks) and the feedback iteration mechanism of RL (Reinforcement Learning). The large model, acting as a generator, continuously proposes new query rewriting schemes, while the cost evaluation module, acting as a discriminator, calculates the cost value and generates reward signals. This "generation-evaluation-feedback" closed loop drives the model to continuously learn how to avoid high-cost traversal patterns. For example, if the previous round used a "node pre-filtering" strategy to reduce the cost from 250 to 120, generating a positive reward, the optimization model will be more inclined to fine-tune around effective strategies such as "filtering" and "pruning" when generating the next round of schemes, while abandoning ineffective full-graph scan strategies, ultimately approximating the globally optimal execution path of the query under the current graph distribution.

[0052] It should be understood that there is a risk of overfitting or getting trapped in local optima during iterative optimization. To prevent this, a certain degree of randomness should be introduced when the large model generates candidate solutions, and it should be required to generate multiple candidate solutions rather than a single one to increase the search breadth. At the same time, the threshold settings in the preset convergence conditions must be scientifically reasonable; too strict a threshold will make it difficult to stop the iteration, while too lenient a threshold may miss the global optimum. Finally, the optimized query path must still undergo final verification in a sandbox environment to ensure its stability and security; it is strictly forbidden to directly deploy it to the production environment.

[0053] Step S60: Based on the execution cost, iteratively optimize the query path to obtain the optimized query path.

[0054] It should be noted that a query path refers to the specific sequence of steps in the execution plan used by a graph database to execute a given graph query statement, including node scanning, relation traversal, filtering, and joining. Iterative optimization refers to using the execution cost calculated in each of the aforementioned steps as a feedback signal to continuously drive the optimization model to generate and filter improved query solutions, so that the query path continuously approaches a lower value in terms of execution cost, eventually converging to an optimized query path that meets preset convergence conditions.

[0055] Understandably, graph query performance is highly dependent on query path design, and traditional manual optimization relies heavily on the experience of DBAs (database administrators), making it difficult to handle the dynamic changes in complex graph structures. This step achieves full automation of slow query optimization by combining quantitative cost assessment with an iterative optimization mechanism. Its aim is to leverage closed-loop feedback regulation to automatically discover and apply low-cost patterns such as node pre-filtering, index utilization, and path pruning during a generation process that combines exploration and utilization, thereby significantly improving the query response speed of graph databases under massive datasets.

[0056] It should be understood that the iterative optimization process should run in a closed loop within a sandbox or replica environment, and exploratory optimizations directly targeting the production system are strictly prohibited. After optimization, the generated optimized query path should be materialized into a new graph query statement and undergo rigorous performance regression verification before deployment. Furthermore, all intermediate data from the entire optimization process, including candidate solutions in each round, cost change curves, and the final adopted strategy, should be recorded as logs or model memories for rapid pre-testing of similar queries in the future or to provide optimization references for other queries.

[0057] This embodiment integrates requests from three stages—graph construction, querying, and optimization—into a unified processing entry point. For the graph construction stage, a self-looping framework is used to conduct multiple rounds of iterative evaluation of the graph structure and construction statements, combining subjective and objective approaches, ensuring the output graph has high executability. In the querying stage, high-purity, low-redundancy target graph knowledge is obtained through parsing the query intent and dynamically pruning graph knowledge, providing a reliable context for accurately generating graph query statements for large models. In the optimization stage, by actually executing candidate solutions in a sandbox and calculating multi-dimensional, weighted adaptive execution costs, a quantitative benchmark is established for iterative optimization of the query path. A reward-driven feedback loop guides the optimization direction, ultimately yielding a fully validated high-performance query statement.

[0058] In summary, this method incorporates the generation of uncertainty in large models into a self-looping closed-loop control based on objective rules, sandbox verification, and quantitative cost evaluation. It addresses the three major challenges of automated graph database construction, natural language query conversion, and intelligent performance optimization as a systematic project, achieving full-process automation from the original request to the verifiable closed-loop output. This significantly improves the overall automation level, application reliability, and operational efficiency of graph databases.

[0059] Combination Figure 1 Please refer to Figure 2 In the graph database self-looping dynamic pruning optimization method provided in this application embodiment, the above step S20 includes steps S201 to S206: Step S201: Construct a self-looping framework consisting of an outer loop and an inner loop, wherein the inner loop includes a graph structure design agent and a graph construction statement design agent.

[0060] It's important to note that the outer loop refers to the top-level loop logic that controls the overall graph construction task flow and has fault tolerance and retry capabilities. It manages the number of times the inner loop starts, stops, and restarts. The inner loop consists of two independent internal loops within the agent, each specializing in graph structure design and graph construction statement design, respectively. Each internal loop employs a self-optimization model of "design expert + evaluation expert," enabling in-depth refinement and local iteration of its own specialized output. The graph structure design agent focuses on constructing entity, attribute, and relationship definitions at the logical level, while the graph construction statement design agent focuses on converting the logical structure into concrete, syntactically precise DDL statements.

[0061] Understandably, graph structure design and graph construction statement generation are two complex tasks requiring different expertise. Directly assigning them to a single large model can easily lead to coupling errors and confusion. This step decouples the tasks architecturally by constructing a two-layer loop framework, allowing two agents to perform their respective duties. The inner loop conducts a specialized "generate-evaluate-optimize" micro-loop. The outer loop acts as a scheduler and corrective mechanism at a higher dimension. When the inner loop fails to meet the requirements no matter how well it is refined, a strategic restart is performed. This significantly improves the framework's fault tolerance for handling complex graph construction requirements and the quality of the final output.

[0062] It should be understood that when constructing this framework, the two inner-loop agents can be fine-tuned instances of the same large model, or independent models infused with different expert knowledge. When the outer loop schedules the inner loop, attention should be paid to passing differentiated contexts. For example, the final result of the graph structure design can be used as the mandatory input for the graph construction statement design agent to ensure consistency between statement construction and structure design. To achieve self-looping, a recognizable evaluation feedback format for the inner-loop agents must be predefined to ensure that the evaluation experts' scores and suggestions can be correctly parsed by the design experts.

[0063] Step S202: Generate a graph structure design through a graph structure design agent.

[0064] It should be noted that graph structure design refers to the logical schema definition of the graph output by this construction request. Specifically, it includes node labels, node attributes and their data types, relation types, relation attributes, and connectivity constraints between these elements. The process of generating a graph structure design involves the agent using its knowledge to logically model the unstructured text input and outputting a structured draft graph schema.

[0065] Understandably, this serves as a logical intermediary layer between bridge construction requests and physical mapping. Directly correcting errors at the physical mapping statement level is costly and makes it difficult to pinpoint the root cause. Generating and validating the logical-level graph structure design first allows for more efficient discovery of discrepancies between business semantics and model derivation. Introducing multi-dimensional scoring at this step aims to address the issues of excessive randomness in large model generation results and the lack of deterministic rule verification, thus laying a solid logical foundation for building an executable graph.

[0066] It should be understood that the design draft generated by the graph structure design agent allows for multiple logically equivalent representations. The evaluation system should not rigidly demand complete consistency with the pre-defined template, but rather focus on semantic integrity and correct connectivity. Furthermore, the data types of attributes involved in the graph structure design (such as INT, STRING, DATE) are fundamental to the correct creation of subsequent graph construction statements; this information should be explicitly provided to the agent.

[0067] In one embodiment, the above-mentioned generation of graph structure design through a graph structure design agent includes: obtaining an objective score for the graph structure design based on its conformity with preset rules, wherein the preset rules include semantic consistency, data integrity, and connectivity analysis rules; obtaining a subjective comprehensive score by performing quality evaluation through a large model based on the quality of the graph structure design; obtaining a graph structure design score based on the objective score and the subjective comprehensive score; if the graph structure design score is less than a preset score threshold, then re-executing the graph structure design through an outer loop; if the graph structure design score is greater than the preset score threshold, then ending the loop and determining the current graph structure design as the final graph structure design.

[0068] It should be noted that semantic consistency rules refer to verifying whether the naming of nodes and relationships aligns with business concepts and whether there are any ambiguities or contradictions; data integrity rules refer to whether all nodes and relationships possess the necessary attributes and whether the attribute types match the descriptions; connectivity analysis rules refer to checking for isolated nodes or relationships without beginning or end. Large-scale model quality assessment refers to the large model acting as an evaluation expert providing a comprehensive score and improvement suggestions for non-quantitative soft indicators such as the rationality, elegance, and scalability of the graph structure design. The graph structure design score is a weighted sum of objective and subjective comprehensive scores, and the weights can be configured according to the expected creativity of the model, for example, set as S_final=w S_subjective+(1-w) S_objective. The preset rating threshold is the user-defined acceptable quality threshold.

[0069] Understandably, introducing a multi-dimensional scoring mechanism for graph structure design aims to reconcile the contradiction between deterministic rules and subjective creativity. Purely objective rules (such as connectivity checks) can only guarantee the absence of theoretical errors, not that the results meet real needs. While purely large-scale model scoring can perceive actual client needs, it may overlook basic objective facts due to misperceptions. A weighted combination of both allows deterministic rules to suppress divergent errors in large models, ensuring a baseline; simultaneously, it allows large models to unleash creativity within the framework of rules, raising the design ceiling. This design enables the evaluation system to avoid inflated scores while uncovering more insightful graph structures.

[0070] It should be understood that the weighting of subjective and objective scores is a key parameter. When starting up for the first time or with poor data quality, the weight of objective scores can be appropriately increased to reduce the risk of misleading results. When business requirements are unclear, the weight of subjective scores can be increased to encourage the model to explore more diverse structural approaches. Furthermore, the quality assessment of large models may itself be biased; therefore, it is advisable to consider introducing multi-model voting or cross-referencing with historical best practices to enhance the reliability of subjective scores.

[0071] In one embodiment, if the score of the above-mentioned graph structure design is less than a preset score threshold, the inner loop is restarted through the outer loop, including: obtaining the number of restarts of the inner loop from the outer loop; if the number of restarts is less than a first preset number, the preset score threshold is maintained; if the number of restarts is greater than or equal to the first preset number and less than a second preset number, the preset score threshold is reduced; if the number of restarts is greater than or equal to the second preset number, the loop is stopped and an executable graph is obtained.

[0072] It should be noted that the restart count refers to the total number of times the inner loop is called back due to the outer loop failing to meet the score. The first preset count is the maximum number of times the high standard threshold can be maintained, and the second preset count is the number of times the loop is completely stopped and forced to converge. Lowering the preset score threshold, i.e., dynamically reducing the quality acceptance threshold, allows designs that were originally judged as unqualified to have a chance to meet the standard in the intermediate loop, thereby promoting convergence.

[0073] Understandably, this mechanism is the "adaptive linear exit mechanism." Actual testing shows that the optimization effect of large models exhibits diminishing marginal returns with increasing loop count. Maintaining a stringent high threshold after several iterations can easily lead to an infinite loop, wasting computational resources. By segmenting the restart count, prioritizing quality in the early stages of the loop, compromising for efficiency within acceptable limits in the middle stages, and forcibly stopping losses in the later stages, this strategy simulates the idea of ​​the annealing algorithm, achieving a dynamic balance between quality, efficiency, and successful exit. For example, if the first preset number of restarts is 3 and the second preset number of restarts is 6, then if the target is not met after 3 loops, the system realizes that it may be approaching the limit of the model's current capabilities and proactively lowers the expectation to avoid idling.

[0074] It should be understood that the first and second preset iterations should be empirically tuned based on the business's tolerance for graph quality and the system's average response time requirements. When lowering the scoring threshold, a linear or exponential decrease is preferable to a sudden, large drop, to prevent premature convergence to a structure of extremely poor quality. Furthermore, even if the loop is forcibly stopped, the design corresponding to the highest score from each iteration should be saved as the final output, not just the result of the last iteration.

[0075] Step S203: Design an agent to generate graph construction statements using graph construction statements.

[0076] It should be noted that graph construction statements refer to a set of data definition language commands generated according to the syntax of a specific graph database, used to create and define node tables, relation tables, indexes, and constraints. The graph construction statement design agent takes a validated graph structure design as input and automatically translates it item by item into an executable script based on the syntax manual of the target graph database.

[0077] Understandably, the graph creation statement is the physical implementation of the graph structure design, and its generation quality directly determines whether the graph can be successfully created. This step is independent of the graph structure design loop because even if the logical structure is perfect, it may still introduce syntax errors or violate specific database restrictions (such as name length, keyword conflicts, etc.) when converted into concrete statements. Therefore, it requires special handling and undergoes executable verification in subsequent steps, rather than just performing logical checks.

[0078] It should be understood that, to ensure high portability of graph construction statements, standard GQL syntax or parameterized configuration should be used during generation, and an adapter should be configured to adapt to the dialect of specific graph databases (such as Neo4j, JanusGraph, etc.). The agent should output both the creation script and the corresponding rollback script during generation, facilitating rapid cleanup of the sandbox environment after verification failures and supporting efficient automated testing.

[0079] Step S204: Evaluate the graph structure design and graph construction statements to obtain the evaluation results.

[0080] It should be noted that the evaluation referred to here integrates the dual verification results of the preceding diagram structure design score and the executability of the drawing statements. The evaluation of the drawing statements adopts a "sandbox pre-execution and one-vote veto mechanism," that is, the evaluation experts execute the generated drawing statements one by one in an isolated environment. If any statement fails to execute, the overall evaluation will fail, the drawing statement module will receive a score of zero, and a detailed error log will be returned.

[0081] Understandably, this step is a critical quality control point to ensure the final output of an "executable graph." The multi-dimensional scoring of the graph structure design guarantees the "goodness and correctness" of the logic, while the sandbox pre-execution of the graph-building statements ensures "usability" from a physical perspective. The introduction of a veto mechanism is necessary because the failure of one part will lead to the failure of the entire graph deployment, requiring zero tolerance. This fault-tolerant design directly builds the reliability of the task on immutable machine execution evidence, completely avoiding the embarrassing situation of "looking correct but failing upon execution."

[0082] It should be understood that during the evaluation process, the resource quotas (such as memory limits and execution timeouts) in the sandbox environment should be consistent with those in the pre-production environment to verify executability under real resource constraints. Furthermore, when executing graph-building statements, some databases allow multiple statements to be executed as a single transaction. This offers the benefit of atomic failures but also requires cleaner rollback operations. The design of the evaluation environment needs to consider these transaction characteristics in advance.

[0083] Step S205: If the evaluation result does not meet the preset conditions, restart the inner loop through the outer loop.

[0084] It should be noted that the preset conditions are that the graph structure design score exceeds the dynamic threshold and all graph building statements are executed successfully in the sandbox. Restarting the inner loop from the outer loop means that when the output of any inner loop fails to meet the above conditions, the outer loop will use the key information of the failure in this round as feedback, reset the state of both inner loops, and restart the entire inner loop process from the graph structure design stage.

[0085] Understandably, logical flaws in graph structure design often propagate to the graph construction statement level, and simply regenerating the graph construction statement may not solve the fundamental problem. Therefore, the strategy is to return to the starting point of the entire chain and reconstruct the entire structure and statement level. This design, with unified scheduling by the outer loop, ensures the depth of problem tracing and the systematic nature of correction, avoiding the trap of local optimization that involves repeatedly modifying details at the end without addressing the root cause.

[0086] It should be understood that special care should be taken to prevent misleading feedback when restarting the inner loop. Only cleaned evaluation information that clearly identifies the problem should be sent back, such as "an isolated 'address' node exists," rather than unstructured, lengthy negative feedback, to avoid interfering with the large model. Furthermore, a complete snapshot of the failure should be recorded before restarting for later process analysis and model fine-tuning.

[0087] Step S206: If the number of restarts reaches a preset threshold, the loop stops and an executable graph is obtained.

[0088] It should be noted that the preset threshold here is the maximum number of scheduling attempts allowed in the outer loop, which is the second preset number mentioned above. Once the number of restarts of the outer loop reaches this limit, regardless of the output score in the current loop, the system will forcibly terminate all evaluation and retry processes, and select the evaluation product with the best overall performance in the current lifecycle as the final executable graph for output.

[0089] Understandably, this is the last line of defense for the adaptive linear exit mechanism. It sets a rigid upper limit on the time taken for the entire graphing process, ensuring that even with extreme inputs or limited model capabilities, the system can still deliver a "best-effort" optimized result within a finite time without service interruption. This feature is crucial for automated pipelines because it guarantees that the overall system's production rhythm will not be delayed by infinite retries of a single task.

[0090] It should be understood that while the executability of the output graph after forced stop is guaranteed, its optimality may not have fully reached the ideal state. The output log can be marked as "degraded output" and the fact that it did not reach the user's original expected threshold can be recorded for subsequent manual review or as a negative training sample to further improve the model's processing capabilities in complex scenarios.

[0091] In this embodiment, by establishing an inner and outer double-layer self-circulating system, the complex task of automatically building a graph database is decomposed into two collaborative sub-tasks at the architecture level: graph structure design and graph building statement generation. Through three core mechanisms—multi-dimensional subjective and objective scoring, sandbox veto, and adaptive linear exit—the uncertainty of large model generation is incorporated into a rigorous process control.

[0092] In summary, this embodiment fundamentally eliminates the generation illusion and non-executability risks of large models in graph database construction through sophisticated two-layer loop control logic and rigorous physical-level executability verification. While ensuring construction quality, it guarantees the system's high robustness and output timeliness, realizing a fully automated and intelligent leap from unstructured requirements to executable physical models in the graph construction process with "zero human intervention and zero syntax errors".

[0093] In combination with the above Figure 1 Please refer to Figure 3 The above step S30 includes steps S301 to S306: Step S301: Perform intent recognition and masking processing on the query request to obtain masked word segmentation, wherein the masking processing includes replacing named entities with entity types.

[0094] It's important to note that intent recognition refers to classifying query statements using a small model to determine their intent type, such as "statistics," "exact search," or "pathfinding." This type will be used as an adjustment factor for subsequent dynamic pruning thresholds. Masking refers to replacing specific named entity values ​​(e.g., "Shenzhen" or "China Energy") with their entity type labels (e.g., [CITY], [COMPANY_NAME]) after word segmentation and named entity recognition of the query statement. The word segmentation after masking is a sequence of words that retains both common nouns and entity type labels.

[0095] Understandably, the specific entity values ​​in the query statement often overlap with attribute names in the graph model or irrelevant words in the background text. Direct matching without masking easily introduces noise; for example, the word "energy" might appear as part of a company name or happen to be an attribute key name of a node. By masking it as meaningless placeholders for the type, such erroneous cross-level associations can be effectively blocked. Identifying the query intent provides a basis for subsequent adaptive pruning, allowing "statistical" requests to encompass more approximate concepts, while "exact search" is more stringent, thus matching the granularity of the user's actual information needs.

[0096] It should be understood that both intent recognition and masking are based on lightweight small models (such as DistilBERT) to complete preprocessing in the front-end pipeline with extremely low computational latency, without crowding out the inference time and context window of the downstream large models. The accuracy of the mask depends on the domain adaptability of the Named Entity Recognition (NER) model. For specialized domains such as finance and medicine, some fine-tuning of the NER model may be necessary. Furthermore, the masked words should be tagged for recovery, as the final query may still require the reconstruction of these entity values ​​as query conditions.

[0097] Step S302: Extract key entity words from the word segmentation after masking.

[0098] It should be noted that key entity terms refer to the common nouns or noun phrases that can express the core business object being queried, retained in the segmented sequence after removing stop words and type tags, such as "company," "address," and "name." The extraction process can be implemented based on part-of-speech tagging and dependency parsing.

[0099] Understandably, after masking, only the skeletal words expressing structural requests remain in the query. The purpose of extracting these words is that they are "semantic hooks" connecting user queries with graph database metadata (such as table names and field names). These words are the only clues for subsequent searching and matching in the graph knowledge base, and their accurate extraction directly determines the direction of pruning. For example, extracting "company" and "address" from "statistics companies with addresses in Shenzhen..." can narrow the search scope to nodes and attributes in the graph related to these two things.

[0100] It should be understood that special attention should be paid to word segmentation granularity and out-of-vocabulary (OV) terms when handling Chinese query requests. "Key entity terms" do not necessarily refer to single words; they may be compound words, such as "corporate legal person." When extracting these terms, a phrase recognition strategy combining a thesaurus or statistical information is advisable. When the query is short and the key entity terms are insufficient, the system should determine whether this will lead to insufficient matching information and may reduce the strictness of subsequent pruning to retain more graph knowledge to prevent omissions.

[0101] Step S303: Perform field matching between key entity words and graph knowledge to obtain the first matching result.

[0102] It should be noted that field matching refers to a case-insensitive, precise string matching between the extracted key entity terms and the physical field names (such as company_name_zh, reg_address) in the graph database schema. The first matching result is the set of graph knowledge elements that are directly matched, usually the most directly relevant core fields.

[0103] Understandably, exact field matching is the most stringent and reliable matching method. When the words in a user's query happen to match the physical field names in the database design, this is a highly reliable correlation signal, a direct match without any intermediate transformations, and the most efficient. This level of matching can quickly identify those core data structures with standardized naming and explicit relevance, providing a clear "anchor" for subsequent fuzzy matching.

[0104] It should be understood that exact matching may be limited by the naming conventions of the database designer. For example, if a user enters "company name" but the physical field is named comp_name, no match will be found. Therefore, the set of the first matching results may be empty or very small, which is normal. The matching scope should not be forcibly expanded; the remaining responsibility should be handled by subsequent similarity matching. In addition, when matching, it is necessary to exclude generic fields that, although sharing the same name as the key entity term, are semantically unrelated (such as a generic name field). A secondary validation can be performed by considering the table type to which the field belongs.

[0105] Step S304: Perform similarity matching between key entity words and graph knowledge to obtain the second matching result.

[0106] It should be noted that similarity matching refers to using a small model to calculate the semantic similarity between graph knowledge elements not covered in the first matching result (exact matching) and each key entity word. The second matching result refers to the set of graph knowledge elements whose similarity scores exceed a preset threshold. This threshold is not a fixed value, but is dynamically adjusted according to the query intent identified in step S301. For example, when the intent is "statistics", the threshold is appropriately relaxed to obtain broader relevant information.

[0107] Understandably, this is a powerful complement to exact matching, bridging the "semantic gap" between the diversity of natural language expression and the strictness of database naming. Through semantic space computation, "company name" can be associated with either "company_name_zh" or "full company name." Using dynamic thresholds instead of fixed thresholds allows the system to exhibit different "associative" capabilities based on the nature of the query task, obtaining the most appropriate breadth of information in both precise single-entity queries and broad statistical correlation data scenarios, thus achieving intelligent adaptive information filtering.

[0108] It should be understood that semantic similarity matching has a higher computational cost than exact matching. To control latency, efficient models such as distilled lightweight Sentence-BERT should be used, and all graph knowledge elements (field annotations, aliases, etc.) should be pre-encoded as vectors and stored in a cache. Only key entity words should be encoded in real time for retrieval. The dynamic threshold should be set within a reasonable range (e.g., 0.7-0.9) to avoid introducing a lot of noise if the threshold is too low or resulting in no results if it is too high. If necessary, the matching results can be sorted, retaining only the top-K elements to prevent information overload.

[0109] Step S305: Obtain the mandatory business fields in the query request.

[0110] It should be noted that mandatory business fields refer to graph knowledge fields that users explicitly instruct to be retained in their query requests through special syntax or markers, such as "please be sure to include the legal entity address" or "#anchor:reg_address". These instructions, as the highest priority knowledge anchors, specify metadata items that cannot be removed during the pruning process.

[0111] Understandably, in the pursuit of streamlined pruning, some fields that users subjectively consider extremely important but are misjudged as irrelevant by the algorithm due to semantic distance may be filtered out. Introducing a mandatory business field mechanism provides a direct injection interface for users' business experience outside of the automated algorithm. As an absolutely reserved "whitelist," it ensures that the system's intelligent pruning does not deviate from the core business requirements and avoids query failures or result deviations due to the loss of key information.

[0112] It should be understood that the parsing of mandatory business fields should be performed before the final step of pruning. The parsing logic can be based on regular expression matching of instructions with specific formats, or it can be the intent identified by the small model. Care must be taken to handle exceptional cases where the mandatory field does not exist in the actual graph knowledge. When the specified field does not exist in the graph, a clear prompt should be issued to the user, rather than causing execution errors during query generation or problems due to invalid anchors during pruning.

[0113] Step S306: Based on the first matching result, the second matching result, and the forced business field, prune the graph knowledge to obtain the target graph knowledge.

[0114] It's important to note that pruning involves taking the entire graph schema knowledge (including all tables, fields, relationships, constraints, and other metadata) as the complete set, retaining the first matching result (exact match), the second matching result (semantic similarity), and all elements anchored by the forced business fields, while removing all other content. The resulting target graph knowledge is an extremely concise, lightweight subset containing only the minimum schema information required for the query.

[0115] Understandably, the merging of the three data streams results in a high-quality subset of knowledge that incorporates both intelligent system recognition and strict user oversight. This subset, serving as the "contextual essence" of the NL2GQL (Natural Language to Graph Query Language) task, will be injected into the larger model. Compared to complete graph knowledge, it removes over 90% of useless information, allowing the model's attention to be highly focused on relevant fields and relationships. This significantly reduces token consumption and the possibility of semantic illusions at the source, making it an efficient bridge between ambiguous natural language and rigorous structured query language.

[0116] It should be understood that the target knowledge graph generated after pruning should have a structured representation, such as JSON format, so that large models can stably parse it rather than dealing with a one-dimensional text stream. Intermediate results of the pruning process (the sources of each matching set) should be recorded. When the final generated query statement fails, these intermediate results can be used to pinpoint whether the problem lies in a missed match or a problem with the model's generation logic. Furthermore, if the target knowledge graph after pruning is too simplistic (e.g., containing only a table name), it may indicate that the query is too simple or that a match has failed. In this case, the system should assess the risk and decide whether to revert to a richer knowledge injection strategy.

[0117] In this embodiment, a four-step dynamic pruning pipeline is constructed, consisting of intent decoding, entity masking, multi-layer matching, and forced anchoring. A lightweight small model is used to perform multi-level comparison and analysis of query requests and graph knowledge, and to accurately extract the minimum knowledge set closely related to the current query from the full amount of information.

[0118] In summary, this application's embodiments effectively eliminate the severe semantic illusions and high token costs associated with injecting full graph knowledge into large models by upgrading graph knowledge from a static inventory to a lightweight injection stream that flows on demand. Without altering the underlying large model structure, intelligent preprocessing technology significantly improves the generalization ability and generation accuracy of NL2GQL tasks in complex, multi-domain business graphs.

[0119] This application also provides a graph database self-looping dynamic pruning optimization device. Please refer to... Figure 4 The graph database self-looping dynamic pruning optimization device includes: The instruction receiving module 10 is used to obtain the construction request, query request and optimization request of the target graph database; The graph construction module 20 is used to iteratively evaluate the graph structure and graph construction statements based on the construction request and the self-looping framework to obtain an executable graph. The query module 30 is used to parse the query intent based on the executable graph and the query request to obtain the target graph knowledge; The query module 30 is also used to generate graph query statements based on the target graph knowledge; The cost evaluation module 40 is used to evaluate the execution cost of candidate optimization solutions based on the graph query statement and optimization request, and obtain the execution cost value. The iterative optimization module 50 is used to iteratively optimize the query path based on the execution cost to obtain the optimized query path.

[0120] The graph database self-loop dynamic pruning optimization device provided in this application, employing the graph database self-loop dynamic pruning optimization method in the above embodiments, can solve the technical problem of how to provide a graph database closed-loop optimization scheme that can balance graph construction executability, query accuracy, and optimization convergence. Compared with the prior art, the beneficial effects of the graph database self-loop dynamic pruning optimization device provided in this application are the same as those of the graph database self-loop dynamic pruning optimization method provided in the above embodiments, and other technical features in this graph database self-loop dynamic pruning optimization device are the same as those disclosed in the methods of the above embodiments, and will not be repeated here.

[0121] This application provides a graph database self-looping dynamic pruning optimization 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, and the instructions are executed by the at least one processor to enable the at least one processor to execute the graph database self-looping dynamic pruning optimization method in the first embodiment described above.

[0122] The following is for reference. Figure 5This document illustrates a structural schematic diagram of a graph database self-looping dynamic pruning optimization device suitable for implementing embodiments of this application. The graph database self-looping dynamic pruning optimization device in this application embodiment may include, but is not limited to, mobile terminals such as mobile phones, 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 5 The illustrated graph database self-looping dynamic pruning optimization device is merely an example and should not impose any limitations on the functionality and scope of use of the embodiments of this application.

[0123] like Figure 5 As shown, the graph database self-looping dynamic pruning optimization 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 read-only memory (ROM) 1002 or a program loaded from storage device 1003 into random access memory (RAM) 1004. The RAM 1004 also stores various programs and data required for the operation of the graph database self-looping dynamic pruning optimization device. The processing unit 1001, ROM 1002, and RAM 1004 are interconnected via a bus 1005. An input / output (I / O) interface 1006 is also connected to the bus. Typically, the following systems can be connected to I / O 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. Communication device 1009 allows the graph database self-looping dynamic pruning optimization device to communicate wirelessly or wiredly with other devices to exchange data. Although graph database self-looping dynamic pruning optimization devices with various systems are shown in the figures, it should be understood that it is not required to implement or possess all the systems shown. More or fewer systems can be implemented alternatively.

[0124] 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 ROM 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.

[0125] The graph database self-loop dynamic pruning optimization device provided in this application, employing the graph database self-loop dynamic pruning optimization method in the above embodiments, can solve the technical problem of how to provide a graph database closed-loop optimization scheme that can balance graph construction executability, query accuracy, and optimization convergence. Compared with the prior art, the beneficial effects of the graph database self-loop dynamic pruning optimization device provided in this application are the same as those of the graph database self-loop dynamic pruning optimization method provided in the above embodiments, and other technical features in this graph database self-loop dynamic pruning optimization device are the same as those disclosed in the previous embodiment method, and will not be repeated here.

[0126] It should be understood that the various parts disclosed in 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.

[0127] The above description is merely a specific embodiment 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.

[0128] 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 graph database self-looping dynamic pruning optimization method in the above embodiments.

[0129] The computer-readable storage medium provided in this application may be, for example, a USB flash drive, but is not limited to, electrical, magnetic, optical, electromagnetic, infrared, or semiconductor systems, 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 fiber, 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, 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.

[0130] The aforementioned computer-readable storage medium may be included in the graph database self-looping dynamic pruning optimization device; or it may exist independently and not be assembled into the graph database self-looping dynamic pruning optimization device.

[0131] The aforementioned computer-readable storage medium carries one or more programs. When these programs are executed by the graph database self-looping dynamic pruning and optimization device, the graph database self-looping dynamic pruning and optimization device performs the following actions: acquiring the construction request, query request, and optimization request of the target graph database; iteratively evaluating the graph structure and construction statements based on the construction request and the self-looping framework to obtain an executable graph; parsing the query intent based on the executable graph and the query request to obtain target graph knowledge; generating graph query statements based on the target graph knowledge; evaluating the execution cost of candidate optimization schemes based on the graph query statements and the optimization request to obtain execution cost value; and iteratively optimizing the query path based on the execution cost value to obtain the optimized query path.

[0132] Computer program code for performing the operations of this application can be written in one or more programming languages ​​or a combination thereof, including 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).

[0133] 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.

[0134] 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.

[0135] The readable storage medium provided in this application is a computer-readable storage medium that stores computer-readable program instructions (i.e., a computer program) for executing the above-described graph database self-loop dynamic pruning optimization method. This solves the technical problem of how to provide a graph database closed-loop optimization scheme that balances graph construction executability, query accuracy, and optimization convergence. Compared with the prior art, the beneficial effects of the computer-readable storage medium provided in this application are the same as those of the graph database self-loop dynamic pruning optimization method provided in the above embodiments, and will not be repeated here.

[0136] The computer program product provided in this application can solve the technical problem of self-looping dynamic pruning optimization of graph databases. Compared with the prior art, the beneficial effects of the computer program product provided in this application are the same as the beneficial effects of the self-looping dynamic pruning optimization method for graph databases provided in the above embodiments, and will not be repeated here.

[0137] The above description is only a part of the embodiments of this application and does 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 self-looping dynamic pruning optimization method for graph databases, characterized in that, The method includes: Obtain the build request, query request, and optimization request of the target graph database; Based on the construction request and the self-looping framework, the graph structure and graph construction statement are iteratively evaluated to obtain an executable graph. Based on the executable graph and the query request, the query intent is parsed to obtain the target graph knowledge; Based on the target graph knowledge, generate a graph query statement; Based on the graph query statement and the optimization request, the execution cost of the candidate optimization scheme is evaluated to obtain the execution cost value; Based on the execution cost, the query path is iteratively optimized to obtain the optimized query path.

2. The graph database self-looping dynamic pruning optimization method according to claim 1, characterized in that, The step of iteratively evaluating the graph structure and graph construction statements based on the construction request and the self-looping framework to obtain an executable graph includes: A self-looping framework consisting of an outer loop and an inner loop is constructed, wherein the inner loop includes a graph structure design agent and a graph construction statement design agent; The graph structure design agent generates a graph structure design; The intelligent agent is designed to generate the mapping statement using the mapping statement; The graph structure design and the graph construction statement are evaluated to obtain the evaluation results; If the evaluation result does not meet the preset conditions, the inner loop is restarted through the outer loop; If the number of restarts reaches a preset threshold, the loop stops, and the executable graph is obtained.

3. The graph database self-looping dynamic pruning optimization method according to claim 2, characterized in that, The generation of graph structure design through the graph structure design agent includes: An objective score for the graph structure design is obtained based on the degree of conformity between the graph structure design and the preset rules, wherein the preset rules include semantic consistency, data integrity, and connectivity analysis rules. Based on the quality of the aforementioned diagram structure design, a quality assessment is conducted using a large model to obtain a subjective comprehensive score; The graph structure design score is obtained based on the objective score and the subjective comprehensive score. If the graph structure design score is less than the preset score threshold, the graph structure design will be re-executed through the outer loop; If the graph structure design score is greater than the preset score threshold, the loop ends and the current graph structure design is determined as the final graph structure design.

4. The graph database self-looping dynamic pruning optimization method according to claim 3, characterized in that, If the graph structure design score is less than a preset score threshold, the inner loop is restarted via the outer loop, including: Obtain the number of times the outer loop restarts the inner loop; If the number of restarts is less than the first preset number, then the preset scoring threshold is maintained; If the number of restarts is greater than or equal to the first preset number and less than the second preset number, then the preset scoring threshold is reduced. If the number of restarts is greater than or equal to the second preset number, the loop stops, and the executable graph is obtained.

5. The graph database self-looping dynamic pruning optimization method according to claim 1, characterized in that, The step of parsing the query intent based on the executable graph and the query request to obtain target graph knowledge includes: The query request is subjected to intent recognition and masking processing to obtain masked word segmentation, wherein the masking processing includes replacing named entities with entity types; Extract key entity words from the word segmentation after the masking process; The key entity vocabulary is matched with the graph knowledge to obtain the first matching result; The key entity words are matched with the graph knowledge to obtain a second matching result; Retrieve the mandatory business fields from the query request; Based on the first matching result, the second matching result, and the forced business field, the graph knowledge is pruned to obtain the target graph knowledge.

6. The graph database self-looping dynamic pruning optimization method according to claim 1, characterized in that, The process of evaluating the execution cost of candidate optimization schemes to obtain the execution cost value includes: The candidate optimization scheme was executed in a sandbox environment to obtain the execution time, number of nodes traversed, and memory usage. The execution cost is calculated based on the execution time, the number of traversed nodes, the memory usage, and the corresponding weights determined based on the graph data type.

7. The graph database self-looping dynamic pruning optimization method according to claim 6, characterized in that, The step of calculating the execution cost based on the execution time, the number of traversed nodes, the memory usage, and the corresponding weights determined based on the graph data type includes: Calculate the reduction in cost of the current optimized solution compared to the historical best solution; The reduction in the cost value is used as a reward signal; Input the optimization strategy for this round and the aforementioned reward signal into the optimization model; Based on the optimization model, generate the next round of optimization scheme; If the cost of the next round of optimization reaches the preset convergence condition, the iteration stops, and the optimized query path is obtained.

8. A graph database self-looping dynamic pruning optimization device, characterized in that, The device includes: The instruction receiving module is used to obtain the construction request, query request, and optimization request of the target graph database; The graph construction module is used to iteratively evaluate the graph structure and graph construction statements based on the construction request and the self-looping framework to obtain an executable graph. The query module is used to parse the query intent based on the executable graph and the query request to obtain the target graph knowledge; The query module is also used to generate a graph query statement based on the target graph knowledge; The cost evaluation module is used to evaluate the execution cost of candidate optimization schemes based on the graph query statement and the optimization request, and obtain the execution cost value. The iterative optimization module is used to iteratively optimize the query path based on the execution cost value to obtain the optimized query path.

9. A graph database self-looping dynamic pruning optimization device, characterized in that, include: The memory, the processor, and the computer program stored in the memory and executable on the processor, wherein the processor, when executing the program, implements the graph database self-looping dynamic pruning optimization method as described in any one of claims 1 to 7.

10. A computer-readable storage medium having a computer program or instructions stored thereon, characterized in that, When the computer program or instructions are executed by the processor, they implement the graph database self-looping dynamic pruning optimization method as described in any one of claims 1 to 7.