将 Embedding 模型加载到 Elasticsearch 中 本工作簿使用一个由 Elastic 博客标题组成的简单数据集在 Elasticsearch 中实现 NLP 文本搜索。你将索引博客文档并使用 ingest pipeline 生成文本 embedding。随后通过使用 NLP 模型你可以使用自然语言对这些博客文档进行查询。更多阅读Elasticsearch如何部署文本嵌入模型并将其用于语义搜索前提条件在开始之前请创建一个 Elastic Cloud deployment并启用 autoscale确保至少有一个具有足够4GB内存的机器学习ML节点。同时确保 Elasticsearch 集群正在运行。如果你还没有 Elastic deployment可以注册免费的 Elastic Cloud 试用版。安装软件包并导入模块!python3 -m pip install sentence-transformers2.7.0 eland elasticsearch transformers开始之前你需要安装所有必需的 Python 依赖项。!python3 -m pip install sentence-transformers2.7.0 eland9 elasticsearch9 transformers # 导入模块 from elasticsearch import Elasticsearch from getpass import getpass from urllib.request import urlopen import json from time import sleep部署 NLP 模型我们使用eland工具安装一个text_embedding模型。这里使用all-MiniLM-L6-v2模型将搜索文本转换为 dense vector。该模型会将你的搜索查询转换为向量用于在存储于 Elasticsearch 中的文档集合上执行搜索。安装文本 embedding NLP 模型使用eland_import_hub_model脚本下载并安装all-MiniLM-L6-v2Transformer 模型并将 NLP 的--task-type设置为text_embedding。要获取 Cloud ID请进入 Elastic Cloud在 deployment 概览页面复制 Cloud ID。为了验证请求身份你可以使用 API key。或者也可以使用 Cloud deployment 的用户名和密码。# https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#finding-your-cloud-id ELASTIC_CLOUD_ID getpass(Elastic Cloud ID: ) # https://www.elastic.co/search-labs/tutorials/install-elasticsearch/elastic-cloud#creating-an-api-key ELASTIC_API_KEY getpass(Elastic Api Key: )!eland_import_hub_model \ --cloud-id $ELASTIC_CLOUD_ID \ --hub-model-id sentence-transformers/all-MiniLM-L6-v2 \ --task-type text_embedding \ --es-api-key $ELASTIC_API_KEY \ --start \ --clear-previous连接到 Elasticsearch 集群使用 deployment 的 Cloud ID 和 API Key 创建一个 Elasticsearch client 实例。在本示例中我们使用上一步中的API_KEY和CLOUD_ID。你也可以使用 deployment 的用户名和密码进行身份验证。es Elasticsearch( cloud_idELASTIC_CLOUD_ID, api_keyELASTIC_API_KEY, request_timeout600 ) es.info() # 应返回集群信息创建 Ingest Pipeline我们需要创建一个文本 embedding ingest pipeline为title字段生成向量文本embedding。下面的 pipeline 定义了一个 processor用于调用 NLP 模型执行 inference。# ingest pipeline 定义 PIPELINE_ID vectorize_blogs es.ingest.put_pipeline( idPIPELINE_ID, processors[ { inference: { model_id: sentence-transformers__all-minilm-l6-v2, target_field: text_embedding, field_map: {title: text_field}, } } ], )创建带有 mapping 的索引现在在索引文档之前我们先创建一个具有正确 mapping 的 Elasticsearch 索引。我们添加text_embedding字段用于包含model_id和predicted_value以存储 embedding。# 定义索引名称 INDEX_NAME blogs # 标志用于检查创建索引前是否删除已有索引 SHOULD_DELETE_INDEX True # 定义索引 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, } } # 检查是否需要在创建索引前删除已有索引 if SHOULD_DELETE_INDEX: if es.indices.exists(indexINDEX_NAME): print(Deleting existing %s % INDEX_NAME) es.indices.delete(indexINDEX_NAME, ignore[400, 404]) print(Creating index %s % INDEX_NAME) es.indices.create( indexINDEX_NAME, mappingsINDEX_MAPPING, settingsINDEX_SETTINGS, ignore[400, 404] )将数据索引到 Elasticsearch现在使用 ingest pipeline 索引示例博客数据。注意在开始索引之前请确保你已经启动训练好的模型 deployment。url https://raw.githubusercontent.com/elastic/elasticsearch-labs/main/notebooks/integrations/hugging-face/blogs.json response urlopen(url) titles json.loads(response.read()) actions [] for title in titles: actions.append({index: {_index: blogs}}) actions.append(title) es.bulk(indexblogs, operationsactions) sleep(5)查询数据集下一步是执行查询搜索相关博客。下面的示例使用我们上传到 Elasticsearch 的sentence-transformers__all-minilm-l6-v2模型对model_text: how to track network connections进行搜索。整个过程只需一次查询尽管内部实际上包含两个步骤。首先查询会使用 NLP 模型为搜索文本生成一个向量然后使用该向量在数据集中执行搜索。最终输出将显示按与搜索查询接近程度排序的文档列表。INDEX_NAME blogs source_fields [id, title] query { field: text_embedding.predicted_value, k: 5, num_candidates: 50, query_vector_builder: { text_embedding: { model_id: sentence-transformers__all-minilm-l6-v2, model_text: how to track network connections, } }, } response es.search( indexINDEX_NAME, fieldssource_fields, knnquery, sourceFalse, ) def show_results(results): for result in results: print( f{result[fields][title]}\n fScore: {result[_score]}\n ) show_results(response.body[hits][hits])输出[Brewing in Beats: Track network connections] Score: 0.5917864 [Machine Learning for Nginx Logs - Identifying Operational Issues with Your Website] Score: 0.40109876 [Data Visualization For Machine Learning] Score: 0.39027885 [Logstash Lines: Introduce integration plugins] Score: 0.36899462 [Keeping up with Kibana: This week in Kibana for November 29th, 2019] Score: 0.35690257原文https://www.elastic.co/search-labs/tutorials/examples/nlp-model-vector-search-elasticsearch

