Elasticsearch:使用 ELSER 文本扩展进行语义搜索

在今天的文章里,我来详细地介绍如何使用 ELSER  进行文本扩展驱动的语义搜索。

安装

Elasticsearch 及 Kibana

如果你还没有安装好自己的 Elasticsearch 及 Kibana,请参考如下的链接来进行安装:

  • 如何在 Linux,MacOS 及 Windows 上进行安装 Elasticsearch

  • Kibana:如何在 Linux,MacOS 及 Windows 上安装 Elastic 栈中的 Kibana

在安装的时候,我们可以选择 Elastic Stack 8.x 的安装指南来进行安装。在本博文中,我将使用最新的 Elastic Stack 8.10 来进行展示。

在安装 Elasticsearch 的过程中,我们需要记下如下的信息:

部署 ELSER

我们可以参考文章 “Elasticsearch:部署 ELSER - Elastic Learned Sparse EncoderR” 来部署 ELSER。

Python 安装包

在本演示中,我们将使用 Python 来进行展示。我们需要安装访问 Elasticsearch 相应的安装包 elasticsearch:

pip install elasticsearch

我们将使用 Jupyter Notebook 来进行展示。

$ pwd
/Users/liuxg/python/elser
$ jupyter notebook

准备数据

我们在项目的根目录下,创建如下的一个数据文件: data.json:

data.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
Semantic search - ELSER.ipynb data.json

创建应用并进行演示

连接 Elasticsearch

我们可以参考文章 “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x” 在 Python 中连接 Elasticsearch。接下来,我们需要导入我们需要的模块。

from elasticsearch import Elasticsearch, helpers
from urllib.request import urlopen
import getpass
import json

现在我们可以实例化 Python Elasticsearch 客户端。

然后我们创建一个客户端对象来实例化 Elasticsearch 类的实例。

ELASTCSEARCH_CERT_PATH = "/Users/liuxg/elastic/elasticsearch-8.10.0/config/certs/http_ca.crt"client = Elasticsearch(  ['https://localhost:9200'],basic_auth = ('elastic', 'vXDWYtL*my3vnKY9zCfL'),ca_certs = ELASTCSEARCH_CERT_PATH,verify_certs = True)

🔐 注意:getpass 使我们能够安全地提示用户输入凭据,而无需将其回显到终端或将其存储在内存中。为了方便,我们将不使用 getpass。在代码中我们使用硬编码。你也可以使用 API keys 来进行连接。详细细节,请参考文章  “Elasticsearch:关于在 Python 中使用 Elasticsearch 你需要知道的一切 - 8.x”。

使用 ELSER 索引文档

为了在我们的 Elasticsearch 集群上使用 ELSER,我们需要创建一个包含运行 ELSER 模型的推理处理器的摄取管道。 让我们使用 put_pipeline 方法添加该管道。

client.ingest.put_pipeline(id="elser-ingest-pipeline", description="Ingest pipeline for ELSER",processors=[{"inference": {"model_id": ".elser_model_1","target_field": "ml","field_map": {"plot": "text_field"},"inference_config": {"text_expansion": {"results_field": "tokens"}}}}]
)

让我们记下该 API 调用中的一些重要参数:

  • inference:使用机器学习模型执行推理的处理器。
  • model_id:指定要使用的机器学习模型的 ID。 在此示例中,模型 ID 设置为 .elser_model_1。
  • target_field:定义存储推理结果的字段。 这里设置为 ml。
  • text_expansion:为推理过程配置文本扩展选项。 在此示例中,推理结果将存储在名为 “tokens” 的字段中。

使用映射创建索引

要在索引时使用 ELSER 模型,我们需要创建支持 text_expansion 查询的索引映射。 映射必须包含 rank_features 类型的字段才能使用我们感兴趣的特征向量。 该字段包含 ELSER 模型根据输入文本创建的 token 权重对。

让我们使用我们需要的映射创建一个名为 elser-example-movies 的索引。

client.indices.create(index="elser-example-movies",settings={"index": {"number_of_shards": 1,"number_of_replicas": 1,"default_pipeline": "elser-ingest-pipeline"}},mappings={"properties": {"plot": {"type": "text","fields": {"keyword": {"type": "keyword","ignore_above": 256}}},"ml.tokens": {"type": "rank_features"},}}
)

在运行完上面的代码后,我们可以在 Kibana 里进行查看:

GET elser-example-movies/_mapping

从上面的输出中,我们可以看到 elser-example-movies 索引已经被成功地创建。

摄入文档

让我们插入 12 部电影的示例数据集。

# Load data into a JSON object
with open('data.json') as f:data_json = json.load(f)print(data_json)# Prepare the documents to be indexed
documents = []
for doc in data_json:documents.append({"_index": INDEX_NAME,"_source": doc,})# Use helpers.bulk to index
helpers.bulk(client, documents)print("Done indexing documents into `search-movies` index!")

我们可以到 Kibana 里进行查看:

GET elser-example-movies/_search

检查新文档以确认它现在有一个 "ml": {"tokens":...} 字段,其中包含新的附加术语列表。 这些术语是你针对 ELSER 推理的字段的文本扩展。 ELSER 实质上创建了一个扩展术语树,以提高文档的语义可搜索性。 我们将能够使用 text_expansion 查询来搜索这些文档。

