Elasticsearch:使用 ELSER v2 文本扩展进行语义搜索
Elastic 提供了一个强大的 ELSER 供我们进行语义搜索。ELSER 是一种稀疏向量的搜索方法。我们无需对它做任何的微调及训练。它是一种 out-of-domain 的模型。目前它仅对英文进行支持。希望将来它能对其它的语言支持的更好。更多关于 ELSER 的知识,请参阅文章 “Elasticsearch:使用 ELSER 释放语义搜索的力量:Elastic Learned Sparse EncoderR”。在本文中,我们将使用第二版的 ELSER 来进行语义搜索。我将使用 Jupyter notebook 演示如何使用 ELSER 模型 .elser_model_2 模型,该模型提供了更高的检索精度。
如果你已使用 ELSER 模型 .elser_model_1 设置索引,并且想要升级到 ELSER v2 模型 - .elser_model_2,请按照文章升级索引以使用 elser 模型的说明进行操作 来进行升级。
安装
如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考文章:
安装 Elasticsearch 及 Kibana
如果你还没有安装好自己的 Elasticsearch 及 Kibana,那么请参考一下的文章来进行安装:
-
如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch
-
Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 Kibana
在安装的时候,请选择 Elastic Stack 8.x 进行安装。在安装的时候,我们可以看到如下的安装信息:
为了能够上传向量模型,我们必须订阅白金版或试用。
Python
我们需要安装相应的 Elasticsearch 包:
$ pwd
/Users/liuxg/python/elser
$ pip3 install elasticsearch -qU
$ pip3 list | grep elasticseach
elasticsearch 8.11.1
rag-elasticsearch 0.0.1 /Users/liuxg/python/rag-elasticsearch/my-app/packages/rag-elasticsearch
环境变量
在启动 Jupyter 之前,我们设置如下的环境变量:
export ES_USER="elastic"
export ES_PASSWORD="yarOjyX5CLqTsKVE3v*d"
export ES_ENDPOINT="localhost"
拷贝 Elasticsearch 证书
我们把 Elasticsearch 的证书拷贝到当前的目录下:
$ pwd
/Users/liuxg/python/elser
$ cp ~/elastic/elasticsearch-8.11.0/config/certs/http_ca.crt .
$ lsfind_books_about_christmas_without_searching_for_christmas.ipynb
Chatbot with LangChain conversational chain and OpenAI.ipynb
ElasticKnnSearch.ipynb
ElasticVectorSearch.ipynb
ElasticsearchStore.ipynb
Mental Health FAQ.ipynb
Multilingual semantic search.ipynb
NLP text search using hugging face transformer model.ipynb
Question Answering with Langchain and OpenAI.ipynb
RAG-langchain-elasticsearch.ipynb
Semantic search - ELSER.ipynb
Semantic search quick start.ipynb
book_summaries_1000_chunked.json
books.json
data.json
http_ca.crt
lib
sample_data.json
upgrading-index-to-use-elser.ipynb
vector_search_implementation_guide_api.ipynb
workplace-docs.json
在上面,我们把 Elasticsearch 的证书 http_ca.crt 拷贝到当前的目录下。
运行应用
连接到 Elasticsearch
from elasticsearch import Elasticsearch
import oselastic_user=os.getenv('ES_USER')
elastic_password=os.getenv('ES_PASSWORD')
elastic_endpoint=os.getenv("ES_ENDPOINT")url = f"https://{elastic_user}:{elastic_password}@{elastic_endpoint}:9200"
es = Elasticsearch(url, ca_certs = "./http_ca.crt", verify_certs = True)print(es.info())
从上面的输出中,我们可以看到,连接到 Elasticsearch 是成功的。
如果你对如何连接到 Elasticsearch 还不是很熟悉的话,那么请阅读文章 “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x”。
下载及部署 ELSER 模型
下面,我们来尝试通过软件的方式来针对 ELSER 进行手动部署。在此示例中,我们将下载 ELSER 模型并将其部署到 ML 节点中。 确保你有一个 ML 节点才能运行 ELSER 模型。如果你之前已经下载过,我们通过软件的方式来进行删除,并安装最新的模型:
# delete model if already downloaded and deployed
try:es.ml.delete_trained_model(model_id=".elser_model_2",force=True)print("Model deleted successfully, We will proceed with creating one")
except exceptions.NotFoundError:print("Model doesn't exist, but We will proceed with creating one")# Creates the ELSER model configuration. Automatically downloads the model if it doesn't exist.
es.ml.put_trained_model(model_id=".elser_model_2",input={"field_names": ["text_field"]})
我们回到 Kibana 的界面中进行查看:
上面显示, .elser_model_2 正在被下载。我们需要等一段时间才能下载完毕。这个依赖于你自己的网路速度。使用以下命令检查模型下载的状态。
while True:status = es.ml.get_trained_models(model_id=".elser_model_2",include="definition_status")if (status["trained_model_configs"][0]["fully_defined"]):print("ELSER Model is downloaded and ready to be deployed.")breakelse:print("ELSER Model is downloaded but not ready to be deployed.")time.sleep(5)
在 Kibana 中显示的状态为:
下载完模型后,我们可以将模型部署到 ML 节点中。 使用以下命令部署模型。
import time# Start trained model deployment if not already deployed
es.ml.start_trained_model_deployment(model_id=".elser_model_2",number_of_allocations=1,wait_for="starting"
)
如上所示,在 Kibana 的界面中,我们可以看到 .elser_model_2 已经被成功地部署了。我们可以使用如下的代码来查看状态:
while True:status = es.ml.get_trained_models_stats(model_id=".elser_model_2",)if (status["trained_model_stats"][0]["deployment_stats"]["state"] == "started"):print("ELSER Model has been successfully deployed.")breakelse:print("ELSER Model is currently being deployed.")time.sleep(5)
摄入一些文档到 Elasticsearch
为了在我们的 Elasticsearch 中使用 ELSER,我们需要创建一个包含运行 ELSER 模型的推理处理器的摄取管道。 让我们使用 put_pipeline 方法添加该管道。
es.ingest.put_pipeline(id="elser-ingest-pipeline", description="Ingest pipeline for ELSER",processors=[{"inference": {"model_id": ".elser_model_2","input_output": [{"input_field": "plot","output_field": "plot_embedding"}]}}]
)
让我们记下该 API 调用中的一些重要参数:
- inference:使用机器学习模型执行推理的处理器。
- model_id:指定要使用的机器学习模型的 ID。 在此示例中,模型 ID 设置为 .elser_model_2。
- input_output:指定输入和输出字段
- input_field:创建稀疏向量表示的字段名称。
- output_field:包含推理结果的字段名称。
创建索引
要在索引时使用 ELSER 模型,我们需要创建支持 text_expansion 查询的索引映射。 该映射包括一个 sparse_vector 类型的字段,用于处理我们感兴趣的特征向量。 该字段包含 ELSER 模型根据输入文本创建的 token-weight 对。
让我们使用我们需要的映射创建一个名为 elser-example-movies 的索引。
es.indices.delete(index="elser-example-movies", ignore_unavailable=True)
es.indices.create(index="elser-example-movies",settings={"index": {"default_pipeline": "elser-ingest-pipeline"}},mappings={"properties": {"plot": {"type": "text","fields": {"keyword": {"type": "keyword","ignore_above": 256}}},"plot_embedding": { "type": "sparse_vector" }}}
)
摄入文档
让我们插入 12 部电影的示例数据集。
如果出现错误,请检查模型是否已部署并且在 ML 节点中可用。 在较新版本的 Elastic Cloud 中,ML 节点是自动缩放的,并且 ML 节点可能尚未准备好。 等待几分钟,然后重试。在进行下面的运行之前,我们先在项目的根目录下创建如下的一个 movies.json 文档:
movies.json
[{"title": "Pulp Fiction","runtime": "154","plot": "The lives of two mob hitmen, a boxer, a gangster and his wife, and a pair of diner bandits intertwine in four tales of violence and redemption.","keyScene": "John Travolta is forced to inject adrenaline directly into Uma Thurman's heart after she overdoses on heroin.","genre": "Crime, Drama","released": "1994"},{"title": "The Dark Knight","runtime": "152","plot": "When the menace known as the Joker wreaks havoc and chaos on the people of Gotham, Batman must accept one of the greatest psychological and physical tests of his ability to fight injustice.","keyScene": "Batman angrily responds 'I’m Batman' when asked who he is by Falcone.","genre": "Action, Crime, Drama, Thriller","released": "2008"},{"title": "Fight Club","runtime": "139","plot": "An insomniac office worker and a devil-may-care soapmaker form an underground fight club that evolves into something much, much more.","keyScene": "Brad Pitt explains the rules of Fight Club to Edward Norton. The first rule of Fight Club is: You do not talk about Fight Club. The second rule of Fight Club is: You do not talk about Fight Club.","genre": "Drama","released": "1999"},{"title": "Inception","runtime": "148","plot": "A thief who steals corporate secrets through the use of dream-sharing technology is given the inverse task of planting an idea into thed of a C.E.O.","keyScene": "Leonardo DiCaprio explains the concept of inception to Ellen Page by using a child's spinning top.","genre": "Action, Adventure, Sci-Fi, Thriller","released": "2010"},{"title": "The Matrix","runtime": "136","plot": "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.","keyScene": "Red pill or blue pill? Morpheus offers Neo a choice between the red pill, which will allow him to learn the truth about the Matrix, or the blue pill, which will return him to his former life.","genre": "Action, Sci-Fi","released": "1999"},{"title": "The Shawshank Redemption","runtime": "142","plot": "Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","keyScene": "Andy Dufresne escapes from Shawshank prison by crawling through a sewer pipe.","genre": "Drama","released": "1994"},{"title": "Goodfellas","runtime": "146","plot": "The story of Henry Hill and his life in the mob, covering his relationship with his wife Karen Hill and his mob partners Jimmy Conway and Tommy DeVito in the Italian-American crime syndicate.","keyScene": "Joe Pesci's character Tommy DeVito shoots young Spider in the foot for not getting him a drink.","genre": "Biography, Crime, Drama","released": "1990"},{"title": "Se7en","runtime": "127","plot": "Two detectives, a rookie and a veteran, hunt a serial killer who uses the seven deadly sins as his motives.","keyScene": "Brad Pitt's character David Mills shoots John Doe after he reveals that he murdered Mills' wife.","genre": "Crime, Drama, Mystery, Thriller","released": "1995"},{"title": "The Silence of the Lambs","runtime": "118","plot": "A young F.B.I. cadet must receive the help of an incarcerated and manipulative cannibal killer to help catch another serial killer, a madman who skins his victims.","keyScene": "Hannibal Lecter explains to Clarice Starling that he ate a census taker's liver with some fava beans and a nice Chianti.","genre": "Crime, Drama, Thriller","released": "1991"},{"title": "The Godfather","runtime": "175","plot": "An organized crime dynasty's aging patriarch transfers control of his clandestine empire to his reluctant son.","keyScene": "James Caan's character Sonny Corleone is shot to death at a toll booth by a number of machine gun toting enemies.","genre": "Crime, Drama","released": "1972"},{"title": "The Departed","runtime": "151","plot": "An undercover cop and a mole in the police attempt to identify each other while infiltrating an Irish gang in South Boston.","keyScene": "Leonardo DiCaprio's character Billy Costigan is shot to death by Matt Damon's character Colin Sullivan.","genre": "Crime, Drama, Thriller","released": "2006"},{"title": "The Usual Suspects","runtime": "106","plot": "A sole survivor tells of the twisty events leading up to a horrific gun battle on a boat, which began when five criminals met at a seemingly random police lineup.","keyScene": "Kevin Spacey's character Verbal Kint is revealed to be the mastermind behind the crime, when his limp disappears as he walks away from the police station.","genre": "Crime, Mystery, Thriller","released": "1995"}
]
$ pwd
/Users/liuxg/python/elser
$ ls Install\ ELSER.ipynb
Install ELSER.ipynb
$ ls movies.json
movies.json
import json
from elasticsearch import helperswith open('movies.json') as f:data_json = json.load(f)# Prepare the documents to be indexed
documents = []
for doc in data_json:documents.append({"_index": "elser-example-movies","_source": doc,})# Use helpers.bulk to index
helpers.bulk(es, documents)print("Done indexing documents into `elser-example-movies` index!")
time.sleep(3)
检查新文档以确认它现在有一个 plot_embedding 字段,其中包含新的附加术语列表。 这些术语是创建管道时在 input_field 中用于 ELSER 推理的目标字段的文本扩展。 ELSER 实质上创建了一个扩展术语树,以提高文档的语义可搜索性。 我们将能够使用 text_expansion 查询来搜索这些文档。我们可以在 Kibana 中查看:
但首先让我们从简单的关键字搜索开始,看看 ELSER 如何提供开箱即用的语义相关结果。
搜索文档
response = es.search(index='elser-example-movies', size=3,query={"text_expansion": {"plot_embedding": {"model_id":".elser_model_2","model_text":"fighting movie"}}}
)for hit in response['hits']['hits']:doc_id = hit['_id']score = hit['_score']title = hit['_source']['title']plot = hit['_source']['plot']print(f"Score: {score}\nTitle: {title}\nPlot: {plot}\n")
上面的所有源码可以在地址 https://github.com/liu-xiao-guo/semantic_search_es/blob/main/Install%20ELSER.ipynb 进行下载。
下一步
现在我们有了使用 ELSER 进行语义搜索的工作示例,你可以在自己的数据上尝试一下。
相关文章:

Elasticsearch:使用 ELSER v2 文本扩展进行语义搜索
Elastic 提供了一个强大的 ELSER 供我们进行语义搜索。ELSER 是一种稀疏向量的搜索方法。我们无需对它做任何的微调及训练。它是一种 out-of-domain 的模型。目前它仅对英文进行支持。希望将来它能对其它的语言支持的更好。更多关于 ELSER 的知识,请参阅文章 “Elas…...

Matlab:BP神经网络算法,二叉决策树
1、BP神经网络算法 (1)步骤 1.准备训练数据和目标值 2.创建并配置BP神经网络模型 3.训练BP神经网络模型 4.用BP神经网络模型预测数据 例:某企业第一年度营业额为132468,第二年度为158948,第三年度为183737,预测第四年度的营…...

Python实现员工管理系统(Django页面版 ) 七
各位小伙伴们好久不见,2024年即将到来,小编在这里提前祝大家新的一年快快乐乐,能够事业有成,学习顺心,家庭和睦,事事顺利。 今天我们本篇要实现的是一个登录界面的实现,其实登录界面的实现看着挺…...

听GPT 讲Rust源代码--src/tools(34)
File: rust/src/tools/clippy/clippy_lints/src/collection_is_never_read.rs 文件"collection_is_never_read.rs"位于Rust源代码中的clippy_lints工具中,其作用是检查在集合类型(如Vec、HashMap等)的实例上执行的操作是否被忽略了…...

