Elasticsearch:用于 LLMs 和搜索引擎的查询重写策略以改善结果

2026年2月8日   |   by mebius

作者:来自 ElasticChristina NasikaEmilia Garcia Casademont

%title插图%num

探索查询重写策略,并说明如何使用 LLMs 的输出来提升原始查询的结果,最大化搜索相关性和召回率。

Elasticsearch内置了大量新功能,帮助你为你的使用场景构建最佳搜索解决方案。通过我们的实战网络研讨会,学习如何将它们应用到构建现代 Search AI 体验中。你也可以立即开始免费的云试用,或者在本地机器上试用 Elastic。


将大型语言模型( LLMs )集成到搜索流水线中的最大挑战之一,是如何驾驭它们所提供的巨大可能性空间。本文聚焦于一小组具体的查询重写( QR )策略,包括使用 LLM 生成的关键词、伪答案或增强术语。我们将重点介绍如何最佳地利用 LLM 的输出来有策略地提升原始查询的结果,从而最大化搜索相关性和召回率。

LLMs 与搜索引擎:用于提升搜索效果的查询重写策略探索

将大型语言模型( LLMs )与搜索引擎集成,代表了搜索与 AI 领域的一项重要进展。这种集成可以根据具体应用以多种形式实现 [1]。一方面,搜索引擎可以通过将生成过程建立在最新检索数据之上来增强 LLMs,这种策略通常被称为检索增强生成(retrieval-augmented generation – RAG )。另一方面, LLMs 也可以通过优化搜索流水线的各个阶段来提升搜索引擎的效果。

搜索流水线通常由三个主要组件组成:索引、第一阶段检索和重排序。 LLMs 可以在每一个阶段发挥作用。在索引阶段, LLMs 可以辅助完成数据准备任务,例如文本清洗、实体抽取,以及通过添加领域知识、同义词或澄清信息来对文档进行增强。在第一阶段检索中, LLMs 可以通过用自然语言重写用户查询来提升检索准确性,或者将查询映射为结构化查询(例如领域特定语言风格的查询 [ DSL-style ] 或 Elasticsearch 查询语言风格的查询 [ ES|QL-style ] )[2]。本文重点讨论这一阶段的查询优化策略。

虽然已有一些研究探讨将 LLMs 用作重排序器 [3],但相关文献仍然相对有限。技术博客中的讨论表明, LLMs 作为重排序器并不总是最优选择,不过这一方向仍然是一个活跃的研究领域 [4,5]。

LLMs 的发展也解锁了传统索引和检索阶段之外的新可能性。例如, LLMs 可以用于生成基于检索数据的自然语言响应( RAG )。用户越来越期待查询能够得到连贯、自然语言形式的回答,同时这些回答还必须可靠,并且明确基于检索到的数据。这种用户期望的转变在集成了 LLMs 的搜索引擎普遍可用之后迅速发生,体现了用户体验的显著提升。能够理解意图、检索数据并综合信息的语言模型,在需要跨多个信息源进行组合的多跳场景中尤为有价值。

在交互式对话搜索界面中应用 LLMs 时,这一点表现得更加明显。这类界面允许用户提交查询、对响应提供反馈或补充澄清,从而在利用对话历史上下文的同时,对结果进行迭代改进。在此基础上,进一步将 LLMs 与自主能力相结合,例如规划、检索、推理和决策,可以促成具备代理特性的搜索系统。这些系统能够基于用户反馈或自我评估不断细化结果,打造更加动态和智能的搜索体验。

最后, LLMs 也被广泛用于搜索工具的开发中,从数据生成到作为向量嵌入和重排序模型的基础架构 [6,7,8]。合成数据生成已经成为训练检索模型的常见步骤,而 LLMs 也越来越多地被用作评审器,用于生成训练和评估所需的标注数据。

%title插图%num
图 1。检索流水线中的 LLM 应用。

查询重写与优化策略

查询重写策略最好通过将用户查询分为两大类来理解:检索型和计算型。

检索型查询

与计算型查询不同,这里的用户意图是信息检索,而不是计算。这类查询是检索算法(例如词法搜索和向量搜索)所处理的标准查询。例如,对于下面的查询:

“What is the origin of life?”

目标是查找提供与该查询相关答案或上下文的文本。

计算型查询

这类查询需要计算、聚合或结构化过滤才能生成答案。它们必须从自然语言翻译为结构化查询语言,例如 Elasticsearch DSL 或 ES|QL。

例如,一个查询:

“What was the average amount spent by customers who placed more than five orders in the last month?”

假设订单和客户的信息可以在某个可用索引中找到,这个查询就不仅仅是简单的文本匹配。它涉及按日期范围过滤、按客户分组、计算订单数量、过滤订单数少于五次的客户,并计算最终的平均值。在这种情况下,LLM 的任务是解析自然语言并生成相应的结构化查询来执行这些计算。

另一个例子是:

“Which universities in Germany have an acceptance rate below 20%, and what is their average tuition fee?”

当不存在包含该特定信息的单一索引文档,而是分别存在包含录取率信息和学费信息的文档时,就会出现这种情况。

