当前位置: 首页 > news >正文

Elasticsearch:使用 huggingface 模型的 NLP 文本搜索

本博文使用由 Elastic 博客 title 组成的简单数据集在 Elasticsearch 中实现 NLP 文本搜索。你将为博客文档建立索引,并使用摄取管道生成文本嵌入。 通过使用 NLP 模型,你将使用自然语言在博客文档上查询文档。

 安装

Elasticsearch 及 Kibana

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

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

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

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

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

由于我们将要使用到 eland 来上传模型。这是一个收费的功能。我们需要启动试用功能:

Python 安装包

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

python3 -m pip install -qU sentence-transformers eland elasticsearch transformers

我们将使用 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
Multilingual semantic search.ipynb
NLP text search using hugging face transformer model.ipynb
Semantic search - ELSER.ipynb
data.json

创建应用并演示

import modules

import pandas as pd, json
from elasticsearch import Elasticsearch
from getpass import getpass
from urllib.request import urlopen

部署 NLP 模型

我们将使用 eland 工具来安装 text_embedding 模型。 对于我们的模型,我们使用 all-MiniLM-L6-v2 将搜索文本转换为密集向量。

该模型会将你的搜索查询转换为向量,该向量将用于对 Elasticsearch 中存储的文档集进行搜索。

我们在 terminal 中打入如下的命令:

eland_import_hub_model --url https://elastic:vXDWYtL*my3vnKY9zCfL@localhost:9200 \--hub-model-id sentence-transformers/all-MiniLM-L6-v2 \--task-type text_embedding \--ca-cert /Users/liuxg/elastic/elasticsearch-8.10.0/config/certs/http_ca.crt \--start

请注意

  • 我们需要根据自己的部署来替换上面的 elastic 超级用户的密码
  • 我们需要根据自己的 Elasticsearch 集群的部署来替换上面的 Elasticsearch 访问地址
  • 我们需要根据自己的部署的证书来替换上面的证书路径

我们回到 Kibana 的界面:

连接到 Elasticsearch

我们创建一个客户端连接:

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

创建 ingest pipeline

我们需要创建一个文本嵌入提取管道来生成 title 字段的向量(文本)嵌入。

下面的管道定义了一个用于 NLP 模型的 inference 处理器。

# ingest pipeline definition
PIPELINE_ID="vectorize_blogs"es.ingest.put_pipeline(id=PIPELINE_ID, processors=[{"inference": {"model_id": "sentence-transformers__all-minilm-l6-v2","target_field": "text_embedding","field_map": {"title": "text_field"}}}])

创建带有映射的索引

现在,在索引文档之前,我们将创建一个具有正确映射的 Elasticsearch 索引。 我们添加 text_embedding 以包含 model_id 和 Predicted_value 来存储嵌入。

# define index name
INDEX_NAME="blogs"# flag to check if index has to be deleted before creating
SHOULD_DELETE_INDEX=True# define index mapping
INDEX_MAPPING = {"properties": {"title": {"type": "text","fields": {"keyword": {"type": "keyword","ignore_above": 256}}},"text_embedding": {"properties": {"is_truncated": {"type": "boolean"},"model_id": {"type": "text","fields": {"keyword": {"type": "keyword","ignore_above": 256}}},"predicted_value": {"type": "dense_vector","dims": 384,"index": True,"similarity": "l2_norm"}}}}}INDEX_SETTINGS = {"index": {"number_of_replicas": "1","number_of_shards": "1","default_pipeline": PIPELINE_ID}
}# check if we want to delete index before creating the index
if(SHOULD_DELETE_INDEX):if es.indices.exists(index=INDEX_NAME):print("Deleting existing %s" % INDEX_NAME)client.options(ignore_status=[400, 404]).indices.delete(index=INDEX_NAME)print("Creating index %s" % INDEX_NAME)
es.options(ignore_status=[400,404]).indices.create(index=INDEX_NAME, mappings=INDEX_MAPPING, settings=INDEX_SETTINGS)

摄入数据到 Elasticsearch

让我们使用摄取管道对示例博客数据进行索引。

注意:在我们开始索引之前,请确保你已启动训练模型部署。

from elasticsearch import helpers# 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": "blogs","_source": doc,})# Use helpers.bulk to index
helpers.bulk(client, documents)