k8s的陈述式资源管理(命令行操作)
(一)k8s的陈述式资源管理 1、命令行:kubectl命令行工具——用于一般的资源管理 (1)优点:90%以上ce场景都可以满足 (2)特点:对资源的增、删、查比较方便,对…...
uniapp uview裁剪组件源码修改(u-avatar-cropper),裁出可自定义固定大小图片
u-avatar-cropper修改后 <template><view class"index"><!-- {{userinfo}} --><view class"top"><view class"bg"><image src"../../static/electronic_card/bg.png"></image></view&g…...

【机器学习前置知识】Beta分布
Beta分布与二项分布的关系 Beta分布与二项分布密切相关,由二项分布扩展而来,它是用来描述一个连续型随机变量出现的概率的概率密度分布,表示为 X X X~ B e t a ( a , b ) Beta(a,b) Beta(a,b) , a 、 b a、b a、b 是形状参数。Beta分布本质上也是一个概率密度函数,只是这…...
Notepad++批量更改文件编码格式及文档格式
背景: 在项目中遇到Windows平台VS的MSVC编译不识别Unix下UTF-8编码导致的编译失败问题。需要将Unix下的UTF-8转为UTF-8-BOM格式。网上找了些方式,之后又深入探究了下文档转换的可能性,共享给大家。(当然Windows和Unix平台代码格式…...

Linux驱动开发学习笔记6《蜂鸣器实验》
目录 一、蜂鸣器驱动原理 二、硬件原理分析 三、实验程序编写 1、 修改设备树文件 (1)添加pinctrl节点 (2)添加BEEP设备节点 (3)检查PIN 是否被其他外设使用 2、蜂鸣器驱动程序编写 3、编写测试AP…...

鸿蒙(HarmonyOS 3.1) DevEco Studio 3.1开发环境汉化
鸿蒙(HarmonyOS 3.1) DevEco Studio 3.1开发环境汉化 一、安装环境 操作系统: Windows 10 专业版 IDE:DevEco Studio 3.1 SDK:HarmonyOS 3.1 二、设置过程 打开IDE,在第一个菜单File 中找到Settings...菜单 在Setting...中找到Plugins…...

毫米波雷达:从 3D 走向 4D
1 毫米波雷达已广泛应用于汽车 ADAS 系统 汽车智能驾驶需要感知层、决策层、执行层三大核心系统的高效配合,其中感知层通过传感器探知周围的环境。汽车智能驾驶感知层将真实世界的视觉、物理、事件等信息转变成数字信号,为车辆了解周边环境、制定驾驶操…...

CENTOS docker拉取私服镜像
概述 docker的应用越来越多,安装部署越来越方便,批量自动化的镜像生成和发布都需要docker镜像的拉取。 centos6版本太老,docker的使用过程中问题较多,centos7相对简单容易。 本文档主要介绍centos系统安装docker和拉取docker私…...

【前端面经】即时设计
目录 前言一面git 常见命令跨窗口通信vue 响应式原理发布订阅模式翻转二叉树Promise.all()扁平化数组面试官建议 二面Event Loop 原理Promise 相关css 描边方式requestAnimationReact 18 新特性JSX 相关react 输出两次函数式编程React 批处理机制http请求头有哪些本地存储性能优…...

前端三件套html/css/js的基本认识以及示例程序
简介 本文简要讲解了html,css,js.主要是让大家简要了解网络知识 因为实际开发中很少直接写html&css,所以不必过多纠结,了解一下架构就好 希望深度学习可以参考MDN和w3school HTML 基础 HTML (Hyper Text Markup Language) 不是一门编程语言,而是一种用来告知浏览器如…...

云计算:OpenStack 配置云主机实例的存储挂载并实现外网互通
目录 一、实验 1. 环境 2.配置存储挂载 3.云主机实例连接外部网络(SNAT) 4.外部网络连接云主机实例(DNAT) 二、问题 1.云主机 ping 不通外部网络 2.nova list 查看云主机列表报错 3.nova list 与 virsh list --all有何区…...

python/selenium/jenkins整合
1、新建python项目,专门写selenium代码,建议用pytest框架写。 2、把代码上传到代码库中。 3、环境配置: 3.1 在跑jenkins的机器上配置好python环境,需要python --version能在任何地方运行(配置好系统环境变量&#…...
华为路由器ACL操作SSH接口
ACL的定义 访问控制列表(Access Control Lists,ACL)是应用在路由器接口的指令列表。这些指令列表用来告诉路由器哪些数据包可以收、哪些数据包需要拒绝。至于数据包是被接收还是拒绝,可以由类似于源地址、目的地址、端口号等的特…...
Flutter 三点三:Dart Stream
Stream Stream用于接收异步事件Stream 可以接收多个异步事件Stream.listen()方法返回StreamSubscription 可用于取消事件订阅,取消后,不再接收事件 基本使用 Stream.fromFutures([Future.delayed(Duration(seconds: 1),(){return "事件1";})…...
centos 防火墙 设置 LTS
centos 防火墙 设置 LTS https://blog.csdn.net/m0_58805648/article/details/130671008...

SAP缓存 表缓存( Table Buffering)
本文主要介绍SAP中的表缓存在查询数据,更新数据时的工作情况以及对应概念。 SAP表缓存的工作 查询数据 更新数据 删除数据 表缓存的概念 表缓存技术设置属性 不允许缓冲: 允许缓冲,但已关闭: 缓冲已激活: 已…...
k8s从入门到放弃之Ingress七层负载
k8s从入门到放弃之Ingress七层负载 在Kubernetes(简称K8s)中,Ingress是一个API对象,它允许你定义如何从集群外部访问集群内部的服务。Ingress可以提供负载均衡、SSL终结和基于名称的虚拟主机等功能。通过Ingress,你可…...

云启出海,智联未来|阿里云网络「企业出海」系列客户沙龙上海站圆满落地
借阿里云中企出海大会的东风,以**「云启出海,智联未来|打造安全可靠的出海云网络引擎」为主题的阿里云企业出海客户沙龙云网络&安全专场于5.28日下午在上海顺利举办,现场吸引了来自携程、小红书、米哈游、哔哩哔哩、波克城市、…...

23-Oracle 23 ai 区块链表(Blockchain Table)
小伙伴有没有在金融强合规的领域中遇见,必须要保持数据不可变,管理员都无法修改和留痕的要求。比如医疗的电子病历中,影像检查检验结果不可篡改行的,药品追溯过程中数据只可插入无法删除的特性需求;登录日志、修改日志…...

【Redis技术进阶之路】「原理分析系列开篇」分析客户端和服务端网络诵信交互实现(服务端执行命令请求的过程 - 初始化服务器)
服务端执行命令请求的过程 【专栏简介】【技术大纲】【专栏目标】【目标人群】1. Redis爱好者与社区成员2. 后端开发和系统架构师3. 计算机专业的本科生及研究生 初始化服务器1. 初始化服务器状态结构初始化RedisServer变量 2. 加载相关系统配置和用户配置参数定制化配置参数案…...

多模态大语言模型arxiv论文略读(108)
CROME: Cross-Modal Adapters for Efficient Multimodal LLM ➡️ 论文标题:CROME: Cross-Modal Adapters for Efficient Multimodal LLM ➡️ 论文作者:Sayna Ebrahimi, Sercan O. Arik, Tejas Nama, Tomas Pfister ➡️ 研究机构: Google Cloud AI Re…...

基于 TAPD 进行项目管理
起因 自己写了个小工具,仓库用的Github。之前在用markdown进行需求管理,现在随着功能的增加,感觉有点难以管理了,所以用TAPD这个工具进行需求、Bug管理。 操作流程 注册 TAPD,需要提供一个企业名新建一个项目&#…...
AGain DB和倍数增益的关系
我在设置一款索尼CMOS芯片时,Again增益0db变化为6DB,画面的变化只有2倍DN的增益,比如10变为20。 这与dB和线性增益的关系以及传感器处理流程有关。以下是具体原因分析: 1. dB与线性增益的换算关系 6dB对应的理论线性增益应为&…...

2025年渗透测试面试题总结-腾讯[实习]科恩实验室-安全工程师(题目+回答)
安全领域各种资源,学习文档,以及工具分享、前沿信息分享、POC、EXP分享。不定期分享各种好玩的项目及好用的工具,欢迎关注。 目录 腾讯[实习]科恩实验室-安全工程师 一、网络与协议 1. TCP三次握手 2. SYN扫描原理 3. HTTPS证书机制 二…...
深度剖析 DeepSeek 开源模型部署与应用:策略、权衡与未来走向
在人工智能技术呈指数级发展的当下,大模型已然成为推动各行业变革的核心驱动力。DeepSeek 开源模型以其卓越的性能和灵活的开源特性,吸引了众多企业与开发者的目光。如何高效且合理地部署与运用 DeepSeek 模型,成为释放其巨大潜力的关键所在&…...

论文阅读:Matting by Generation
今天介绍一篇关于 matting 抠图的文章,抠图也算是计算机视觉里面非常经典的一个任务了。从早期的经典算法到如今的深度学习算法,已经有很多的工作和这个任务相关。这两年 diffusion 模型很火,大家又开始用 diffusion 模型做各种 CV 任务了&am…...