如何通过 LlamaIndex 将数据导入 Elasticsearch

作者:来自 Elastic Andre Luiz

逐步介绍如何使用 RAG 和 LlamaIndex 提取数据并进行搜索。

在本文中,我们将使用 LlamaIndex 来索引数据,从而实现一个常见问题搜索引擎。 Elasticsearch 将作为我们的向量数据库,实现向量搜索,而 RAG(Retrieval-Augmented Generation - 检索增强生成)将丰富上下文,提供更准确的响应。

更多阅读,请参阅

  • Elasticsearch:和 LIamaIndex 的集成
  • 使用 Elasticsearch 和 LlamaIndex 进行高级文本检索:句子窗口检索

什么是 LlamaIndex?

LlamaIndex 是一个框架,它有助于创建由大型语言模型 (Language Models - LLM) 驱动的代理(agents)和工作流,以便与特定或私有数据进行交互。它允许将来自各种来源(API、PDF、数据库)的数据与 LLM 集成,从而实现研究、信息提取和生成情境化响应等任务。

关键概念

  • 代理:使用 LLM 执行任务的智能助手,从简单的响应到复杂的动作。
  • 工作流:结合代理、数据连接器和工具以执行高级任务的多步骤流程。
  • 上下文增强:一种利用外部数据丰富 LLM 的技术,克服其训练限制。

LlamaIndex 与 Elasticsearch 集成

Elasticsearch 可以以多种方式与 LlamaIndex 一起使用:

  • 数据源:使用 Elasticsearch Reader 提取文档。
  • 嵌入模型:将数据编码为向量以进行语义搜索。
  • 向量存储:使用 Elasticsearch 作为搜索向量化文档的存储库。
  • 高级存储:配置文档摘要或知识图谱等结构。

使用 LlamaIndex 和 Elasticsearch 构建常见问题解答搜索

数据准备

我们将使用 Elasticsearch 服务常见问题解答作为示例。每个问题都从网站中提取出来并保存在单独的文本文件中。你可以使用任何方法来组织数据;在此示例中,我们选择在本地保存文件。

示例文件:

File Name: what-is-elasticsearch-service.txt
Content: Elasticsearch Service is hosted and managed Elasticsearch and Kibana brought to you by the creators of Elasticsearch. Elasticsearch Service is part of Elastic Cloud and ships with features that you can only get from the company behind Elasticsearch, Kibana, Beats, and Logstash. Elasticsearch is a full text search engine that suits a range of uses, from search on websites to big data analytics and more.

:在上例中,文件名是 what-is-elasticsearch-service.txt。这个文件的内容是 “Elasticsearch Service  is ....”。

保存所有问题后,目录将如下所示:

安装依赖项

我们将使用 Python 语言实现提取和搜索,我使用的版本是 3.9。作为先决条件,需要安装以下依赖项:

llama-index-vector-stores-elasticsearch
llama-index
openai

Elasticsearch 和 Kibana 将使用 Docker 创建,并通过 docker-compose.yml 配置以运行版本 8.16.2。这使得创建本地环境变得更加容易。

docker-compose.yml

version: '3.8'
services:elasticsearch:image: docker.elastic.co/elasticsearch/elasticsearch:8.16.2container_name: elasticsearch-8.16.2environment:- node.name=elasticsearch- xpack.security.enabled=false- discovery.type=single-node- "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"ports:- 9200:9200networks:- shared_networkkibana:image: docker.elastic.co/kibana/kibana:8.16.2container_name: kibana-8.16.2restart: alwaysenvironment:- ELASTICSEARCH_URL=http://elasticsearch:9200ports:- 5601:5601depends_on:- elasticsearchnetworks:- shared_networknetworks:shared_network:

:你也可以参考文章 “使用 start-local 脚本在本地运行 Elasticsearch” 来进行本地部署。

文档采集

这些文档将使用 LlamaIndex 被索引到 Elasticsearch 中。首先,我们使用 SimpleDirectoryReader 加载文件,它允许从本地目录加载文件。加载文档后,我们将使用 VectorStoreIndex 对其进行索引。