相关新闻

最新新闻

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现

SerenityOS 命令行选项解析指南:getopt 与 getopt_long 用法、返回值与底层实现 【免费下载链接】serenity The Serenity Operating System 🐞 项目地址: https://gitcode.com/GitHub_Trending/se/serenity 导读 本文以 getopt(3) 手册 为核心&a…

2026/9/25 12:45:43
轻量服务器还是ECS?大促云服务器选购与避坑实战指南

轻量服务器还是ECS?大促云服务器选购与避坑实战指南

每年大促节点,群里永远有人在问同一个问题:“38元的轻量服务器到底怎么抢?为什么我每次点进去都是已售罄?68元直购和99元的ECS我到底选哪个?”作为一个常年帮团队和自己采购云服务器的老用户,我太清楚这种纠…

2026/9/24 14:25:52
为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南

为 AI 代理的 Review 动作编写 Cedar 审批门控策略:review-agent-governance 策略编写实战指南 【免费下载链接】agents Multi-harness agentic plugin marketplace for Claude Code, Codex, Cursor, OpenCode, GitHub Copilot, and Google Antigravity 项目地址:…

2026/9/24 14:49:33
PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署

PaddleOCR 手写数学公式识别算法 CAN 实战指南:Counting-Aware Network 训练、评估与推理部署 【免费下载链接】PaddleOCR Turn any PDF or image document into structured data for your AI. A powerful, lightweight OCR toolkit that bridges the gap between i…

2026/9/23 8:01:38
Spring源码解析:构造器注入的类型转换与候选匹配机制

Spring源码解析:构造器注入的类型转换与候选匹配机制

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

2026/9/24 14:28:18
openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由

openai-agents-python 多模型接入指南:深入解析 AnyLLMModel 适配层与 any-llm 路由 【免费下载链接】openai-agents-python A lightweight, powerful framework for multi-agent workflows 项目地址: https://gitcode.com/GitHub_Trending/op/openai-agents-pyth…

2026/9/25 15:49:36

日新闻

周新闻