如何通过 LlamaIndex 将数据导入 Elasticsearch

news2025/7/12 10:52:40

作者:来自 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

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

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

相关文章

Boosting

Boosting 学习目标 知道boosting集成原理和实现过程知道bagging和boosting集成的区别知道AdaBoost集成原理 Boosting思想 Boosting思想图 每一个训练器重点关注前一个训练器不足的地方进行训练通过加权投票的方式,得出预测结果串行的训练方式 1 什么是boosting 随着…

【通俗讲解电子电路】——从零开始理解生活中的电路(一)

导言:电子电路为什么重要? ——看不见的“魔法”,如何驱动你的生活? 清晨,当你的手机闹钟响起时,你可能不会想到,是电子电路在精准控制着时间的跳动;当你用微波炉加热早餐时&#…

LeetCode72编辑距离(动态规划)

给你两个单词 word1 和 word2, 请返回将 word1 转换成 word2 所使用的最少操作数 。 你可以对一个单词进行如下三种操作: 插入一个字符 删除一个字符 替换一个字符 示例 1: 输入:word1 “horse”, word2 “ros” 输出&#xf…

【K8S】Kubernetes 基本架构、节点类型及运行流程详解(附架构图及流程图)

Kubernetes 架构 k8s 集群 多个 master node 多个 work nodeMaster 节点(主节点):负责集群的管理任务,包括调度容器、维护集群状态、监控集群、管理服务发现等。Worker 节点(工作节点):实际运…

Windows版FFmpeg使用及B站视频下载示例python源码

Windows版FFmpeg使用及B站视频下载示例python源码 FFmpeg介绍和下载 FFmpeg 是一个功能强大、灵活且广泛使用的多媒体处理工具,无论是在专业领域还是日常使用中,都能满足各种多媒体处理需求。FFmpeg 是一个开源项目,遵循 LGPL 或 GPL 许可。…

飞书考勤Excel导入到自己系统

此篇主要用于记录Excel一行中,单条数据的日期拿取,并判断上下班打卡情况。代码可能满足不了大部分需求,目前只够本公司用,如果需要,可以参考。 需要把飞书月度汇总的考勤表导入系统中可以参考下。 下图为需要获取的年…

【leetcode hot 100 560】和为K的子数组

解法一&#xff1a;用左右指针寻找字串&#xff0c;如果和>k&#xff0c;则减少一个数&#xff08;left&#xff09;&#xff1b;如果和<k&#xff0c;则加上一个数&#xff08;right&#xff09;。 class Solution {public int subarraySum(int[] nums, int k) {int nu…

EGO-Planner的无人机视觉选择(yolov5和yolov8)

EGO-Planner的无人机视觉选择&#xff08;yolov5和yolov8&#xff09; 效果 yolov5检测效果 yolov8检测效果 一、YOLOv8 vs YOLOv5&#xff1a;关键差异解析 1. 训练效率&#xff1a;为何YOLOv8更快&#xff1f; 架构轻量化 YOLOv8采用C2f模块&#xff08;Cross Stage Partia…

性能测试分析和调优

步骤 性能调优的步骤 性能调优的步骤&#xff1a; 1.确定问题&#xff1a;根据性能测试的结果来分析确定bug。–测试人员职责 2.分析原因&#xff1a;分析问题产生的原因。----开发人员职责 3.给出解决方案&#xff1a;可以是修改软件配置、增加硬件资源配置、修改代码等----…

阿里云oss文件上传springboot若依java

一、第一步 引入依赖 <!-- 阿里云OSS --> <dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId> </dependency> 二、第二步 application.yml #阿里云oss服务配置 aliyun:oss:endpoint: …

使用create_sql_query_chain工具根据自然语言问题生成SQL查询,踩坑版

1. 开启调试模式 from langchain import debugdebug True # 启用调试模式说明&#xff1a; 这里从 langchain 库中导入了一个名为 debug 的变量&#xff08;或模块&#xff09;&#xff0c;然后将它设置为 True。这通常用来启用调试模式&#xff0c;方便开发者在程序运行时看…

无人机自主导航与避障技术!

自主导航的实现 环境感知&#xff1a;通过传感器&#xff08;如摄像头、激光雷达、超声波传感器等&#xff09;获取周围环境信息。 地图构建&#xff1a;利用SLAM&#xff08;同步定位与地图构建&#xff09;技术&#xff0c;实时生成环境地图并确定无人机的位置。 路径规划…

密码学(哈希函数)

4.1 Hash函数与数据完整性 数据完整性&#xff1a; 检测传输消息&#xff08;加密或未加密&#xff09;的修改。 密码学Hash函数&#xff1a; 构建某些数据的简短“指纹”&#xff1b;如果数据被篡改&#xff0c;则该指纹&#xff08;以高概率&#xff09;不再有效。Hash函数…

嵌入式开发工程师笔试面试指南-HR面试常见问题汇总

在嵌入式领域的招聘面试中,HR 通过一系列精心设计的问题,全面考察候选人的综合素质、专业能力以及与岗位的匹配度。以下从多个关键方面汇总了 HR 在嵌入式面试中常见的问题。 ** 一、语言表达方面 请简单介绍一下你自己这是面试开场常见问题,旨在让候选人做一个自我展示,…

Docker 搭建 Gitlab 服务器 (完整详细版)

参考 Docker 搭建 Gitlab 服务器 (完整详细版)_docker gitlab-CSDN博客 Docker 安装 (完整详细版)_docker安装-CSDN博客 Docker 日常命令大全(完整详细版)_docker命令-CSDN博客 1、Gitlab镜像 # 查找Gitlab镜像 docker search gitlab # 拉取Gitlab镜像 docker pull gitlab/g…

MongoDB安全管理

MongoDB如何鉴权 保证数据的安全性是数据库的重大职责之一。与大多数数据库一样&#xff0c;MongoDB内部提供了一套完整的权限防护机制。如下例所示&#xff1a; mongo --host 127.0.0.1 --port 27017 --username someone --password errorpass --authenticationDatabasestor…

架构案例:从初创互联网公司到分布式存储与反应式编程框架的架构设计

文章目录 引言一、初创互联网公司架构演化案例1. 万级日订单级别架构2. 十万级日订单级别架构3. 百万级日订单级别架构 二、分布式存储系统 Doris 架构案例三、反应式编程框架架构案例总结 引言 分布式架构 今天我们将探讨三种不同类型的架构案例&#xff0c;分别探讨 一个初…

神经网络之CNN图像识别(torch api 调用)

1.简介 CNN 是受生物学上感受野机制启发而提出的。它通过卷积操作自动提取数据中的特征&#xff0c;避免了传统机器学习方法中复杂的特征工程过程&#xff0c;能够自动学习到数据中的有效特征&#xff0c;从而进行分类、识别等任务。 2.结构 2.1卷积&#xff1a; 假设你有一…

使用Truffle、Ganache、MetaMask、Vue+Web3完成的一个简单区块链项目

文章目录 概要初始化Truffle项目创建编写合约编译合约配置Ganache修改truffle-config.js文件编写迁移文件部署合约使用Truffle 控制台使用MetaMask和VueWeb3与链交互 概要 使用Truffle、Ganache、MetaMask、VueWeb3完成的一个简单区块链项目。 初始化Truffle项目 安装好truf…

学生管理前端

文章目录 首页student.html查询功能 首页 SpringBoot前端html页面放在static文件夹下&#xff1a;/src/main/resources/static 默认首页为index.html&#xff0c;我们可以用两个超链接或者两个button跳转到对应的页面。这里只是单纯的跳转页面&#xff0c;不需要提交表单等其…