如何通过 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.2
   container_name: elasticsearch-8.16.2
   environment:
     - node.name=elasticsearch
     - xpack.security.enabled=false
     - discovery.type=single-node
     - "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"
   ports:
     - 9200:9200
   networks:
     - shared_network

 kibana:
   image: docker.elastic.co/kibana/kibana:8.16.2
   container_name: kibana-8.16.2
   restart: always
   environment:
     - ELASTICSEARCH_URL=http://elasticsearch:9200
   ports:
     - 5601:5601
   depends_on:
     - elasticsearch
   networks:
     - shared_network

networks:
 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 ElasticsearchStore

openai.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_text


embed_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

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

从黑暗到光明:FPC让盲人辅助眼镜成为视障者的生活明灯!【新立电子】

在科技日新月异的今天,智能技术正以前所未有的方式改变着我们的生活。对于视障人士而言,科技的进步更是为他们打开了一扇通往更加独立自主生活的大门。其中,盲人辅助智能眼镜可以成为视障人士日常生活中的得力助手。FPC在AR眼镜中的应用&…

【MySQL】数据类型与表约束

目录 数据类型分类 数值类型 tinyint类型 bit类型 小数类型 字符串类型 日期和时间类型 enum和set 表的约束 空属性 默认值 列描述 zerofill 主键 自增长 唯一键 外键 数据类型分类 数值类型 tinyint类型 MySQL中,整形可以是有符号和无符号的&…

tableau之标靶图、甘特图和瀑布图

一、标靶图 概念 标靶图(Bullet Chart)是一种用于显示数据与目标之间关系的可视化图表,常用于业务和管理报告中。其设计旨在用来比较实际值与目标值,同时展示额外的上下文信息(如趋势)。 作用 可视化目标…

微服务学习(2):实现SpringAMQP对RabbitMQ的消息收发

目录 SpringAMQP是什么 为什么采用SpringAMQP SpringAMQP应用 准备springBoot工程 实现消息发送 SpringAMQP是什么 Spring AMQP是Spring框架下用于简化AMQP(高级消息队列协议)应用开发的一套工具集,主要针对RabbitMQ等消息中间件的集成…

【JAVA SE基础】抽象类和接口