我们可以回到 Kibana 的界面查看被写入的文档:

GET blogs/_search

查询数据集

下一步是运行查询来搜索相关博客。 该示例查询使用我们上传到 Elasticsearch Sentence-transformers__all-minilm-l6-v2 的模型来搜索 “model_text”: “scientific fiction”。

该过程是一个查询,尽管它内部包含两个任务。 首先,查询将使用 NLP 模型为您的搜索文本生成一个向量,然后传递该向量以在数据集上进行搜索。

结果,输出显示按照与搜索查询的接近度排序的查询文档列表。

INDEX_NAME="blogs"source_fields = [ "id", "title"]query = {"field": "text_embedding.predicted_value","k": 10,"num_candidates": 50,"query_vector_builder": {"text_embedding": {"model_id": "sentence-transformers__all-minilm-l6-v2","model_text": "scientific fiction"}}
}response = es.search(index=INDEX_NAME,fields=source_fields,knn=query,source=False)results = pd.json_normalize(json.loads(json.dumps(response.body['hits']['hits'])))# shows the result
results[['_id', '_score', 'fields.title']]

上面命令显示的结果为:

你可尝试另外的一个搜索,比如:dark knight

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

相关文章:

Elasticsearch:使用 huggingface 模型的 NLP 文本搜索

本博文使用由 Elastic 博客 title 组成的简单数据集在 Elasticsearch 中实现 NLP 文本搜索。你将为博客文档建立索引,并使用摄取管道生成文本嵌入。 通过使用 NLP 模型,你将使用自然语言在博客文档上查询文档。 安装 Elasticsearch 及 Kibana 如果你还没…...

论文解析——异构多芯粒神经网络加速器

作者 朱郭益, 马胜,张春元, 王波(国防科技大学计算机学院) 摘要 随着神经网络技术的快速发展, 出于安全性等方面考虑, 大量边缘计算设备被应用于智能计算领域。首先,设计了可应用于边缘计算的异构多芯粒神经网络加速器其基本结构…...

MyBatisPlus(十六)逻辑删除

说明 实际生产中的数据,一般不采用物理删除,而采用逻辑删除,也就是将一条记录的状态改为已删除。 逻辑删除,本质上是更新操作。 MyBatis Plus 框架,提供了逻辑删除功能。在配置了逻辑删除后,增删改查和统…...

基于黏菌优化的BP神经网络(分类应用) - 附代码

基于黏菌优化的BP神经网络(分类应用) - 附代码 文章目录 基于黏菌优化的BP神经网络(分类应用) - 附代码1.鸢尾花iris数据介绍2.数据集整理3.黏菌优化BP神经网络3.1 BP神经网络参数设置3.2 黏菌算法应用 4.测试结果:5.M…...

C语言基础语法复习08-位域bit-fields

在c2011 iso文档中,位域与struct、union是一起定义的: Structure and union specifiers Syntaxstruct-or-union-specifier:struct-or-union identifier opt { struct-declaration-list }struct-or-union identifierstruct-or-union:structunionstruct-d…...

3.2.OpenCV技能树--二值图像处理--图像腐蚀与膨胀

文章目录 1.文章内容来源2.图像膨胀处理2.1.图像膨胀原理简介2.2.图像膨胀核心代码2.3.图像膨胀效果展示 3.图像腐蚀处理3.1.图像腐蚀原理简介3.2.图像腐蚀核心代码3.3.图像腐蚀效果展示 4.易错点总结与反思 1.文章内容来源 1.题目来源:https://edu.csdn.net/skill/practice/o…...

基于FPGA的数字时钟系统设计