documents = SimpleDirectoryReader("./faq").load_data()storage_context = StorageContext.from_defaults(vector_store=es)
index = VectorStoreIndex(documents, storage_context=storage_context, embed_model=embed_model)

LlamaIndex 中的向量存储负责存储和管理文档嵌入。 LlamaIndex 支持不同类型的向量存储,在本例中,我们将使用 Elasticsearch。在 StorageContext 中,我们配置 Elasticsearch 实例。由于上下文是本地的,因此不需要额外的参数。其他环境的配置,请参考文档查看必要参数:ElasticsearchStore 配置。

默认情况下,LlamaIndex 使用 OpenAI text-embedding-ada-002 模型来生成嵌入。但是,在这个例子中,我们将使用 text-embedding-3-small 模型。值得注意的是,使用该模型需要 OpenAI API 密钥。

以下是文档提取的完整代码。

import openai
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader, StorageContext
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.vector_stores.elasticsearch import ElasticsearchStoreopenai.api_key = os.environ["OPENAI_API_KEY"]es = ElasticsearchStore(index_name="faq",es_url="http://localhost:9200"
)def format_title(filename):filename_without_ext = filename.replace('.txt', '')text_with_spaces = filename_without_ext.replace('-', ' ')formatted_text = text_with_spaces.title()return formatted_textembed_model = OpenAIEmbedding(model="text-embedding-3-small")documents = SimpleDirectoryReader("./faq").load_data()for doc in documents:doc.metadata['title'] = format_title(doc.metadata['file_name'])storage_context = StorageContext.from_defaults(vector_store=es)
index = VectorStoreIndex(documents, storage_context=storage_context, embed_model=embed_model)

执行后,文档将被索引到 faq 索引中,如下所示:

使用 RAG 搜索

为了执行搜索,我们配置 ElasticsearchStore 客户端,并使用 Elasticsearch URL 设置 index_namees_url 字段。在 retrieval_strategy 中,我们定义了用于向量搜索的 AsyncDenseVectorStrategy。还有其他策略可用,例如 AsyncBM25Strategy(关键字搜索)和 AsyncSparseVectorStrategy(稀疏向量)。更多详细信息请参阅官方文档。

es = ElasticsearchStore(index_name="faq",es_url="http://localhost:9200",retrieval_strategy=AsyncDenseVectorStrategy()
)

接下来,将创建一个 VectorStoreIndex 对象,我们在其中使用 ElasticsearchStore 对象配置 vector_store。使用 as_retriever 方法,我们对查询最相关的文档进行搜索,并通过 similarity_top_k 参数将返回的结果数设置为 5。

   index = VectorStoreIndex.from_vector_store(vector_store=es)retriever = index.as_retriever(similarity_top_k=5)results = retriever.retrieve(query)

下一步是 RAG。向量搜索的结果被纳入 LLM 的格式化提示中,从而能够根据检索到的信息做出情境化响应。

在 PromptTemplate 中我们定义了提示格式,其中包括:

  • Context ({context_str}):检索器检索到的文档。
  • Query({query_str}):用户的问题。
  • Instructions:指导模型根据上下文做出反应,而不依赖外部知识。

最后,LLM 处理提示并返回精确且具有上下文的响应。

llm = OpenAI(model="gpt-4o")
context_str = "\n\n".join([n.node.get_content() for n in results])
response = llm.complete(qa_prompt.format(context_str=context_str, query_str=query)
)print("Answer:")
print(response)

完整代码如下:

es = ElasticsearchStore(index_name="faq",es_url="http://localhost:9200",retrieval_strategy=AsyncDenseVectorStrategy()
)def print_results(results):for rank, result in enumerate(results, start=1):title = result.metadata.get("title")score = result.get_score()text = result.get_text()print(f"{rank}. title={title} \nscore={score} \ncontent={text}")def search(query: str):index = VectorStoreIndex.from_vector_store(vector_store=es)retriever = index.as_retriever(similarity_top_k=10)results = retriever.retrieve(QueryBundle(query_str=query))print_results(results)qa_prompt = PromptTemplate("You are a helpful and knowledgeable assistant.""Your task is to answer the user's query based solely on the context provided below.""Do not use any prior knowledge or external information.\n""---------------------\n""Context:\n""{context_str}\n""---------------------\n""Query: {query_str}\n""Instructions:\n""1. Carefully read and understand the context provided.\n""2. If the context contains enough information to answer the query, provide a clear and concise answer.\n""3. Do not make up or guess any information.\n""Answer: ")llm = OpenAI(model="gpt-4o")context_str = "\n\n".join([n.node.get_content() for n in results])response = llm.complete(qa_prompt.format(context_str=context_str, query_str=query))print("Answer:")print(response)question = "Elastic services are free?"
print(f"Question: {question}")
search(question)

现在我们可以执行搜索,例如 “Elastic services are free?” 并根据常见问题数据本身获得情境化的响应。

Question: Elastic services are free?
Answer:
Elastic services are not entirely free. However, there is a 14-day free trial available for exploring Elastic solutions. After the trial, access to features and services depends on the subscription level.

为了生成此响应,使用了以下文档:

1. title=Can I Try Elasticsearch Service For Free 
score=1.0 
content=Yes, sign up for a 14-day free trial. The trial starts the moment a cluster is created.
During the free trial period get access to a deployment to explore Elastic solutions for Enterprise Search, Observability, Security, or the latest version of the Elastic Stack.2. title=Do You Offer Elastic S Commercial Products 
score=0.9941274512218439 
content=Yes, all Elasticsearch Service customers have access to basic authentication, role-based access control, and monitoring.
Elasticsearch Service Gold, Platinum and Enterprise customers get complete access to all the capabilities in X-Pack: Security, Alerting, Monitoring, Reporting, Graph Analysis & Visualization. Contact us to learn more.3. title=What Is Elasticsearch Service 
score=0.9896776845746571 
content=Elasticsearch Service is hosted and managed Elasticsearch and Kibana brought to you by the creators of Elasticsearch. Elasticsearch Service is part of Elastic Cloud and ships with features that you can only get from the company behind Elasticsearch, Kibana, Beats, and Logstash. Elasticsearch is a full text search engine that suits a range of uses, from search on websites to big data analytics and more.4. title=Can I Run The Full Elastic Stack In Elasticsearch Service 
score=0.9880631561979476 
content=Many of the products that are part of the Elastic Stack are readily available in Elasticsearch Service, including Elasticsearch, Kibana, plugins, and features such as monitoring and security. Use other Elastic Stack products directly with Elasticsearch Service. For example, both Logstash and Beats can send their data to Elasticsearch Service. What is run is determined by the subscription level.5. title=What Is The Difference Between Elasticsearch Service And The Amazon Elasticsearch Service 
score=0.9835054890793161 
content=Elasticsearch Service is the only hosted and managed Elasticsearch service built, managed, and supported by the company behind Elasticsearch, Kibana, Beats, and Logstash. With Elasticsearch Service, you always get the latest versions of the software. Our service is built on best practices and years of experience hosting and managing thousands of Elasticsearch clusters in the Cloud and on premise. For more information, check the following Amazon and Elastic Elasticsearch Service comparison page.
Please note that there is no formal partnership between Elastic and Amazon Web Services (AWS), and Elastic does not provide any support on the AWS Elasticsearch Service.

结论

使用 LlamaIndex,我们演示了如何创建一个高效的常见问题搜索系统,并支持 Elasticsearch 作为向量数据库。使用嵌入来提取和索引文档,从而实现向量搜索。通过 PromptTemplate,搜索结果被纳入上下文并发送到 LLM,LLM 根据检索到的文档生成精确且情境化的响应。

该工作流程将信息检索与情境化响应生成相结合,以提供准确且相关的结果。