在计算型查询中,模型本质上需要将查询拆解为一个可检索的信息查询,以及在检索到数据后可以执行的计算,或者构建一个能够同时完成这两件事的结构化查询。

查询类型 主要机制 示例 查询重写任务
检索型 词法搜索和向量搜索 “What is the origin of life?” 优化查询文本以提高词法或向量匹配效果
计算型 计算、聚合或结构化过滤 “Which universities in Germany have an acceptance rate below 20%, and what is their average tuition fee?” 拆解查询:检索相关数据(大学档案),然后对检索到的文档子集执行计算(平均学费)

设计方法论:基于模板的扩展

本博客的主要关注点是检索型查询。然而,与简单要求 LLM 重写或完全改写查询的标准方法不同,我们采用了基于模板的设计方法。

通过完全改写查询来提升查询文本到查询文本的相关性,对于向量搜索或词汇搜索往往并不简单。这会引入当考虑多种假设时合并搜索结果的复杂性,而且 LLM 常常会偏离用户的原始意图。相反,我们探索通过 ElasticsearchQuery DSL 模板 + prompt 策略扩展原始查询。通过使用特定提示,我们引导 LLM 输出特定文本元素(如实体列表、同义词或伪答案),而不是完全自由生成。这些元素随后被插入到预定义的 Elasticsearch Query DSL 模板(搜索“配方”)中。

这种方法减少了 LLM 的应用范围,使输出更具确定性。在我们的实验中,LLM 只是被提示输出一些文本,然后将其插入模板中。

为了验证该方法,我们对不同的 Elasticsearch 原语进行了有限探索,以识别并 “固定” 一个足够好的搜索模板。这使我们能够测试不同提示策略如何在固定结构内影响相关性,而不是改变结构本身。

虽然本博客关注检索型查询,以及词法提取和语义扩展策略(语言层面起主导作用),但该方法论是灵活的。可以为其他特定检索查询用例设计特定模板,例如处理产品编码,因为相关性标准通常依赖上下文。然而,对于依赖复杂聚合或严格过滤的查询,应视为计算型查询,这类查询需要本博客范围之外的查询优化策略。

查询优化策略

虽然查询优化早于 LLM,但 LLM 在这项任务上表现出色。它们可以被提示应用多种重写策略 [9],例如:

  • 通用查询重述。
  • 伪答案生成。
  • 噪声减少(移除无关文本,提取重要实体)。
  • 实体扩展(同义词、缩写展开或其他相关术语)。
  • 修复拼写错误。
  • 以上方法的组合。

这些技术大多依赖于模型理解用户意图的能力以及对语料库特性的认知。

在接下来的章节中,我们将展示针对信息查询的查询重写实验及其在 Elasticsearch 中的应用。我们会展示最成功的实验,并讨论不太成功的实验。

实验与结果

本文展示的所有实验均使用 Anthropic Claude 3.5 Sonnet 运行。博客中用于评估实验的指标是位置 10 的归一化折扣累积增益(Normalized Discounted Cumulative Gain – NDCG)以及位置 10 和 50 的召回率(Recall)。所有 NDCG召回率分数均使用 pytrec_eval [10] 计算。

我们对信息查询的查询重写任务进行了多种变体实验,并在三个广泛使用的信息检索基准上测量了相关性和召回率的提升:

  • Benchmarking Information Retrieval – BEIR,共 15 个数据集,仅英文 [11]。

  • Multilingual Document Ranking – MLDR,13 种语言 [12]。

  • Multilingual Information Retrieval Across a Continuum of Languages – MIRACL,18 种语言 [13]。

我们主要探索了以下任务:

  • 词汇关键词扩展。

  • 伪答案生成。

  • 让模型决定使用哪种方法或方法组合,包括关键词提取、关键词扩展和伪答案生成。

下文详细说明了我们在每种情况下使用的提示,并扩展了一些尝试的变体。

值得注意的是,在我们评估的数据集中,只有 BEIR 中的四个数据集(NQ、Robust04、Quora 和 MS MARCO)包含真实用户查询,这些查询可以从通用查询重写策略中受益,例如拼写错误修正或查询清理。其余数据集要么是合成生成的(MLDR、MIRACL),要么是人工构建的(大多数 BEIR 数据集)。

词汇关键词扩展

这是我们尝试的第一个任务,并尝试了各种提示以优化结果。我们从最简单的版本开始,提示 LLM 提取相关关键词,而不指定更多细节。

提示 1。

You are a search engine and you want to extract the relevant keyword, codewords or proper names from a query. 
Please, extract them and list them in a comma-separated list. Reply with the list only.

第二次尝试时,我们使用了更明确的提示,要求模型只提供最重要的关键词,并说明这些关键词对我们的用例为什么重要。我们还在这里引入了实体增强的概念,提示模型仅在认为原始查询过短或缺少信息时才进行扩展。

提示 2。

