Elasticsearch:同义词在 RAG 中重要吗?

news2025/2/20 12:15:11

作者:来自 Elastic Jeffrey Rengifo 及 Tomás Murúa

探索 RAG 应用程序中 Elasticsearch 同义词的功能。

同义词允许我们使用具有相同含义的不同词语在文档中搜索,以确保用户无论使用什么确切的词语都能找到他们所寻找的内容。你可能会认为,由于 RAG 应用程序使用语义/向量搜索,同义词功能的一部分已经被同义词涵盖(因为根据定义,同义词是语义相关的词)。

这是真的吗?语义搜索真的能取代同义词吗?在本文中,我们将分析在 RAG 应用程序中使用同义词的影响。

步骤

  • 配置端点
  • 配置同义词
  • 索引文档
  • 语义搜索
  • 同义词和 RAG

配置推理端点

对于这个例子,我们将在 HR 环境中实现带有和不带有同义词的 RAG(Retrieval-Augmented Generation - 检索增强生成)系统。我们将使用术语 PTO(Paid Time Off - 带薪休假)的变体(如 “vacation” 或 “holiday”)为不同的文档编制索引。然后我们将配置同义词来展示这些关系如何提高搜索的相关性和准确性。

首先,让我们通过在 Kibana DevTools 中运行以下命令,使用带有推理 API(inference api) 的 ELSER 模型创建一个端点:

PUT _inference/sparse_embedding/code-wave_inference
{
  "service": "elasticsearch",
  "service_settings": {
    "num_allocations": 1,
    "num_threads": 1
  }
}

配置同义词

Elasticsearch 中的同义词是什么?

在 Elasticsearch 中,同义词(synonyms)是具有相同或相似含义的单词或短语,存储为同义词集,可以作为文件或通过 API 进行管理。它们允许用户找到相关信息,即使他们使用不同的术语来指代同一概念。

因此,例如,如果我们创建一组同义词,其中 “holiday” 和 “vacation” 是 “Paid Time Off” 的同义词,当员工搜索其中任何一个词时,他们就会找到与所有词相关的文档。

你可以在这篇文章中阅读有关它们的更多信息。

让我们使用同义词 API(synonyms API:) 创建一组同义词:

PUT _synonyms/code-wave_synonyms
{
  "synonyms_set": [
    {
      "synonyms": "holidays, paid time off"
    }
  ]
}

值得注意的是,同义词集必须先进行配置,然后才能应用于索引。

现在,让我们定义数据的设置和映射:

PUT /code-wave_index
{
  "settings": {
    "analysis": {
      "filter": {
        "synonyms_filter": {
          "type": "synonym_graph",
          "synonyms_set": "code-wave_synonyms",
          "updateable": true
        }
      },
      "analyzer": {
        "my_search_analyzer": {
          "type": "custom",
          "tokenizer": "standard",
          "filter": [
            "lowercase",
            "synonyms_filter"
          ]
        }
      }
    }
  },
  "mappings": {
    "properties": {
      "text_field": {
        "type": "text",
        "analyzer": "standard",
        "copy_to": "semantic_field",
        "fields": {
          "synonyms": {
            "type": "text",
            "analyzer": "standard",
            "search_analyzer": "my_search_analyzer"
          }
        }
      },
      "semantic_field": {
        "type": "semantic_text",
        "inference_id": "code-wave_inference"
      }
    }
  }
}

我们将使用 semantic_text 字段进行语义搜索,并使用 synonyms graph token filter 来处理多词同义词。

我们还创建了 text_field.synonym 版本和 text_field 版本的字段(可以针对这两种不同的类型进行搜索。请注意的是这两个类型都是 text 类型),以便更好地控制如何使用或不考虑同义词来查询字段。

最后,我们使用 copy_to 将 text_field 的值复制到该字段的 semantic_text 版本,以实现全文和语义查询。

索引文档

我们现在将使用批量 API 索引我们的文档:

POST _bulk
{"index":{"_index":"code-wave_index","_id":"1"}}
{"semantic_field":"Paid time off: All employees receive 20 days of paid vacation annually, with additional days earned for tenure milestones.","text_field":"Paid time off: All employees receive 20 days of paid vacation annually, with additional days earned for tenure milestones."}
{"index":{"_index":"code-wave_index","_id":"2"}}
{"semantic_field":"Holidays: Paid public holidays recognized each calendar year.","text_field":"Holidays: Paid public holidays recognized each calendar year."}
{"index":{"_index":"code-wave_index","_id":"3"}}
{"semantic_field":"Sick leave: Paid sick leave of up to 15 days per year.","text_field":"Sick leave: Paid sick leave of up to 15 days per year."}
{"index":{"_index":"code-wave_index","_id":"4"}}
{"semantic_field":"Holidays sale: Enjoy discounts up to 50% during our exclusive holidays sale event!","text_field":"Holidays sale: Enjoy discounts up to 50% during our exclusive holidays sale event!"}
{"index":{"_index":"code-wave_index","_id":"5"}}
{"semantic_field":"Holidays recipes: Try our top 10 holidays dessert recipes, perfect for family gatherings and celebrations.","text_field":"Holidays recipes: Try our top 10 holidays dessert recipes, perfect for family gatherings and celebrations."}
{"index":{"_index":"code-wave_index","_id":"6"}}
{"semantic_field":"Holidays travel: Find the best deals for your holidays flights and accommodations this season.","text_field":"Holidays travel: Find the best deals for your holidays flights and accommodations this season."}
{"index":{"_index":"code-wave_index","_id":"7"}}
{"semantic_field":"Holidays music: Stream your favorite holidays classics and discover new seasonal hits.","text_field":"Holidays music: Stream your favorite holidays classics and discover new seasonal hits."}
{"index":{"_index":"code-wave_index","_id":"8"}}
{"semantic_field":"Holidays decorations: Our store offers a wide range of holidays decorations to make your home festive.","text_field":"Holidays decorations: Our store offers a wide range of holidays decorations to make your home festive."}
{"index":{"_index":"code-wave_index","_id":"9"}}
{"semantic_field":"Holidays movies: Check out our list of must-watch holidays movies for cozy winter nights.","text_field":"Holidays movies: Check out our list of must-watch holidays movies for cozy winter nights."}
{"index":{"_index":"code-wave_index","_id":"10"}}
{"semantic_field":"Holidays festival: Join us at the city's annual holidays festival featuring lights, music, and local food.","text_field":"Holidays festival: Join us at the city's annual holidays festival featuring lights, music, and local food."}
{"index":{"_index":"code-wave_index","_id":"11"}}
{"semantic_field":"Holidays weather: Stay updated with our holidays weather forecast to plan your activities.","text_field":"Holidays weather: Stay updated with our holidays weather forecast to plan your activities."}
{"index":{"_index":"code-wave_index","_id":"12"}}
{"semantic_field":"Holidays gift guide: Browse our ultimate holidays gift guide for everyone on your list.","text_field":"Holidays gift guide: Browse our ultimate holidays gift guide for everyone on your list."}
{"index":{"_index":"code-wave_index","_id":"13"}}
{"semantic_field":"Holidays traditions: Explore unique holidays traditions celebrated around the world.","text_field":"Holidays traditions: Explore unique holidays traditions celebrated around the world."}

我们现在就可以开始搜索了!但首先,让我们通过搜索 holidays 来确保同义词有效:

GET code-wave_index/_search
{
  "_source": {
    "excludes": [
      "*embeddings",
      "*chunks"
    ]
  },
  "query": {
    "multi_match": {
      "query": "holidays",
      "fields": [
        "text_field^10",
        "text_field.synonyms^0.6"
      ]
    }
  }
}

我们对 boost 进行调整,使同义词的得分低于原始单词。

检查响应:

{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 12,
      "relation": "eq"
    },
    "max_score": 5.2014494,
    "hits": [
      {
        "_index": "code-wave_index",
        "_id": "2",
        "_score": 3.0596757,
        "_source": {
          "text_field": "Holidays: Paid public holidays recognized each calendar year.",
          "semantic_field": {
            "inference": {
              "inference_id": "code-wave_inference",
              "model_settings": {
                "task_type": "sparse_embedding"
              }
            },
            "text": "Holidays: Paid public holidays recognized each calendar year."
          }
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "1",
        "_score": 3.023004,
        "_source": {
          "text_field": "Paid time off: All employees receive 20 days of paid vacation annually, with additional days earned for tenure milestones.",
          "semantic_field": {
            "inference": {
              "inference_id": "code-wave_inference",
              "model_settings": {
                "task_type": "sparse_embedding"
              }
            },
            "text": "Paid time off: All employees receive 20 days of paid vacation annually, with additional days earned for tenure milestones."
          }
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "13",
        "_score": 2.9230676,
        "_source": {
          "text_field": "Holidays traditions: Explore unique holidays traditions celebrated around the world.",
          "semantic_field": {
            "inference": {
              "inference_id": "code-wave_inference",
              "model_settings": {
                "task_type": "sparse_embedding"
              }
            },
            "text": "Holidays traditions: Explore unique holidays traditions celebrated around the world."
          }
        }
      },
      ...
    ]
  }
}

