Query rewrite, which aims to generate more efficient queries by altering a SQL query's structure without changing the query result, has been an important research problem. In order to maintain equivalence between the rewritten query and the original one during rewriting, traditional query rewrite methods always rewrite the queries following certain rewrite rules. However, some problems still remain. Firstly, existing methods of finding the optimal choice or sequence of rewrite rules are still limited and the process always costs a lot of resources. Methods involving discovering new rewrite rules typically require complicated proofs of structural logic or extensive user interactions. Secondly, current query rewrite methods usually rely highly on DBMS cost estimators which are often not accurate. In this paper, we address these problems by proposing a novel method of query rewrite named LLM-R2, adopting a large language model (LLM) to propose possible rewrite rules for a database rewrite system. To further improve the inference ability of LLM in recommending rewrite rules, we train a contrastive model by curriculum to learn query representations and select effective query demonstrations for the LLM. Experimental results have shown that our method can significantly improve the query execution efficiency and outperform the baseline methods. In addition, our method enjoys high robustness across different datasets.
翻译:查询重写旨在通过改变SQL查询结构而不改变查询结果来生成更高效的查询,一直是重要的研究问题。为了在重写过程中保持重写后查询与原查询的等价性,传统查询重写方法通常遵循特定重写规则进行重写。然而,仍存在一些问题:首先,现有寻找最优重写规则选择或序列的方法依然有限,且过程通常耗费大量资源;而涉及发现新重写规则的方法往往需要复杂结构逻辑证明或大量用户交互。其次,当前查询重写方法通常高度依赖DBMS代价估计器,但此类估计器往往不够精确。本文针对这些问题提出名为LLM-R2的新型查询重写方法,采用大语言模型为数据库重写系统推荐可能的重写规则。为进一步提升大语言模型在推荐重写规则方面的推理能力,我们采用课程学习训练对比模型以学习查询表征,并为大语言模型选择有效的查询示例。实验结果表明,我们的方法能显著提升查询执行效率并优于基线方法。此外,该方法在不同数据集上具有高鲁棒性。