You are a search engine and you want to extract the relevant keyword, codewords or proper names from a query.
            
            Think about the query and select only the very central and necessary entities. 
            They will be used as boosters for the lexical search, so make sure to only extract critical ones. We don't want to boost documents that contain entities that might not be reltgcodeated to the specific context of the query. 
            If, and only if, the query is too short and is missing essential information, see if you can extract synonyms or enrich the query with entities that don't exist in the original query but might help the search.
            
            Return the thinking process inside  tags and the final entities inside  tags.

最后,我们尝试了一个包含更多明确指示和细节的提示,鼓励模型根据原始查询的长度应用不同的技术。

提示 3。

You are a search engine and you want to extract the relevant keyword, codewords or proper names from a query.
            
            Extraction for boosting -  query length independent:
         Think about the query and identify ttgcodehe main context or the information that the user is asking for. 
         Select only the very central and necessary entities. They will be used as boosters for the lexical search, so make sure to only extract critical ones. 
         We don't want to boost documents that contain entities that might not be related to the specific context of the query.

             Enrichment - query length dependent:
       	If the query is shorter than 5 words, then extract the most important entities, but also evaluate whether you can enrich with synonyms or other entities that might enhance recall.
             If the query is larger than 10 words stick to entities that exist in the query
             If you find any initials, return the initials as well as the full words represented by the initials

            Stem-proofing - query length independent:
         Regardless of the query length, return the entities in different forms, in order to overcome stemming miss-matches, provided that the versions of the word are relevant to the query context e.g.: walk, walked, walking.
            
Return the thinking process inside  tags and the final entities, comma separated, inside  tags.
          Make sure you are only returning the most important entities! Don't return entities that are too limiting.	

我们在 BEIR 数据集的子集上对这三种提示变体进行了词汇搜索测试,并比较了相关性和召回率的表现。下表列出了 ArguAna、FiQA-2018、Natural Questions (NQ)、SciDocs、SciFact、TREC-COVID、Touch 2020、NFCorpus、Robust04 数据集的平均结果:

Original query Prompt 1 Prompt 2 Prompt 3
NDCG@10 0.346 0.345 0.356 0.346
Recall@10 0.454 0.453 0.466 0.455

我们考虑原始查询的基线词汇搜索,并将其与使用 LLM 输出实体进行词汇搜索的实验进行比较。结果通过 Elasticsearch bool 查询进行线性组合,其中 must 子句包含原始查询,should 子句包含每个返回的 LLM 词项。(有关布尔查询的更多信息,请参阅 Elasticsearch 文档。)线性组合可表示为:

%title插图%num

其中 n 是为每个查询返回的关键词数量。此处的 Score 指词汇 BM25 分数。查询以原生 Elasticsearch Query DSL 编写,具体见下一节。

重新评分(rescoring),包括提取的关键词贡献,仅应用于前 200 个检索到的文档。

Prompt 2 表现最佳,在前 10 个结果的相关性和召回率上均有提升,提升约 +1 分,而其他 Prompt 的效果较小。我们随后在词汇关键词提取中继续使用 Prompt 2。

我们对部分测试查询返回的关键词进行了可视化检查,并识别出前一节中提到的几种查询优化技术。

拼写纠正 (Typo corrections):

  • Query: when does season 3 of strnger things come out
  • Keywords: Stranger Things, Season 3

噪声减少 (Noise reduction):

  • Query: Evolvability : What Is It and How Do We Get It?
  • Keywords: evolvability

关键词扩展/增强 (Keyword expansion/augmentation):

  • a)
    • Query: Trust-Aware Review Spam Detection
    • Keywords: Trust-Aware, Review Spam Detection, fake reviews, credibility
  • b)
    • Query: Dimensional inconsistencies in code and ROS messages: A study of 5.9M lines of code
    • Keywords: dimensional inconsistencies, code, ROS, Robot Operating System, 5.9M
  • c)
    • Query: low-carb diets
    • Keywords: low-carb, diets, ketogenic, keto, carbohydrate

伪答案生成 (Pseudo-answer generation)

提示 LLM 生成原始查询的伪答案是另一种探索的技术。这种方法在查询重写的背景下已有研究 [9],预计对事实性查询尤其有效,并能发挥关键词增强的优势。对于此方法,我们使用了如下 Prompt:

Prompt 4.

You are a search engine assistant and you want to generate 5 possible replies for a query. 
The replies will be used to boost the search results, in a combined manner with the original query. Make sure that the generated results respect the preferences of most search (lexical or vector) engines, that is, they should be concise, relevant, and cover different aspects of the query.
Return the rewritten replies inside  tags. Separate the replies by the line break symbol.

我们探讨了针对这种提示策略的 LLM 输出示例。为便于比较,也列出了 Prompt 4 提取的实体(Entities)。

为一般知识问题提供回答:

Query: What is the best way to practice web development?

  • Replies:
    • Learn HTML, CSS, and JavaScript fundamentals
    • Build personal projects and create a portfolio
    • Contribute to open-source projects on GitHub
    • Follow online tutorials and take coding courses
    • Practice responsive design and cross-browser compatibility
  • Entities (Prompt 4): development, practice, coding projects, tools

提供可能包含答案的假想文档标题(针对一般知识无法回答的问题):