我们可以看到,当我们搜索 “holidays” 时,第二个文档有同义词:“Paid Time Off”。

混合搜索

混合搜索使我们能够将全文和语义搜索查询的结果组合成一个规范化的结果集,方法是使用 RRF(Reciprocal Rank Fusion - 倒述排序融合)来平衡来自不同检索器的分数。

GET code-wave_index/_search
{
  "_source": "text_field",
  "retriever": {
    "rrf": {
      "retrievers": [
        {
          "standard": {
            "query": {
              "nested": {
                "path": "semantic_field.inference.chunks",
                "query": {
                  "sparse_vector": {
                    "inference_id": "code-wave_inference",
                    "field": "semantic_field.inference.chunks.embeddings",
                    "query": "holidays"
                  }
                }
              }
            }
          }
        },
        {
          "standard": {
            "query": {
              "multi_match": {
                "query": "holidays",
                "fields": [
                  "text_field.synonyms"
                ]
              }
            }
          }
        }
      ]
    }
  }
}

回复:

{
  "took": 11,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 13,
      "relation": "eq"
    },
    "max_score": 0.03175403,
    "hits": [
      {
        "_index": "code-wave_index",
        "_id": "7",
        "_score": 0.03175403,
        "_source": {
          "text_field": "Holidays music: Stream your favorite holidays classics and discover new seasonal hits."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "13",
        "_score": 0.031257633,
        "_source": {
          "text_field": "Holidays traditions: Explore unique holidays traditions celebrated around the world."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "4",
        "_score": 0.031009614,
        "_source": {
          "text_field": "Holidays sale: Enjoy discounts up to 50% during our exclusive holidays sale event!"
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "2",
        "_score": 0.030834913,
        "_source": {
          "text_field": "Holidays: Paid public holidays recognized each calendar year."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "6",
        "_score": 0.03079839,
        "_source": {
          "text_field": "Holidays travel: Find the best deals for your holidays flights and accommodations this season."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "11",
        "_score": 0.02964427,
        "_source": {
          "text_field": "Holidays weather: Stay updated with our holidays weather forecast to plan your activities."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "5",
        "_score": 0.029418126,
        "_source": {
          "text_field": "Holidays recipes: Try our top 10 holidays dessert recipes, perfect for family gatherings and celebrations."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "12",
        "_score": 0.028991597,
        "_source": {
          "text_field": "Holidays gift guide: Browse our ultimate holidays gift guide for everyone on your list."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "1",
        "_score": 0.016393442,
        "_source": {
          "text_field": "Paid time off: All employees receive 20 days of paid vacation annually, with additional days earned for tenure milestones."
        }
      },
      {
        "_index": "code-wave_index",
        "_id": "10",
        "_score": 0.016393442,
        "_source": {
          "text_field": "Holidays festival: Join us at the city's annual holidays festival featuring lights, music, and local food."
        }
      }
    ]
  }
}

该查询将返回语义和文本相关的文档。

同义词和 RAG

在本节中,我们将评估同义词和语义搜索如何改进 RAG 系统中的查询。我们将使用一个关于休息日的常见问题作为此示例:

How many vacation days are provided for holidays?

对于这个问题,我们对文档 1 中的信息感兴趣。文档 2 更接近我们想要的结果,但并不精确。当我们不使用同义词进行搜索时,我们将得到此结果。我们来看看它们的内容:

  • [1] Paid time off: All employees receive 20 days of paid vacation annually, with additional days earned for tenure milestones.
  • [2] Holidays: Paid public holidays recognized each calendar year.

这两个文档都包含与休息日(days off)相关的信息,但只有文档 2 特别使用了术语 “holidays”,因此我们可以测试同义词和语义搜索在 Playground 中的工作方式。

你可以从 Search>Playground 访问 Playground。从那里,你需要配置你想要使用的 LLM 并选择我们已经创建的索引作为上下文发送。你可以在此处阅读有关 Playground 及其配置的更多信息

配置完 Playground 后,如果我们点击查询按钮,我们可以看到同义词已被停用:

对于每个问题,我们会将前一个查询的前三个结果发送给 LLM,作为上下文:

现在,让我们向 Playground 提出问题并检查停用同义词后的结果:

由于前三个搜索结果中没有列出说明员工每年可享受多少假期的文件,因此 LLM 无法回答这个问题。在这种情况下,最接近的结果在文档 [2] 中。

注意:通过点击 “Snippet”,我们可以看到答案在 Elasticsearch 中的具体内容。

让我们清理聊天记录,激活同义词并再次提出同样的问题:

请注意,当你启用 semantic_text 字段和 text 字段时,Playground 将自动生成混合搜索查询:

让我们重复一下这个问题,现在激活同义词:

现在,答案确实包含了我们正在搜索的文档,因为同义词允许将文档 [1] 发送到 LLM。

结论

在本文中,我们发现同义词是搜索系统的基本组成部分,即使在使用语义搜索时也不一定涵盖同义词功能。

同义词允许我们根据用例控制要提升的文档,并通过调整相关性来提高准确性。另一方面,语义搜索对于 recall 很有用,这意味着它可以引入潜在的相关结果,而无需我们为每个相关术语添加同义词。

通过混合搜索,我们可以同时进行同义词和语义搜索,实现两全其美的效果。使用 Playground,如果我们选择语义和文本字段的组合作为搜索字段,它将自动为我们构建混合查询。

想要获得 Elastic 认证吗?了解下一期 Elasticsearch 工程师培训何时举行!

Elasticsearch 包含许多新功能,可帮助你为你的用例构建最佳的搜索解决方案。深入了解我们的示例笔记本以了解更多信息,开始免费云试用,或立即在本地机器上试用 Elastic。

原文:Are synonyms important in RAG? - Elasticsearch Labs

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2298047.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

React 低代码项目:组件设计

React 低代码项目:组件设计 Date: February 6, 2025 React表单组件 **目标:**使用 Ant Design 表单组件,开发登录、注册、搜索功能 内容: 使用 React 表单组件、受控组件使用 Ant Design 表单组件使用 表单组件的校验和错误提…

从0到1的回溯算法学习

回溯算法 前言这个算法能帮我们做啥算法模版力扣例题( 以下所有题目代码都经过力扣认证 )形式一 元素无重不可复选46.全排列思路详解代码 77.组合思路详解代码 78.子集思路详解代码 形式二 元素可重不可复选思考(deepseek)核心思想…

AVL树:高效平衡的二叉搜索树

🌟 快来参与讨论💬,点赞👍、收藏⭐、分享📤,共创活力社区。🌟 引言🤔 在数据结构的奇妙世界里,二叉搜索树(BST)原本是查找数据的好帮手。想象一下…

RHCA练习5:配置mysql8.0使用PXC实现高可用

准备4台CentOS7的虚拟机(CentOS7-1、CentOS7-2、CentOS7-3、CentOS7-4) 备份原yum源的配置: mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup 更换阿里云镜像YUM源: curl -o /etc/yum.repos.…

Java 大视界 -- 边缘计算与 Java 大数据协同发展的前景与挑战(85)

💖亲爱的朋友们,热烈欢迎来到 青云交的博客!能与诸位在此相逢,我倍感荣幸。在这飞速更迭的时代,我们都渴望一方心灵净土,而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识,也…

机器学习 - 理论和定理

在机器学习中,有一些非常有名的理论或定理,对理解机器学习的内在特性非常有帮助。本文列出机器学习中常用的理论和定理,并举出对应的举例子加以深化理解,有些理论比较抽象,我们可以先记录下来,慢慢啃&#…

2025.2.11——一、[极客大挑战 2019]PHP wakeup绕过|备份文件|代码审计

题目来源:BUUCTF [极客大挑战 2019]PHP 目录 一、打开靶机,整理信息 二、解题思路 step 1:目录扫描、爆破 step 2:代码审计 1.index.php 2.class.php 3.flag.php step 3:绕过__wakeup重置 ​编辑 三、小结…

Vivado生成edif网表及其使用

介绍如何在Vivado中将模块设为顶层,并生成相应的网表文件(Verilog文件和edif文件),该过程适用于需要将一个模块作为顶层设计进行综合,并生成用于其他工程中的网表文件的情况。 例如要将fpga_top模块制作成网表给其它工…

JAVA生产环境(IDEA)排查死锁

使用 IntelliJ IDEA 排查死锁 IntelliJ IDEA 提供了强大的工具来帮助开发者排查死锁问题。以下是具体的排查步骤: 1. 编写并运行代码 首先,我们编写一个可能导致死锁的示例代码: public class DeadlockExample {private static final Obj…

AI学习记录 - 最简单的专家模型 MOE

代码 import torch import torch.nn as nn import torch.nn.functional as F from typing import Tupleclass BasicExpert(nn.Module):# 一个 Expert 可以是一个最简单的, linear 层即可# 也可以是 MLP 层# 也可以是 更复杂的 MLP 层(active function 设…

【2025深度学习系列专栏大纲:深入探索与实践深度学习】

第一部分:深度学习基础篇 第1章:深度学习概览 1.1 深度学习的历史背景与发展轨迹 1.2 深度学习与机器学习、传统人工智能的区别与联系 1.3 深度学习的核心组件与概念解析 神经网络基础 激活函数的作用与类型 损失函数与优化算法的选择 1.4 深度学习框架简介与选择建议 第2…

数据治理双证通关经验分享 | CDGA/CDGP备考全指南

历经1个月多的系统准备,本人于2024年顺利通过DAMA China的CDGA(数据治理工程师)和CDGP(数据治理专家)双认证。现将备考经验与资源体系化整理,助力从业者高效通关。 🌟 认证价值与政策背景 根据…

亚信安全正式接入DeepSeek

亚信安全致力于“数据驱动、AI原生”战略,早在2024年5月,推出了“信立方”安全大模型、安全MaaS平台和一系列安全智能体,为网络安全运营、网络安全检测提供AI技术能力。自2024年12月DeepSeek-V3发布以来,亚信安全人工智能实验室利…

unet学习(初学者 自用)

代码解读 | 极简代码遥感语义分割,结合GDAL从零实现,以U-Net和建筑物提取为例 以上面链接中的代码为例,逐行解释。 训练 unet的train.py如下: import torch.nn as nn import torch import gdal import numpy as np from torch…

CCFCSP第34次认证第一题——矩阵重塑(其一)

第34次认证第一题——矩阵重塑(其一) 官网链接 时间限制: 1.0 秒 空间限制: 512 MiB 相关文件: 题目目录(样例文件) 题目背景 矩阵(二维)的重塑(reshap…

探索B-树系列

🌈前言🌈 本文将讲解B树系列,包含 B-树,B树,B*树,其中主要讲解B树底层原理,为什么用B树作为外查询的数据结构,以及B-树插入操作并用代码实现;介绍B树、B*树。 &#x1f4…

GRN前沿:DeepMCL:通过深度多视图对比学习从单细胞基因表达数据推断基因调控网络

1.论文原名:Inferring gene regulatory networks from single-cell gene expression data via deep multi-view contrastive learning 2.发表日期:2023 摘要: 基因调控网络(GRNs)的构建对于理解细胞内复杂的调控机制…

Linux 内核架构入门:从基础概念到面试指南*

1. 引言 Linux 内核是现代操作系统的核心,负责管理硬件资源、提供系统调用、处理进程调度等功能。对于初学者来说,理解 Linux 内核的架构是深入操作系统开发的第一步。本篇博文将详细介绍 Linux 内核的架构体系,结合硬件、子系统及软件支持的…

【竞技宝】PGL瓦拉几亚S4预选:Tidebound2-0轻取spiky

北京时间2月13日,DOTA2的PGL瓦拉几亚S4预选赛继续进行,昨日进行的中国区预选赛胜者组首轮Tidebound对阵的spiky比赛中,以下是本场比赛的详细战报。 第一局: 首局比赛,spiky在天辉方,Tidebound在夜魇方。阵容方面,spiky点出了幻刺、火枪、猛犸、小强、巫妖,Tidebound则是拿到飞…

EasyRTC智能硬件:小体积,大能量,开启音视频互动新体验

在万物互联的时代,智能硬件正以前所未有的速度融入我们的生活。然而,受限于硬件性能和网络环境,许多智能硬件在音视频互动体验上仍存在延迟高、卡顿、回声等问题,严重影响了用户的使用体验。 EasyRTC智能硬件,凭借其强…