参考

  • https://www.elastic.co/guide/en/cloud/current/ec-faq-getting-started.html
  • https://docs.llamaindex.ai/en/stable/api_reference/readers/elasticsearch/
  • https://docs.llamaindex.ai/en/stable/module_guides/indexing/vector_store_index/
  • https://docs.llamaindex.ai/en/stable/examples/query_engine/custom_query_engine/
  • https://www.elastic.co/search-labs/integrations/llama-index

想要获得 Elastic 认证吗?了解下一期 Elasticsearch 工程师培训何时举行!

Elasticsearch 包含许多新功能,可帮助你为你的用例构建最佳的搜索解决方案。深入了解我们的示例笔记本以了解更多信息,开始免费云试用,或立即在本地机器上试用 Elastic。

原文:How to ingest data to Elasticsearch through LlamaIndex - Elasticsearch Labs

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

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

相关文章

yunedit-post ,api测试比postman更好

postman应该是大家最熟悉的api测试软件了,但是由于它是外国软件,使用它的高端功能注册和缴费都比较麻烦。生成在线文档分享也经常无法访问被拦截掉。 这里可以推荐一下yunedit-post,该有的功能都有。 https://www.yunedit.com/postdetail …

Gopeed 各种类型的文件资源下载器 v1.6.7 中文版

Gopeed 是一款由 Go 和 Flutter 开发的下载器。它具有简洁美观的界面以及强大的功能,支持 HTTP、BitTorrent、Magnet 等协议,并且可以在全平台上使用。 开发语言及技术:Gopeed 采用 Go 和 Flutter 进行开发。Go 语言具有高效、简洁的特点&am…

3d投影到2d python opencv

目录 cv2.projectPoints 投影 矩阵计算投影 cv2.projectPoints 投影 cv2.projectPoints() 是 OpenCV 中的一个函数,用于将三维空间中的点(3D points)投影到二维图像平面上。这在计算机视觉中经常用于相机标定、物体姿态估计、3D物体与2D图…

Linux操作系统5-进程信号3(信号产生总结与核心转储)

上篇文章:Linux操作系统5-进程信号2(信号的4种产生方式,signal系统调用)-CSDN博客 本篇Gitee仓库:myLerningCode/l25 橘子真甜/Linux操作系统与网络编程学习 - 码云 - 开源中国 (gitee.com) 本篇重点:核心…

Linux《基础开发工具(上)》

在之前的篇章当中我们已经了解了Linux当中基本的指令以及相关的知识,那么接下来在本篇当中就开始学基本的开发工具,在此我们一共要了解6大开发工具,在此将这些工具的学习分为上中下篇,在本篇当中我们首先要来学习的是yun以及vim,一…

kali liux的下载

Kali Linux | Penetration Testing and Ethical Hacking Linux Distributionhttps://www.kali.org/ VMware虚拟机https://pan.quark.cn/s/aa869ffbf184 【补充一个今天学到的知识昂和内容无关:(遥感)指非接触的远距离探测技术,使用传感器探…

微软AI900认证备考全攻略:开启AI职业进阶之路

在当今数字化时代,人工智能(AI)正深刻地改变着我们的工作和生活。微软AI900认证作为AI领域的权威认证之一,不仅为技术爱好者提供了深入探索AI的机会,更是开启AI职业进阶之路的重要敲门砖。以下是一份全面的备考攻略&am…

【Mark】记录用宝塔+Nginx+worldpress+域名遇到的跨域,301,127.0.0.1,CSS加载失败问题

背景 想要用宝塔搭建worldpress,然后用域名直接转https,隐藏掉ipport。 结果被折磨了1天,一直在死活在301,127.0.0.1打转 还有css加载不了的情况 因为worldpress很多是301重定向的,所以改到最后我都不知道改了什么&am…

算法题001——移动零

移动零 力扣——移动零点击链接即可跳转 这道题的数组被划分为两个区间,前一个区间为 非零元素,而后一个指针是 零元素 我们运用双指针,先定义两个指针,分别为 dest 和 cur , cur用来遍历整个数组,而 dest 表示我们…

Selenium自动化测试:如何搭建自动化测试环境,搭建环境过程应该注意的问题