Query: In your opinion, what is the best classical song of all time?

  • Replies:
    • Best classical compositions ranked by music critics
    • Most popular and influential classical pieces in history
    • Timeless masterpieces from renowned classical composers
    • Iconic classical works that have stood the test of time
    • Top classical music recommendations for beginners and enthusiasts
  • Entities (Prompt 4): classical music, classical composition, symphony, concerto, opera

Query: A description of the history and meaning of the 1st amendment

  • Replies:
    • First Amendment: origins, historical context, and significance in US Constitution
    • Freedom of speech, religion, press, assembly: core principles of 1st Amendment
    • Supreme Court interpretations and landmark cases on First Amendment rights
    • Evolution of First Amendment protections throughout American history
    • Impact and controversies surrounding the First Amendment in modern society
  • Entities (Prompt 4): Amendment, Constitution, Bill of Rights

我们观察到这种策略下 LLM 输出模式的有趣组合。不同类型的查询会有不同的处理方式:

  • 当查询可以基于一般知识直接回答时,LLM 会返回可能的回答。
  • 如果不能,LLM 会 “想象” 用户可能想要的文档类型,并返回类似标题的文档描述作为回答。

两种方法最终都引入了有用且具有创造性的关键词。

让模型选择一种方法

最后,我们进行了实验,使用一种提示(Prompt 5)鼓励模型选择最合适的方法,或者方法的组合,并要求它解释选择背后的理由。我们期望模型能够本质上 “思考” 每个查询如何在搜索上下文中得到改进:

Prompt 5.

You are a search engine and you want to extract the relevant keyword, codewords or proper names from a query.
            There are 3 basic methods to do so:
            1. extract important entities and keywords
            2. create a pseudo answer to the query
            3. expand the initial query with synonyms and related terms
            Given a query, choose a method or a combination of any of them and return the rewritten query inside  tags.
            You can separate the different parts or terms with the line break symbol.
            Also return the rationale behind your choice of methods inside  tags. Why does this query need this type of method?

对于提示 4 和 5 的查询重写实现与提示 2 非常相似。具体来说,LLM 输出被整合到一个 Boolean 查询中,原始查询放在 must 子句中,每个 LLM 生成的 term 都包含在 should 子句中。对于提示 4,LLM 输出的 term 表示一个 pseudo-answer,而对于提示 5,它表示一次 rewrite。

总体而言,在 lexical search 的上下文中,不同提示的性能变化显著,提示 4 和 5 的表现优于提示 2。下表中,LKE 表示使用提示 2 的 lexical keyword extraction,PA 表示使用提示 4 的 pseudo-answer generation,MC 表示 model’s choice,对应提示 5。模型输出按照公式 1 使用。

%title插图%num

在表格的最后一行,分数在 benchmark 级别取平均。它是 BEIR、MLDR 和 MIRACL benchmark 平均分的平均值。pseudo-answer 和 model’s choice 策略在各项指标上表现更好,其中 pseudo-answer 略胜一筹。

我们将在下一部分进一步分析这些 prompting 技术,并获得更多关于 vector search 实验的结果。

我们还展示了仅使用 query rewriting terms 时的 lexical search 结果。在下表中,原始 query 对分数的贡献被完全排除:

%title插图%num

在结果中排除原始 query 分数似乎会平均降低 relevance 性能。在 Recall@50 指标上,pseudo-answer 策略相较于 baseline 有所提升,但增幅小于策略包含原始 query 时的效果。

总体而言,我们建议将 query rewriting terms 与原始 query 结合,以在 lexical search 中在各项指标上获得提升。

大 language models 与小 language models

在本文讨论的大多数结果中,我们使用了 Anthropic 的 Claude 3.5 Sonnet LLM。不过,我们也尝试了一个较小的模型,以评估推理成本如何影响性能。我们在 BEIR 的部分数据集(ArguAna、FiQA-2018、Natural Questions [NQ]、SciDocs、SciFact、TREC-COVID、Touch 2020、NFCorpus、Robust04)上尝试了使用 Anthropic Claude 3.5 Haiku 的 LKE。

Original query LKE with Sonnet LKE with Haiku
NDCG@10 0.346 0.364 0.368
Recall@10 0.454 0.472 0.475

前 10 条结果的 relevance 和 recall 保持不变。虽然这一初步研究并不全面,并且在实施 query optimization 的真实场景中还需要进一步研究,但这些初步结果强烈表明,对于这个特定用例,小 language models (SLMs) 很可能是可行的选择。

下面给出了 Claude 3.5 Sonnet 与 Claude 3.5 Haiku 的对比:

Model Number of parameters Context window Max output Input cost Output cost
Claude 3.5 Sonnet Est. ~175B 200K 8192 tokens $15.00 / million tokens $4.00 / million tokens
Claude 3.5 Haiku Est. ~20B 200K 8192 tokens $3.00 / million tokens $0.80 / million tokens

在企业搜索中,当精度和控制至关重要时,我们探索了将 query rewriting 与现有 search 功能集成的方法。重点是构建在原始 query 基础上的策略,以在不产生高实施成本的情况下提升 relevance。