但首先让我们从简单的关键字搜索开始,看看 ELSER 如何提供开箱即用的语义相关结果。

使用 ELSER 查询文档

让我们使用 ELSER 测试语义搜索。

response = client.search(index='elser-example-movies', size=3,query={"text_expansion": {"ml.tokens": {"model_id":".elser_model_1","model_text":"child toy"}}}
)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")

最终的 jupyter 文件可以在地址下载。

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

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

相关文章

机器学习7:pytorch的逻辑回归

一、说明 逻辑回归模型是处理分类问题的最常见机器学习模型之一。二项式逻辑回归只是逻辑回归模型的一种类型。它指的是两个变量的分类,其中概率用于确定二元结果,因此“二项式”中的“bi”。结果为真或假 — 0 或 1。 二项式逻辑回归的一个例子是预测人…

《低代码指南》——低代码维格云服务菜单

简介​ 快速了解付费客户能够获得维格服务团队哪些服务,本篇内容不包含使用免费试用版本的客户。 了解维格表产品价格与功能权益:戳我看价格与权益​ 客户付费后能得到哪些服务项目?​ 常规服务项目:

Covert Communication 与选择波束(毫米波,大规模MIMO,可重构全息表面)

Covert Communication for Spatially Sparse mmWave Massive MIMO Channels 2023 TOC abstract 隐蔽通信,也称为低检测概率通信,旨在为合法用户提供可靠的通信,并防止任何其他用户检测到合法通信的发生。出于下一代通信系统安全链路的强烈…

数据结构P46(2-1~2-4)

2-1编写算法查找顺序表中值最小的结点&#xff0c;并删除该结点 #include <stdio.h> #include <stdlib.h> typedef int DataType; struct List {int Max;//最大元素 int n;//实际元素个数 DataType *elem;//首地址 }; typedef struct List*SeqList;//顺序表类型定…

基于遗传算法的新能源电动汽车充电桩与路径选择(Matlab代码实现)

&#x1f4a5;&#x1f4a5;&#x1f49e;&#x1f49e;欢迎来到本博客❤️❤️&#x1f4a5;&#x1f4a5; &#x1f3c6;博主优势&#xff1a;&#x1f31e;&#x1f31e;&#x1f31e;博客内容尽量做到思维缜密&#xff0c;逻辑清晰&#xff0c;为了方便读者。 ⛳️座右铭&a…

如何用ChatGPT学或教英文?5个使用ChatGPT的应用场景!

原文&#xff1a;百度安全验证 AI工具ChatGPT的出现大幅改变许多领域的运作方式&#xff0c;就连「学英文」也不例外&#xff01;我发现ChatGPT应用在英语的学习与教学上非常有意思。 究竟ChatGPT如何改变英文学习者(学生)与教学者(老师)呢&#xff1f; 有5个应用场景我感到…

docker部署Vaultwarden密码共享管理系统

Vaultwarden是一个开源的密码管理器&#xff0c;它是Bitwarden密码管理器的自托管版本。它提供了类似于Bitwarden的功能&#xff0c;允许用户安全地存储和管理密码、敏感数据和身份信息。 Vaultwarden的主要特点包括&#xff1a; 1. 安全的数据存储&#xff1a;Vaultwarden使…

SAP-MM-委外订单合并有什么不同?

计划下了两个委外采购申请&#xff0c;用ME59N合并时会有哪些不同&#xff1f; 1、采购申请2个都是委外采购申请&#xff0c;有BOM组件 因为两个采购申请的条件一致&#xff0c;所以在转采购订单ME59时&#xff0c;会被合并 但是合并之后&#xff0c;BOM组件却不显示了

【Vue】vscode格式刷插件Prettier以及配置项~~保姆级教程

文章目录 前言一、下载插件二、在项目内创建配置文件1.在根目录创建&#xff0c;src同级2.写入配置3.每个字段含义 总结 前言 vscode格式刷&#xff0c;有太多插件了&#xff0c;但是每个的使用&#xff0c;换行都不一样。 这里我推荐一个很多人都推荐了的Prettier 一、下载插…

【SpringCloud】微服务技术栈入门5 - ElasticSearch

ElasticSearch 倒排索引 倒排索引建立&#xff1a;对文章标题进行分词&#xff0c;将每个词存入 term&#xff0c;这些词也对应一个 id 也就是文档 倒排索引检索&#xff1a;假设我们搜索华为手机 分词&#xff1a;“华为”“手机”从数据库中找到对应的两个 key&#xff0c;…

CSS鼠标指针表

(机翻)搬运自:cursor - CSS: Cascading Style Sheets | MDN (mozilla.org) 类型Keyword演示注释全局autoUA将基于当前上下文来确定要显示的光标。例如&#xff0c;相当于悬停文本时的文本。default 依赖于平台的默认光标。通常是箭头。none不会渲染光标。链接&状态contex…

【开发篇】二十、SpringBoot整合RocketMQ

文章目录 1、整合2、消息的生产3、消费4、发送异步消息5、补充&#xff1a;安装RocketMQ 1、整合 首先导入起步依赖&#xff0c;RocketMQ的starter不是Spring维护的&#xff0c;这一点从starter的命名可以看出来&#xff08;不是spring-boot-starter-xxx&#xff0c;而是xxx-s…