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 进行语义搜索的工作示例,你可以在自己的数据上尝试一下。 

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

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

相关文章

MySql——1146 - Table‘mysql.proc‘doesn‘t exit是这个

项目场景: 做自己的小项目需要连接mysql数据库 问题描述 点击数据库时报错 1146 - Table’mysql.proc’doesn’t exit 原因分析: 误删原生的mysql数据库 解决方案: 重新安装装部署mysql就好了 注意不要轻易删除原生的东西

day55 算法训练|动态规划part15

392.判断子序列 给定字符串 s 和 t ,判断 s 是否为 t 的子序列。 字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace"是"abcde"的…

react学习第一天

脚手架的创建 1.创建环境变量 npm init -y 2.创建node-modules npm add -D create-react-app 3.创建脚手架 npx create-react-app react-demo1 报错一号 报错原因:node版本太低 解决:升级版本 nvm install 14.0.0 nvm use 14.0.0 报错二号 报错原因&…

单元测试:无返回值接口单元测试

在平常的工作中,我们经常会用到单元测试,那么,单元测试应该怎么写呢?有什么需要注意的地方呢? 比如保存,数据是否保存成功,我们应该用单元测试怎么断言呢?像保存完成后,再…

牛客网SQL训练5—SQL大厂面试真题

文章目录 一、某音短视频1.各个视频的平均完播率2.平均播放进度大于60%的视频类别3.每类视频近一个月的转发量/率4.每个创作者每月的涨粉率及截止当前的总粉丝量5.国庆期间每类视频点赞量和转发量6.近一个月发布的视频中热度最高的top3视频 二、用户增长场景(某度信…

git上传代码到github远程仓库

1、添加SSH公钥 为了把本地的仓库传到github,还需要配置ssh key,说白了就是为了把本地的代码上传到github。 1、前置准备 本地需要安装git:Git - Downloads。安装成功后本地右键鼠标会多出一些git选项。 2、添加SSH Key 首先在本地创建s…

红队打靶练习:MISDIRECTION: 1

信息收集 1、arp ┌──(root㉿ru)-[~/kali] └─# arp-scan -l Interface: eth0, type: EN10MB, MAC: 00:0c:29:69:c7:bf, IPv4: 192.168.12.128 Starting arp-scan 1.10.0 with 256 hosts (https://github.com/royhills/arp-scan) 192.168.12.1 00:50:56:c0:00:08 …

数据结构(C)

基础知识 数据是所有能被输入计算机中,且能被计算机处理的符号的集合数据元素是数据的基本单位数据项是独立含义的数据最小单元数据对象是独立含义最小单位数据对象是指性质相同的数据元素的集合数据结构是带结构的数据元素的集合主要讨论数据之间的相邻关系或者邻…

Linux环境下OpenSSH升级到 OpenSSH_9.5p1(内置保姆级教程)

我最近在修复服务器的openssh漏洞的时候是服务器生产环境,自己在做的时候,就遇到的重启之后直接断掉ssh的连接,最后发现原因是没配置sshd_config的允许远程用户登录,因此,在此记录一下升级openssh的操作步骤&#xff0…

Rosalind 036 Matching Random Motifs

题目背景: 这个问题要求我们计算在一组随机生成的DNA字符串中,至少有一个字符串与给定的基序(特定的DNA序列)相匹配的概率。这些DNA字符串的随机生成受到给定的GC含量的控制,这是指DNA中要么是鸟嘌呤(G&am…

算法基础之能被整除的数

能被整除的数 核心思想&#xff1a; 容斥原理 总面积 1-23-4…. 总集合元素中个数 1-23-4…. #include<iostream>#include<cstring>#include<algorithm>using namespace std;const int N 20;typedef long long LL;int p[N];int main(){int n,m;cin&…

【C++设计模式 -- 单例(Singleton)模式】

C 单例&#xff08;Singleton&#xff09;模式 单例模式什么是单例模式单例模式的特点为什么要使用单例模式单例模式的缺点 单例模式实现懒汉式&#xff08;Lazy Initialization&#xff09;方式(不安全)双重检查锁&#xff08;Double-Checked Locking&#xff09;&#xff08;…

第三百三十九回

文章目录 1. 概念介绍2. 方法与信息2.1 获取方法2.2 详细信息 3. 示例代码4. 内容总结 我们在上一章回中介绍了"蓝牙综合示例"相关的内容&#xff0c;本章回中将介绍如何获取设备信息.闲话休提&#xff0c;让我们一起Talk Flutter吧。 1. 概念介绍 我们在本章回中获…

十八、任务通知

1、前言 (1)所谓“任务通知”&#xff0c;可以反过来读"通知任务"。我们使用队列、信号量、事件组等等方法时&#xff0c;并不知道对方是谁。使用任务通知时&#xff0c;可以明确指定&#xff1a;通知哪个任务。 (2)使用队列、信号量、事件组时&#xff0c;我们都需…

2023年“中银杯”四川省职业院校技能大赛“云计算应用”赛项样题卷②

2023年“中银杯”四川省职业院校技能大赛“云计算应用”赛项&#xff08;高职组&#xff09; 样题&#xff08;第2套&#xff09; 目录 2023年“中银杯”四川省职业院校技能大赛“云计算应用”赛项&#xff08;高职组&#xff09; 样题&#xff08;第2套&#xff09; 模块…

Topics(动态路由)

Topic类型的Exchange与Direct相比&#xff0c;都是可以根据RoutingKey把消息路由到不同的队列中。只不过Topic类型Exchange可以让队列在绑定路由时可以使用通配符。 *&#xff1a;匹配不多不少刚好一个单词。 #&#xff1a;匹配一个或多个词。 举例&#xff1a; audit.#可以匹配…

2023吉利汽车大模型算法工程师面试经验

来源&#xff1a;投稿 作者&#xff1a;LSC 编辑&#xff1a;学姐 问了很多问题&#xff0c;包括实习的项目经验、各种计算机、人工智能的基础&#xff0c;时长1h30min 1.coding 给你一个整数数组 prices 和一个整数 k &#xff0c;其中 prices[i] 是某支给定的股票在第 i 天的…

解密C++中的forward<int>(a)和forward<int >(a):你真的了解它们之间的区别吗?

一文看尽C中的forward完美转发 一、前言二、深入理解forward和完美转发三、对forward<int>(a)的解析四、对forward<int &&>(a)的解析五、forward<int>(a)和forward<int &&>(a)的区别总结 一、前言 完美转发在C中具有重要性&#xff0…

Java开发一个接口提供给第三方调用

1. 环境 基于SpringBoot编写一个接口&#xff0c;提供给第三方调用。类似于我们使用阿里的语音识别功能&#xff0c;我们可以调用阿里封装好的api&#xff0c;也就是通过发送HTTP请求的方式来做语音识别。本篇文章主要记录在SpringBoot中我们是如何开发接口并让别人可以安全调…

一文掌握Java注解之@SpringBootApplication知识文集(1)

&#x1f3c6;作者简介&#xff0c;普修罗双战士&#xff0c;一直追求不断学习和成长&#xff0c;在技术的道路上持续探索和实践。 &#x1f3c6;多年互联网行业从业经验&#xff0c;历任核心研发工程师&#xff0c;项目技术负责人。 &#x1f389;欢迎 &#x1f44d;点赞✍评论…