Elasticsearch 提供了广泛的 search 工具,以应对不同的 search 场景。它支持 lexical 和 vector retrieval,以及 rerankers。我们寻求在 Elasticsearch 中整合 query rewriting 策略的最佳方式,尝试在基础 retrievers 和 hybrid 方法之间进行探索。

在上一节中,我们展示了 lexical search 的结果,并介绍了公式 1 和 2。这些对应以下 Elasticsearch Query DSL 代码:

{
  "query": {
    "bool": {
      "must":  { "match": { "text": "ORIGINAL QUERY" } },
      "should": [
        { "match": { "text": "QR TERM 1" } },
        { "match": { "text": "QR TERM 2" } },
        { "match": { "text": "QR TERM 3" } }
      ]
    }
  }
}

QR TERM 1、2、3 代表 query rewriting term,指 LLM 输出的内容:keywords、pseudo-answers 或其他类型的 replies。

bool query 的作用类似于 terms 的线性组合。关键在于,must clause 强制执行硬性要求,意味着任何未匹配该 clause 的 document 都会被排除在结果之外。相比之下,should clause 起到tgcode score booster 的作用:匹配的 document 得到更高的最终 score,而不匹配的 document 不会被从结果中剔除。

通过反复实验,我们确定了最有效的 query 配置。最初的尝试包括仅使用 LLM 生成的 terms 查询,或者将原始 query 与 LLM terms 进行各种组合。我们观察到,过度依赖 LLM 输出会降低 relevance。最优设置是始终完整包含原始 query,同时仅使用 LLM 输出选择性地提升某些 document 的 ranking,从而持续获得最佳结果。

Dense vector search 作为 base retriever

当使用 vector search 作为 base retriever 时,情况有所不同。业界已经普遍认可,hybrid search(lexical + vector)通过将 dense vector 的语义理解与 BM25 的精确匹配结合起来,可以同时提升 relevance 和 recall。我们的目标是确定,将 query rewriting 应用于 vector retriever 是否能覆盖 hybrid search 修复的同样缺口,或是否能提供额外提升。

在 base retriever 不是 BM25,而是使用 dense vectors 的 K-Nearest Neighbors (KNN) search 的实验中,我们选择探索通过优化的加权线性组合在 relevance 和 recall 上能达到的最大提升。我们优化权重的目的是确保 query rewriting strategies 对性能的影响被独立评估,避免因线性组合选择不当而影响结果。我们在测试集上使用贝叶斯优化(Bayesian Optimization, Optuna14)执行了如 equation 3 所示的优化过程。

%title插图%num

优化过程在用于评估的相同文本查询上进行,以建立潜在性能提升的上限。由于我们只调整一个参数,因此拟合测试数据的可能性很小。我们在下面通过对一些数据集在 train split 上运行优化,并观察性能差异来验证这一假设。

对于 vector search 评估,我们使用两个优化指标:

  • LINEAR NDCG@10 OPTIMIZED(vector_oq, bm25_qr):优化权重以在前 10 个结果中实现最大 NDCG。
  • LINEAR RECALL@50 OPTIMIZED(vector_oq, bm25_qr):优化权重以在前 50 个结果中实现最大 Recall。

在这些指标中,oq 代表 original query,qr 代表 query rewriting。我们包括 Recall@50 是为了评估 query 优化作为 first-stage retriever 的性能,假设搜索结果随后将由 reranker 处理。

为了进行比较,我们还进行了实验,将 original query 的 BM25 分数与 vector search 分数结合。这些组合表示为:

  • LINEAR NDCG@10 OPTIMIZED(vector_oq, bm25_oq)
  • LINEAR RECALL@50 OPTIMIZED(vector_oq, bm25_qr)

在以下表格中的实验中,我们对 BEIR 和 MIRACL 基准使用 multilingual-e5-large [15] dense vector 模型,对 MLDR 基准中长上下文文档使用 Qwen3-0.6B-Embedding [16] 模型进行搜索。

首先,我们验证在 evaluation split 上执行优化而非 training split,结果仍遵循相同趋势。Pseudo-answers prompting strategy 被用来计算 qr 分数。

%title插图%num

我们比较了在 training split 与 evaluation split 上优化时的 Recall@50 分数(针对 MIRACL 和 MLDR),发现两者产生的结果在同一范围内。

在以下表格中,优化使用的是 evaluation split。最后一行的结果与前表一样,是在 benchmark 级别上的平均值。

%title插图%num

%title插图%num
对于完整的 MLDR 数据集,我们比较了在 training split 与 test split 上的优化效果。对于 MIRACL,我们使用了 16 种语言的 training split,并比较了 training split 与 development split(作为通用评估基准,因为 test set 没有公开标签)。我们没有包含 BEIR,因为它的许多数据集缺少 training split,仅用于评估。

%title插图%num

我们省略了 Recall@10 的结果,因为它们与 NDCG@10 的结果非常相似。这些表格显示,在混合搜索中使用 QR terms 替代原始 query 并没有优势。在相关性方面,用 QR 替换原始 query 会使结果下降。在召回率方面,BEIR 和 MIRACL 中有一些提升,但平均分显示,相较于调优良好的混合搜索没有优势。