在FPGA的学习中,数字时钟是一个比较基础的实验案例,通过该实验可以更好的锻炼初学者的框架设计能力以及逻辑思维能力,从而打好坚实的基本功,接下来就开始我们的学习吧! 1.数码管介绍 数码管通俗理解就是将8个LED(包含…...

linux centos Python + Selenium+Chrome自动化测试环境搭建?

在 CentOS 系统上搭建 Python Selenium Chrome 自动化测试环境,需要执行以下步骤: 1、安装 Python CentOS 7 自带的 Python 版本较老,建议使用 EPEL 库或源码安装 Python 3。例如,使用 EPEL 库安装 Python 3: sud…...

mysql面试题20:有哪些合适的分布式主键方案

该文章专注于面试,面试只要回答关键点即可,不需要对框架有非常深入的回答,如果你想应付面试,是足够了,抓住关键点 面试官:有哪些合适的分布式主键方案? UUID:UUID通常是由一个二进制的128位整数表示,可以保证全局的唯一性。在Java中,可以通过UUID类生成一个UUID。例…...

git的基础操作

https://blog.csdn.net/a18307096730/article/details/124586216?spm1001.2014.3001.5502 1:使用场景 SVN,如果服务器里面的东西坏掉了,那么就全线崩盘了。 1:基本配置 git config --global user.name “luka” (自己的名字就行) git co…...

lua 中文字符的判断简介

一般在工作中会遇到中文字符的判断、截断、打码等需求,之前一直没有总结,虽然网上资料也多,今天在这里简单的总结一下。 1 .UTF-8简单描述 UTF-8 是 Unicode 的实现方式之一,其对应关系(编码规则)如下表所…...

SSM-XML整合

SSM-XML整合 核心配置文件 maven坐标 <dependencies><!--数据库驱动--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>8.0.27</version></dependency><!--数据…...

线性代数小例子

这样做有什么问题呢&#xff1a; A 2 A > A ( A − E ) 0 > A E A 0 A^2 A > A(A - E) 0> A E \quad A 0 A2A>A(A−E)0>AEA0 上述做法是错误的&#xff0c;这是因为两个矩阵的乘积结果为0&#xff0c;并不能说明这两个矩阵就是0&#xff0c;即上述…...

ASP.NET Core 开发 Web API

2. Web Api 的创建与Http类型的介绍 2.1 ASP.Net Core Web API项目的创建 1.创建ASP.NET Core Web API项目 从“文件”菜单中选择“新建”“项目”。 在搜索框中输入“Web API”。 选择“ASP.NET Core Web API”模板&#xff0c;然后选择“下一步”。 在“配置新项目”对话框中…...

QImage函数setAlphaChannel

最近使用QImage的函数setAlphaChannel时遇到了一个坑&#xff0c;花了不少时间才弄清楚&#xff1a;在使用这个函数后&#xff0c;图像格式都会变成QImage::Format_ARGB32_Premultiplied。 先看下setAlphaChannel在帮助文档的说明&#xff1a; void QImage::setAlphaChannel(…...

区块链、隐私计算、联邦学习、人工智能的关联

目录 前言 1.区块链 2.隐私计算 3.联邦学习&#xff08;隐私计算技术&#xff09; 4.区块链和联邦学习 5.区块链和人工智能 展望 参考文献 前言 区块链公开透明&#xff0c;但也需要隐私&#xff0c;人工智能强大&#xff0c;但也需要限制。当前我们需要的是一个在保证…...

Unity可视化Shader工具ASE介绍——4、ASE的自定义模板使用

大家好&#xff0c;我是阿赵。   继续介绍Unity可视化Shader编辑工具ASE。之前的文章介绍了在ASE里面可以选择不同的Shader类型。这一篇来继续探讨一下&#xff0c;这些Shader类型究竟是什么。 一、所谓的Shader类型是什么 选择不同的Shader类型&#xff0c;会出现不同的选项…...

FastAPI学习-22.response 异常处理 HTTPException

前言 某些情况下&#xff0c;需要向客户端返回错误提示。 这里所谓的客户端包括前端浏览器、其他应用程序、物联网设备等。 需要向客户端返回错误提示的场景主要如下&#xff1a; 客户端没有执行操作的权限客户端没有访问资源的权限客户端要访问的项目不存在等等 … 遇到这些…...

75.颜色分类

原地排序&#xff1a;空间复杂度为1 class Solution { public:void sortColors(vector<int>& nums) {if(0){//法一&#xff1a;单指针两个遍历int nnums.size();int ptr0;for(int i0;i<n;i){if(nums[i]0){swap(nums[i],nums[ptr]);ptr;}}for(int iptr;i<n;i){…...

浅谈分散式存储项目MEMO

Memo本质上是互联网项目&#xff0c;应用了一些区块链技术而已&#xff0c;或者叫做包了层区块链皮的互联网项目。 最开始对标Filcoin&#xff0c;后来发现Filcoin也有问题&#xff0c;分布式存储解决方案并不完美&#xff0c;抑或者是自己团队的研发能力无法与IPFS团队PK&…...

Java 8 Stream API 入门到实践详解

一、告别 for 循环&#xff01; 传统痛点&#xff1a; Java 8 之前&#xff0c;集合操作离不开冗长的 for 循环和匿名类。例如&#xff0c;过滤列表中的偶数&#xff1a; List<Integer> list Arrays.asList(1, 2, 3, 4, 5); List<Integer> evens new ArrayList…...

Docker 运行 Kafka 带 SASL 认证教程

Docker 运行 Kafka 带 SASL 认证教程 Docker 运行 Kafka 带 SASL 认证教程一、说明二、环境准备三、编写 Docker Compose 和 jaas文件docker-compose.yml代码说明&#xff1a;server_jaas.conf 四、启动服务五、验证服务六、连接kafka服务七、总结 Docker 运行 Kafka 带 SASL 认…...

UDP(Echoserver)

网络命令 Ping 命令 检测网络是否连通 使用方法: ping -c 次数 网址ping -c 3 www.baidu.comnetstat 命令 netstat 是一个用来查看网络状态的重要工具. 语法&#xff1a;netstat [选项] 功能&#xff1a;查看网络状态 常用选项&#xff1a; n 拒绝显示别名&#…...

Auto-Coder使用GPT-4o完成:在用TabPFN这个模型构建一个预测未来3天涨跌的分类任务

通过akshare库&#xff0c;获取股票数据&#xff0c;并生成TabPFN这个模型 可以识别、处理的格式&#xff0c;写一个完整的预处理示例&#xff0c;并构建一个预测未来 3 天股价涨跌的分类任务 用TabPFN这个模型构建一个预测未来 3 天股价涨跌的分类任务&#xff0c;进行预测并输…...

《通信之道——从微积分到 5G》读书总结

第1章 绪 论 1.1 这是一本什么样的书 通信技术&#xff0c;说到底就是数学。 那些最基础、最本质的部分。 1.2 什么是通信 通信 发送方 接收方 承载信息的信号 解调出其中承载的信息 信息在发送方那里被加工成信号&#xff08;调制&#xff09; 把信息从信号中抽取出来&am…...

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别

OpenPrompt 和直接对提示词的嵌入向量进行训练有什么区别 直接训练提示词嵌入向量的核心区别 您提到的代码: prompt_embedding = initial_embedding.clone().requires_grad_(True) optimizer = torch.optim.Adam([prompt_embedding...

智能分布式爬虫的数据处理流水线优化:基于深度强化学习的数据质量控制

在数字化浪潮席卷全球的今天&#xff0c;数据已成为企业和研究机构的核心资产。智能分布式爬虫作为高效的数据采集工具&#xff0c;在大规模数据获取中发挥着关键作用。然而&#xff0c;传统的数据处理流水线在面对复杂多变的网络环境和海量异构数据时&#xff0c;常出现数据质…...

2025季度云服务器排行榜

在全球云服务器市场&#xff0c;各厂商的排名和地位并非一成不变&#xff0c;而是由其独特的优势、战略布局和市场适应性共同决定的。以下是根据2025年市场趋势&#xff0c;对主要云服务器厂商在排行榜中占据重要位置的原因和优势进行深度分析&#xff1a; 一、全球“三巨头”…...

JAVA后端开发——多租户

数据隔离是多租户系统中的核心概念&#xff0c;确保一个租户&#xff08;在这个系统中可能是一个公司或一个独立的客户&#xff09;的数据对其他租户是不可见的。在 RuoYi 框架&#xff08;您当前项目所使用的基础框架&#xff09;中&#xff0c;这通常是通过在数据表中增加一个…...

Java求职者面试指南:Spring、Spring Boot、MyBatis框架与计算机基础问题解析

Java求职者面试指南&#xff1a;Spring、Spring Boot、MyBatis框架与计算机基础问题解析 一、第一轮提问&#xff08;基础概念问题&#xff09; 1. 请解释Spring框架的核心容器是什么&#xff1f;它在Spring中起到什么作用&#xff1f; Spring框架的核心容器是IoC容器&#…...