目录 一、前言 二、抽象类 2.1 抽象类的概念 2.2 抽象类语法 2.3 抽象类特性 2.4 抽象类的作用 三、接口 3.1 什么是接口 3.2 语法规则 3.3 接口使用 3.4 接口特性 3.5 实现多接口 3.6 接口间的继承 四、Object类 4.1 获取对象信息( toString() &…

《每天读一个JDK源码》之HashMap解读

📌《每天读一个JDK源码》之HashMap解读 🔗源码定位:java.util.HashMap(建议IDE对照阅读) 今天我们来破解Java集合框架中最精妙的艺术品——HashMap!它不仅是面试必考题(出现率99%)&…

蓝牙接近开关模块感应开锁手机靠近解锁支持HID低功耗

ANS-BT101M是安朔科技推出的蓝牙接近开关模块,低功耗ble5.1,采用UART通信接口,实现手机自动无感连接,无需APP,人靠近车门自动开锁,支持苹果、安卓、鸿蒙系统,也可以通过手机手动开锁或上锁&…

[STM32]从零开始的STM32 BSRR、BRR、ODR寄存器讲解

一、前言 学习STM32一阵子以后,相信大家对STM32 GPIO的控制也有一定的了解了。之前在STM32 LED的教程中也教了大家如何使用寄存器以及库函数控制STM32的引脚从而点亮一个LED,之前的寄存器只是作为一个引入,并没有深层次的讲解,在教…

Linux下的网络通信编程

在不同主机之间,进行进程间的通信。 1解决主机之间硬件的互通 2.解决主机之间软件的互通. 3.IP地址:来区分不同的主机(软件地址) 4.MAC地址:硬件地址 5.端口号:区分同一主机上的不同应用进程 网络协议…

C#高级:结合Linq的SelectMany方法实现笛卡尔积效果

一、笛卡尔积定义 又称直积&#xff0c;表示为X Y&#xff0c;第一个对象是X的成员而第二个对象是Y的所有可能有序对的其中一个成员 二、基础示例 class Program {static void Main(string[] args){try{List<List<string>> input new List<List<string&g…

通信原理速成笔记(信息论及编码)

信息论基础 信息的定义与度量 信息是用来消除不确定性的内容。例如&#xff0c;在猜硬币正反的情境中&#xff0c;结果存在正反两种不确定性&#xff0c;而得知正确结果能消除这种不确定性&#xff0c;此结果即为信息。单个事件的信息量&#xff1a;对于离散信源中的事件xi​&…

MySQL实现文档全文搜索,分词匹配多段落重排展示,知识库搜索原理分享

一、背景 在文档搜索场景中&#xff0c;高效精准的搜索功能至关重要&#xff0c;能提升检索效率&#xff0c;为用户提供精准、快速的信息获取体验&#xff0c;提高工作效率。在文档管理系统里&#xff0c;全文搜索是非常重要的功能之一。随着文档数量增长&#xff0c;如何快速…

力扣hot100——回溯

文章目录 前言55.全排列题目描述思路&#xff1a;DFS回溯code 56.子集题目描述思路&#xff1a;dfs回溯code 57.电话号码的字母组合题目描述思路&#xff1a;DFS回溯code 58.数组总和题目描述题目描述code 59.括号生成题目描述思路&#xff1a;DFS回溯code 60.单词搜索题目描述…

云和恩墨亮相PolarDB开发者大会,与阿里云深化数据库服务合作

2025年2月26日&#xff0c;备受瞩目的阿里云PolarDB开发者大会于北京嘉瑞文化中心盛大举行&#xff0c;众多行业精英齐聚一堂&#xff0c;共襄技术盛会。云和恩墨作为阿里云重要的生态合作伙伴受邀参会。云和恩墨联合创始人兼技术研究院总经理杨廷琨与阿里云智能数据库产品事业…

Vue前端项目构建教程

文章目录 1. 引言2.环境准备2.1 请自行查找资料安装以下开发工具2.2 安装cnpm 3. 创建Vue3项目3.1 安装依赖3.2 项目结构 4. 配置Vue项目4.1 在项目根目录下添加环境变量文件4.2 添加环境变量 5. 常用插件和工具总结 1. 引言 本前端项目将使用Vue3 Vite4构建。 Vue3是目前最…

seacms v9 实现的MySQL注入

目录 过滤关键词information_schema 怎么办 一、环境搭建 二、环境分析 三、源代码分析 1、过滤程序 2、注入点 四、获取数据库名 五、获取数据库表名 六、获取表的列名 七、获取数据信息 过滤关键词information_schema 怎么办 1.、利用sys数据库&#xff08;MySQL 5.…

鸿蒙NEXT开发-元服务和服务卡片的开发

注意&#xff1a;博主有个鸿蒙专栏&#xff0c;里面从上到下有关于鸿蒙next的教学文档&#xff0c;大家感兴趣可以学习下 如果大家觉得博主文章写的好的话&#xff0c;可以点下关注&#xff0c;博主会一直更新鸿蒙next相关知识 目录 1. 元服务基本概念 1.1 基本介绍 1.2 元…

【考试大纲】高级系统架构设计师考试大纲

目录 引言一、 考试说明1.考试目标2.考试要求3.考试科目设置二、 考试范围考试科目1:系统架构设计综合知识考试科目2:系统架构设计案例分析考试科目3:系统架构设计论文引言 最新的系统架构设计师考试大纲出版于 2022 年 11 月,本考试大纲基于此版本整理。 一、 考试说明…

Springboot快速接入豆包大模型

背景 突然接到上面的通知&#xff0c;想要在系统里面接入各大模型的能力&#xff0c;我这边随机选了个豆包&#xff0c;然后快速对接了一下&#xff0c;很顺利&#xff0c;一把过&#xff0c;现在文档的快速入门还是很ok的&#xff0c;在此记录一下过程&#xff0c;给宝子们参考…

Failed to start The PHP FastCGI Process Manager.

报错如下&#xff1a; Job for php-fpm.service failed because the control process exited with error code. See "systemctl status php-fpm.service" and "journalctl -xe" for details. 2月 25 21:49:00 nginx systemd[1]: Starting The PHP FastC…