我们进一步探索了使用倒数排序融合(RRF)的混合搜索,依赖于 Elasticsearch 内置功能。方法 RRF(vector_oq, bm25_qr) 对应的 DSL 代码如下:

{
  "retriever": {
    "rrf": {
      "retrievers": [
        {
          "knn": {
            "field": "dense_vector_field",
            "query_vector": ORIGINAL_QUERY_VECTOR,
            "k": 100,
            "num_candidates": 200
          }
        },
        {
          "standard": {
            "query": {
              "bool": {
                "should": [
                  { "match": { "text": "QR TERM" } },
                  { "match": { "text": "QR TERM" } },
                  { "match": { "text": "QR TERM" } }
                ]
              }
            }
          }
        }
      ],
      "rank_window_size": 500,
      "rank_constant": 20
    }
  },
  "size": 200,
}

对应的基线运行表示为 RRF(vector_oq, bm25_oq)

%title插图%num

将原始 query 替换为 LLM-output terms 来获取 lexical search 分数会在所有情况下平均降低 recall。在相关性方面,我们观察到 BEIR 有轻微提升,而 MIRACL 的 NDCG@10 则显著增加了约 8 点。然而 MLDR 的相关性受到严重影响,使得平均结果在基线运行中整体更高。

到目前为止,我们的探索尚未揭示通过暴露的 query rewriting 方法增强 vector search 性能的明确策略。结合对 lexical search 的探索经验,我们尝试实验包括原始 query 和 query rewriting terms 的 hybrid search 策略。我们专注于 first-stage retrieval 场景,并旨在提升 Recall@50。在下一个实验中,我们尝试使用 RRF 的 hybrid search,其中 lexical 分数是原始 query 的 BM25 分数与 LLM-output terms 的 BM25 分数的优化线性组合。为了建立潜在性能提升的上限,我们使用 Optuna 库 [14] 对查询集进行 Bayesian 优化。

我们将此实验表示为 RRF(vector_oq, LINEAR RECALL50 OPTIMIZED(bm25_oq, bm25_qr))。前一表格中运行的相同基线 RRF(vector_oq, bm25_oq) 在本实验中仍提供了有用的比较。

%title插图%num

本实验并非为优化相关性而设计;然而,为完整性记录了生成的 NDCG@10 分数。使用此方法实现了 recall@50 提升 1–3 个百分点,其中生成 pseudo-answers 的 prompting 策略在各基准测试中最为有效。此策略仅适用于基于常识的 informational queries 或 LLM 拥有必要领域知识的场景。此方法用于确定潜在性能提升的上限。需要注意的是,如此使用完整测试数据优化权重在实际应用中不可行。

PA 被证明是 BEIR 和 MIRACL 中最成功的策略,而 LKE 在 MLDR 中提供了最高的 recall 提升。

First-stage retriever 与 reranking

为了在生产环境中最大化性能,query rewriting 可被视为多阶段 pipeline 的一部分。first-stage retriever 的目标不是优化相关性,而是优化 recall,即确保优质文档进入 reranker 的候选集合。

我们实现了以下 pipeline 配置:

  • Base retrieval: 检索前 200 条文档。
  • Entity boosting: 基于 LLM 提取的实体重新评分(来自 prompt 2)。
  • Pruning: 保留前 50 条文档。
  • Reranking: 对前 50 条文档应用 jina-reranker-v2。

我们比较了使用不同 first-stage 输入的 pipeline 最终结果,包括 base retrievers 与 base retrievers + QR。对于 QR 和 hybrid baseline,我们使用了获得更高 recall 的实验。

  • Lexical 对应使用 BM25 的原始 query。
  • Lexical + QR 对应使用 prompt MC 的实验。
  • Vector 对应使用 vector search 的原始 query。
  • Vector + QR 对应 prompt PA 的实验 LINEAR RECALL50 OPTIMIZED (vector_oq, bm25_qr)。
  • Hybrid 对应 RRF (vector_oq, bm25_oq)。
  • Hybrid + QR 对应 prompt PA 的实验 RRF (vector_oq, LINEAR RECALL50 OPTIMIZED (bm25_oq, bm25_qr))。

%title插图%num

最后一行显示了 BEIR、MLDR 和 MIRACL 的平均结果。

Lexical 和 vector 中的 QR 是通过将分数按公式(1、2)组合并针对 recall 优化来应用的。RRF 被广泛认为是最大化 hybrid search recall 的强标准。我们的结果显示,经过优化的原始 vector 与 QR 的线性组合实际上可以比无法优化的 RRF 配置获得更高的 recall。这表明,在合适的权重下,线性组合在利用 LLM 生成的 query 提升 recall 方面可能比基于排名的融合更有效,因为 RRF 的优化效果有限。

下表显示了 reranking 前后的 NDCG@10 平均值及 recall@50:

%title插图%num

应用 reranking 后,Relevance(NDCG@10)结果有所提升,并且与 recall@50 一起持续改善。

策略域适配

