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

news2024/10/3 6:36:43

本博文使用由 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 文件可以在地址下载。

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

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

相关文章

如何做好互联网产品需求分析?看这里!

文章目录 🌟需求分析🍊领域知识分析🍊技术知识分析🎉人工智能技术的基本原理🎉开发工具和组件库🎉数据处理和模型训练🎉代码库和技术标准 🍊数据分析🎉准备数据&#x1f…

途虎养车上市、京东养车“震虎”,如何突围汽车后市场?

“汽车后市场第一股”终于来了! 赶在十一黄金周之前,途虎养车股份有限公司(09690.HK,下称“途虎养车”)于9月26日挂牌港交所,开盘价为28港元/股,与发行价持平;IPO首日报收29.50港元/股,涨幅5.3…

【图像处理GUI】图像颜色过滤、颜色强调、反转颜色等(Matlab代码实现)

💥💥💞💞欢迎来到本博客❤️❤️💥💥 🏆博主优势:🌞🌞🌞博客内容尽量做到思维缜密,逻辑清晰,为了方便读者。 ⛳️座右铭&a…

Tomcat历史版本下载地址(Tomcat7或更早)

官网地址直达 随便选择一个版本 点击找到自己想要的版本下载就可以了!

干洗店会员管理系统上门洗鞋小程序介绍

干洗店管理系统,洗衣洗鞋店收银会员管理小程序,是在传统的洗护行业中,使用现在比较流行的线上下单系统,可以帮助门店实现便捷收银、会员管理、商品销售等功能。 具体如下: 1.会员管理:支持会员储值&#xf…

CSS 之 table 表格布局

一、简介 ​ 除了使用HTML的<table>元素外&#xff0c;我们还可以通过display: table/inline-table; 设置元素内部的布局类型为表格布局。并结合table-cell、table-row等相关CSS属性值可以实现HTML中<table>系列元素的效果&#xff0c;具有表头、表尾、行、单元格…

面试题:如何正确的停掉线程?

文章目录 前言为什么不强制停止如何用 interrupt 停止线程sleep 期间能否感受到中断停止线程的方式有几种总结 前言 启动线程需要调用 Thread 类的 start() 方法&#xff0c;并在 run() 方法中定义需要执行的任务。启动一个线程非常简单&#xff0c;但如果想要正确停止它就没那…

在PicGo上使用github图床解决typora上传csdn图片不显示问题(保姆级教程)

文章目录 在PicGo上使用github图床解决typora上传csdn图片不显示问题&#xff08;保姆级教程&#xff09;1、typora上传csdn图片不显示&#xff08;外链图片转存失败&#xff09;2、PicGo2.1、PicGo下载2.2、PicGo使用2.2.1、对PicGo完成基本的配置2.2.2、配置github图床2.2.3、…

vue3+elementPlus:el-tree复制粘贴数据功能,并且有弹窗组件

在tree控件里添加contextmenu属性表示右键点击事件。 因右键自定义菜单事件需要获取当前点击的位置&#xff0c;所以此处绑定动态样式来控制菜单实时跟踪鼠标右键点击位置。 //html <div class"box-list"><el-tree ref"treeRef" node-key"id…

SCADA系统是什么意思?

监控和数据采集 (SCADA) 是一种计算机控制系统&#xff0c;用于监视和控制工厂过程。该软件使用数据通信、图形用户界面和扩展管理来监视和控制系统。 概述 世界上最大的制造公司也被认为是最受数据驱动的企业。在技​​术能力不断增强的时代&#xff0c;随着 SCADA 等系统的使…

认识python就是这么简单!

我的笔记里的python代码运行环境都是在pycharm软件中运行&#xff0c;所以不去记录如何配置环境变量呀什么的。 python种类 Cpython&#xff1a; Python的官方版本&#xff0c;使用C语言实现&#xff0c;使用最为广泛&#xff0c;CPython实现会将源文件&#xff08;py文件&a…

学生用的台灯护眼的哪种比较好?精选适合学生用的护眼台灯

现代小孩的学习压力确实很大&#xff0c;已经不能和我们以往那种“半大自然化学习”相提并论啦&#xff0c;如今各种学习PAD、电脑网课&#xff0c;成堆的学习资料与作业&#xff0c;恐怕是从小学甚至学前就已经是常态了。而且在平时我们路过学校的时候应该也不难发现&#xff…

为SecureCRT配置密钥验证,实现免密登录远程Linux服务器

本实例以普通用户zhangsan远程连接Linux服务器为例。 一、生成密钥对 在Linux服务器上为普通用户zhangsan远程连接服务器制作密钥对&#xff0c;执行命令如下&#xff1a; [rootServer ~]# su - zhangsan #切换到zhangsan身份登录 [zhangsanServer ~]$ ssh-keygen #生成…

JAVA项目点赞功能如何实现?如何利用缓存优化?如何防止刷赞?

- 普通的点赞如何实现&#xff1f; - 每个人都见过点赞功能&#xff0c;大家想实现一个点赞功能也简单&#xff0c;比如一个简单的文章点赞逻辑如下&#xff1a; 首先需要建个表&#xff0c;记录下点赞人的id&#xff0c;被点赞文章的id&#xff0c;点赞状态三个关键因素即可&a…

【modprobe_path】RWCTF2022-Digging-into-kernel-2

启动脚本&#xff1a; qemu-system-x86_64 \-kernel bzImage \-initrd rootfs.cpio \-append "consolettyS0 root/dev/ram rdinit/sbin/init quiet kaslr" \-cpu kvm64,smep,smap \-monitor null \--nographic \-s 开启了 smep、smap、kaslr保护。 程序分析 单独创…

ceph版本和Ceph的CSI驱动程序

ceph版本和Ceph的CSI驱动程序 ceph查看ceph版本Ceph的CSI驱动程序 ceph ceph版本和Ceph的CSI驱动程序 查看ceph版本 官网ceph-releases-index Ceph的CSI驱动程序 Ceph的CSI驱动程序 https://github.com/ceph/ceph-csi

Docker项目部署lnmp+wordpress

一.项目环境 公司在实际的生产环境中&#xff0c;需要使用Docker 技术在一台主机上创建LNMP服务并运行Wordpress网站平台。然后对此服务进行相关的性能调优和管理工作。 1.1 环境描述 主机 操作系统 IP地址 主要软件 Docker C…

HTTP长连接实现原理

1. HTTP长连接和短连接的定义 HTTP长连接 浏览器向服务器进行一次HTTP会话访问后&#xff0c;并不会直接关闭这个连接&#xff0c;而是会默认保持一段时间&#xff0c;那么下一次浏览器继续访问的时候就会再次利用到这个连接。在HTTP/1.1版本中&#xff0c;默认的连接都是长连…

《Python 自动化办公应用大全》书籍推荐(包邮送书五本)

前言 随着科技的快速发展和智能化办公的需求增加&#xff0c;Python自动化办公成为了一种趋势。Python作为一种高级编程语言&#xff0c;具有简单易学、功能强大和开放源代码等优势&#xff0c;可以帮助我们更高效地完成日常办公任务。 Python自动化办公还可以帮助我们实现更…

数据结构-二叉查找树(BST)

二叉查找树 需要满足这些规则&#xff1a; 左子节点小于父节点右子节点大于父节点 查找的效率 非常好&#xff0c;每次都能根据大小去舍弃另一半的分支&#xff0c;极大的减少的比对次数 具体的性能&#xff0c;取决于树的层数和平衡程度。 BST树的节点 struct Node {No…