最近也有很多人私下问我,selenium学习难吗,基础入门的学习内容很多是3以前的版本资料,对于有基础的人来说,3到4的差别虽然有,但是不足以影响自己,但是对于没有学过的人来说,通过资料再到自己写的…

mysql 全方位安装教程

下载 MySQL 【官网下载地址】 注意要选择较大的哪个安装包,小的安装包是一个安装器。 我们不用登录,直接下载 直接运行下载好的安装包 MySQL如果是 安装包安装, 可以图形化界面自主配置 如果是压缩包解压, 可以配置 配置文件, 可以解压安装到指定的…

深入刨析 之C++ string类

欢迎来到干货小仓库!!! 没有完美的计划,每个人都在试验的过程中渐渐清晰!!! 1.标准库的string类 a. string是表示字符串的字符串类。 b. 该类的接口与常规容器的接口基本相同,再添加了一些专门用来操作string的常规操…

【AI论文】MedVLM-R1:通过强化学习激励视觉语言模型(VLMs)的医疗推理能力

摘要:推理是推进医学影像分析的关键前沿领域,其中透明度和可信度对于赢得临床医生信任和获得监管批准起着核心作用。尽管医学视觉语言模型(VLMs)在放射学任务中展现出巨大潜力,但大多数现有VLM仅给出最终答案&#xff…

深入理解并实现自定义 unordered_map 和 unordered_set

亲爱的读者朋友们😃,此文开启知识盛宴与思想碰撞🎉。 快来参与讨论💬,点赞👍、收藏⭐、分享📤,共创活力社区。 在 C 的标准模板库(STL)中,unorder…

使用ChatGPT-Deep Reaserch两步给出文献综述!

文献综述是学术论文写作中不可或缺的一部分,它不仅是对已有研究的梳理和总结,更是为后续研究奠定理论基础的关键步骤。通过文献综述研究者能够全面了解当前研究领域的现状、主要观点和研究方法,从而找到自己研究的切入点和创新点。这一过程需…

[Java基础] JVM常量池介绍(BeanUtils.copyProperties(source, target)中的属性值引用的是同一个对象吗)

文章目录 1. JVM内存模型2. 常量池中有什么类型?3. 常量池中真正存储的内容是什么4. 判断一个字符串(引用)是否在常量池中5. BeanUtils.copyProperties(source, target)中的属性值引用的是同一个对象吗?6. 获取堆内存使用情况、非堆内存使用情况 1. JVM内…

塔能科技:工厂智慧照明,从底层科技实现照明系统的智能化控制

在全球节能减碳和智慧生活需求激增的背景下,基于“用软件定义硬件,让物联运维更简捷更节能”的产品理念,塔能科技的智慧照明一体化方案如新星般崛起,引领照明行业新方向。现在,我们来深入探究其背后的创新技术。该方案…

RabbitMq-消息确认机制-消息队列可靠投递

RabbitMq-消息确认机制-消息队列可靠投递 发送端确认 ConfirmCallback 在spring中开启ConfirmCallback, springboot rabbitmq属性配置spring.rabbitmq.publisher-confirm和spring.rabbitmq.publisher-confirm-type详解_弃用的配置属性 spring.rabbitmq.publisher-…

水滴tabbar canvas实现思路

废话不多说之间看效果图,只要解决了这个效果水滴tabbar就能做出来了 源码地址 一、核心实现步骤分解 布局结构搭建 使用 作为绘制容器 设置 width=600, height=200 基础尺寸 通过 JS 动态计算实际尺寸(适配高清屏) function initCanvas() {// 获取设备像素比(解决 Re…

散户如何实现自动化交易下单——篇1:体系介绍与获取同花顺资金账户和持仓信息

一、为什么要实现自动化交易 在瞬息万变的金融市场中,越来越多的散户投资者开始尝试构建自己的交易策略:有人通过技术指标捕捉趋势突破,有人利用基本面分析挖掘低估标的,还有人设计出复杂的网格交易或均值回归模型。然而&a…