与开放网络搜索不同,企业域(如法律、医疗或内部 wiki)具有通用 LLM 可能无法覆盖的特定词汇。下面讨论几种可用于针对特定域定制所述 QR 策略的方法:

  • 域特定调优:进一步针对小众领域或特定用例调优 query rewriting 指令(prompts)。
  • 上下文学习:使用从知识库检索的少量示例(例如,将前 k 个 BM25 结果附加到 prompt 中,来自快速、低成本的初始搜索)为重写过程提供上下文。
  • LLM + 规则混合方法:结合 LLM 的灵活性与针对特定域术语的确定性规则。
  • 门控式 query rewriting:仅在必要时选择性应用 QR,使用规则、自定义分类器或专用 prompt 和模型检测 query 是否需要针对特定用例优化。
  • 生成优化:针对生成的 query rewriting,不仅扩展查询或上下文以改进检索,还专门用于提升最终 LLM 响应生成的质量。

结论

研究表明,简单的 LLM 驱动 query 优化在现代搜索生态中可以产生积极影响。

关键要点

  • LLM 是提升 lexical search 的好帮手:使用 LLM 来丰富 keywords 或生成 pseudo-answers,在标准 lexical 检索中对 relevance 和 recall 都有稳定提升。
  • Hybrid search 难以超越:在使用 dense vector search 或 hybrid 检索时,简单的 query rewriting terms 提升有限。最佳效果来自使用 QR 来增强现有 hybrid score,而不是替换它们。
  • Pseudo-answers 提升 recall:生成假设性答案(pseudo-answer generation)被证明是在多阶段 pipeline 中最大化 recall 的最有效策略。
  • 结构化指导胜于自由生成:引导 LLM 至关重要。与其让 LLM 自由改写 query,不如提供严格模板(如提取特定实体以匹配 DSL clause),确保输出有价值且不会引入噪声。特定 prompt + DSL template 的组合可用于设计特定的 relevance 用例(如 lexical extraction 与 semantic expansion),并降低出错范围。
  • 小模型也高效:这里探索的策略简单,可使用 SLM 或蒸馏成小型模型有效部署,提供成本效益高的解决方案。

下表包含一些实用指南,说明如何根据具体环境将最成功的 query rewriting 技术整合到搜索 pipeline 中:

现实场景 QR 策略 实现方法
Lexical search Lexical keyword enrichment (prompt 2) 在不迁移到 vector search 的情况下提升搜索性能:使用 LLM 输出(keywords、entities、synonyms)放入 Elasticsearch 的 should clause 来提升匹配扩展 terms 的文档,同时保留原始 query 在 must clause 中。避免仅依赖 QR 生成的 terms,可使用 SLM 降低成本而不影响 QR 性能。
多阶段检索带 reranking Pseudo-answer generation (prompt 4) 在多阶段搜索系统(retriever 后接 reranker)中,使用 pseudo-answers 作为 boosting terms。使用与之前相同的 Elasticsearch should + must clause 结构,在传递给 reranker 评分前检索尽可能多的潜在相关文档。

为了重申我们之前的评论,这些解决方案适用于大多数查询是 retrieval queries 的场景,即相关性不依赖于特定 filtering、aggregations 或其他类型的结构的场景。然而,相同的 template 元策略也可以潜在地适配此类情况。

搜索管道设计中面向任务的调优价值

本次研究的一个更广泛的意义在于,将搜索管道架构视为一组模块化、定义明确的阶段,其中轻量级、面向任务的调整可以显著提升性能,使管道组件可以针对特定检索目标进行调优。此类调优可以包含多种策略,例如:实验 LLM 的 prompt 以针对特定收益(如最大化 recall 或 precision)、参数化 LLM 输出与原始 query 的组合方式(例如 DSL Query template)、或者评估不同 rescoring 策略(如 MMR 或 match_phrase–based query rescoring)对初始候选集(如 top 200 retrieved documents)的影响,并在更高计算成本的 reranking 步骤之前分层应用这些技术。总体而言,这种视角鼓励设计具有明确组件边界和少量可控超参数的管道,以实现针对性的检索结果。此外,尽管我们的实验在通用 IR 场景中显示了可衡量的提升,但我们预计在相关性定义更严格的场景中,这些干预措施的影响会更显著,使基于 template 的方法能够以更可控的方式改善结果。

现代搜索管道中的 LLM 驱动 query 优化

简单的 query rewriting 策略是易于集成、可针对性能提升的解决方案。在已经使用 LLM 的环境中(例如 RAG、对话式接口或 agentic search workflows),额外的 LLM 调用开销被吸收,使延迟问题不再显著。这允许在特定领域或复杂查询类型中,实现显著且针对性的相关性和 recall 改进。

本文讨论的所有策略均由 LLM prompt 与 Elasticsearch Query DSL template 组合而成,因此可以自然地集成到搜索解决方案的应用层。

最后,Elasticsearch 已经开始将 LLM 驱动功能直接整合到搜索体验中,提供了诸如 ES|QL COMPLETION、通过 Elastic Inference Service (EIS) 管理的 LLMs,以及最近在 Elastic Agent Builder 内构建自定义 query rewriting 工具的可能性。

详细的结果表格可以在此找到。

参考文献

  1. Xiong,H.,Bian,J.,Li,Y.,Li,X.,Du,M.,Wang,S.,Yin,D.,& Helal,S.(2024). When search engine services meet large language models: Visions and challenges. arXiv.
  2. Remmey,M.(2024,May 14). NL to SQL architecture alternatives. Azure Architecture Blog. https://techcommunity.microsoft.com/blog/azurearchitectureblog/nl-to-sql-architecture-alternatives/4136387
  3. Abdallah,A.,Piryani,B.,Mozafari,J.,Ali,M.,& Jatowt,A.(2025,August 22). How good are LLM-based rerankers? An empirical analysis of state-of-the-art reranking models. arXiv. arxiv
  4. Joshi,A.,Shi,Z.,Goindani,A.,& Liu,H.(2025,October 22). The case against LLMs as rerankers. Voyage AI. https://blog.voyageai.com/2025/10/22/the-case-against-llms-as-rerankers/
  5. Oosterhuis,H.,Jagerman,R.,Qin,Z.,& Wang,X.(2025,July). Optimizing compound retrieval systems. In Proceedings of the 48th International ACM SIGIR Conference on Research and Development in Information Retrieval (SIGIR ’25) (pp.1–11). ACM. https://doi.org/10.1145/3726302.3730051
  6. Zhang Y,Li M,Long D,Zhang X,Lin H,Yang B,Xie P,Yang A,Liu D,Lin J,Huang F,Zhou J. Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models. arXiv preprint arXiv:2506.05176. 2025. arXiv
  7. Wang L,Yang N,Huang X,Yang L,Majumder R,Wei F. Improving Text Embeddings with Large Language Models. arXiv preprint arXiv:2401.00368. 2024. arXiv
  8. Lee J,Dai Z,Ren X,Chen B,Cer D,Cole JR,et al. Gecko: Versatile Text Embeddings Distilled from Large Language Models. arXiv preprint arXiv:2403.20327. 2024. arxiv
  9. Li,Zhicong;Wang,Jiahao;Jiang,Zhishu;Mao,Hangyu;Chen,Zhongxia;Du,Jiazhen;Zhang,Yuanxing;Zhang,Fuzheng;Zhang,Di;Liu,Yong(2024). DMQR-RAG: Diverse Multi-Query Rewriting for RAG. arXiv preprint arXiv:2411.13154. DOI:10.48550/arXiv.2411.13154. (arxiv)
  10. Van Gysel C,de Rijke M. pytrec_eval: An extremely fast Python interface to trec_eval. In: Proceedings of the 2018 SIGIR Workshop on Reproducibility in Information Retrieval;2018.
  11. Thakur N,Reimers N,Rckl A,Srivastava A,Gurevych I. BEIR: A Heterogeneous Benchmark for Zero-shot Evaluation of Information Retrieval Models. arXiv [cs.IR]. 2021;arXiv:2104.08663. (arxiv)
  12. Chen J,Xiao S,Zhang P,Luo K,Lian D,Liu Z. BGE M3-Embedding: Multi-Linguality, Multi-Functionality, Multi-Granularity Text Embeddings Through Self-Knowledge Distillation. arXiv [cs.CL]. 2024;arXiv:2402.03216. (arxiv)
  13. Zhang X,Thakur N,Ogundepo O,Kamalloo E,Alfonso-Hermelo D,Li X,Liu Q,Rezagholizadeh M,Lin J. MIRACL: A Multilingual Retrieval Dataset Covering 18 Diverse Languages. Trans Assoc Comput Linguistics. 2023;11:1114-1131. (aclanthology.org)
  14. Akiba T,Sano S,Yanase T,Ohta T,Koyama M. Optuna: A Next-generation Hyperparameter Optimization Framework. Proceedings of the 25th ACM SIGKDD International Conference on Knowledge Discovery & Data Mining (KDD ’19). 2019:2623-2631. doi:10.1145/3292500.3330701
  15. Wang L,Yang N,Huang X,Yang L,Majumder R,Wei F. Multilingual E5 Text Embeddings: A Technical Report. arXiv preprint arXiv:2402.05672. Published 2024. Accessed November 18,2025. arxiv
  16. Zhang Y,Li M,Long D,Zhang X,Lin H,Yang B,Xie P,Yang A,Liu D,Lin J,Huang F,Zhou J. Qwen3 Embedding: Advancing Text Embedding and Reranking Through Foundation Models. arXiv preprint arXiv:2506.05176. Published 2025. Accessed November 18,2025. https://arxiv.org/abs/2506.05176 Hugging Face+2GitHub+2

原文:https://www.elastic.co/search-labs/blog/query-rewriting-llm-search-improve

文章来源于互联网:Elasticsearch:用于 LLMs 和搜索引擎的查询重写策略以改善结果

相关推荐: 2026 年的可观测性趋势:成熟度、成本控制与推动业务价值

作者:来自 ElasticElastic Observability Team 过去几年,可观测性领域经历了根本性变革。在最近由 Dimensional Research 进行、Elastic 赞助的报告《2026 年的可观测性格局:平衡成本与创新》中,对 5…