Elasticsearch:和 LIamaIndex 的集成

LlamaIndex 是一个数据框架,供 LLM 应用程序摄取、构建和访问私有或特定领域的数据。

LlamaIndex 是开源的,可用于构建各种应用程序。 在 GitHub 上查看该项目。

安装

在 Docker 上设置 Elasticsearch

使用以下 docker 命令启动单节点 Elasticsearch 实例。我们可以参考之前的文章 "Elasticsearch:如何在 Docker 上运行 Elasticsearch 8.x 进行本地开发"。我选择不使用安全配置。直接使用 docker compose 来启动 Elasticsearch 及 Kibana:

.env

markdown 复制代码
1.  $ pwd
2.  /Users/liuxg/data/docker8
3.  $ ls -al
4.  total 16
5.  drwxr-xr-x    4 liuxg  staff   128 Jan 16 13:00 .
6.  drwxr-xr-x  193 liuxg  staff  6176 Jan 12 08:31 ..
7.  -rw-r--r--    1 liuxg  staff    21 Jan 16 13:00 .env
8.  -rw-r--r--    1 liuxg  staff   733 Mar 14  2023 docker-compose.yml
9.  $ cat .env
10.  STACK_VERSION=8.11.3

docker-compose.yml

yaml 复制代码
1.  version: "3.9"
2.  services:
3.    elasticsearch:
4.      image: elasticsearch:${STACK_VERSION}
5.      container_name: elasticsearch
6.      environment:
7.        - discovery.type=single-node
8.        - ES_JAVA_OPTS=-Xms1g -Xmx1g
9.        - xpack.security.enabled=false
10.      volumes:
11.        - type: volume
12.          source: es_data
13.          target: /usr/share/elasticsearch/data
14.      ports:
15.        - target: 9200
16.          published: 9200
17.      networks:
18.        - elastic

20.    kibana:
21.      image: kibana:${STACK_VERSION}
22.      container_name: kibana
23.      ports:
24.        - target: 5601
25.          published: 5601
26.      depends_on:
27.        - elasticsearch
28.      networks:
29.        - elastic      

31.  volumes:
32.    es_data:
33.      driver: local

35.  networks:
36.    elastic:
37.      name: elastic
38.      driver: bridge

我们使用如下的命令来启动:

docker-compose up

这样我们就完成了 Elasticsearch 及 Kibana 的安装了。我们的 Elasticsearch 及 Kibana 都没有安全的设置。这个在生产环境中不被推荐使用。

应用设计 - 组装管道

我们将使用 Jupyter notebook 来进行设计。我们在命令行中打入:

jupyter notebook

安装依赖

我们使用如下的命令来安装 Python 的依赖包:

perl 复制代码
pip3 install llama-index openai elasticsearch load_dotenv

我们接下来在当前的工作目录中创建一个叫做 .env 的文件:

.env

ini 复制代码
OPENAI_API_KEY="YourOpenAIKey"

请在 .env 中创建如上所示的变量。你需要把自己的 openai key 写入到上面的文件里。

加载模块及读取环境变量

javascript 复制代码
1.  import logging
2.  import sys
3.  import os
4.  from dotenv import load_dotenv

6.  load_dotenv()

8.  logging.basicConfig(stream=sys.stdout, level=logging.INFO)
9.  logging.getLogger().addHandler(logging.StreamHandler(stream=sys.stdout))

11.  os.environ["OPENAI_API_KEY"] = os.getenv('OPENAI_API_KEY')

13.  import openai

连接到 Elasticsearch

ElasticsearchStore 类用于连接到 Elasticsearch 实例。 它需要以下参数:

  • index_name:Elasticsearch 索引的名称。 必需的。
  • es_client:可选。 预先存在的 Elasticsearch 客户端。
  • es_url:可选。Elasticsearch 网址。
  • es_cloud_id:可选。 Elasticsearch 云 ID。
  • es_api_key:可选。 Elasticsearch API 密钥。
  • es_user:可选。 Elasticsearch 用户名。
  • es_password:可选。 弹性搜索密码。
  • text_field:可选。 存储文本的 Elasticsearch 字段的名称。
  • vector_field:可选。 存储 Elasticsearch 字段的名称嵌入。
  • batch_size:可选。 批量索引的批量大小。 默认为 200。
  • distance_strategy:可选。 用于相似性搜索的距离策略。默认为 "COSINE"。

针对,我们的情况,我们可以使用如下的示例方法来进行本地连接:

ini 复制代码
1.  from llama_index.vector_stores import ElasticsearchStore

3.  es = ElasticsearchStore(
4.      index_,
5.      es_url="http://localhost:9200",
6.  )

我们将在下面的代码中使用上述的方法来连接 Elasticsearch。

加载文档,使用 Elasticsearch 构建 VectorStoreIndex

javascript 复制代码
1.  from llama_index import VectorStoreIndex, SimpleDirectoryReader
2.  from llama_index.vector_stores import ElasticsearchStore

4.  !mkdir -p 'data/paul_graham/'
5.  !wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'

运行完上面的命令后,我们可以在当前的目录下查看:

bash 复制代码
1.  $ pwd
2.  /Users/liuxg/python/elser
3.  $ ls data/paul_graham/
4.  paul_graham_essay.txt

我们可以看到一个叫做 pau_graham_essay.txt 的文件。它的内容如下:

vbnet 复制代码
`

1.  What I Worked On

3.  February 2021

5.  Before college the two main things I worked on, outside of school, were writing and programming. I didn't write essays. I wrote what beginning writers were supposed to write then, and probably still are: short stories. My stories were awful. They had hardly any plot, just characters with strong feelings, which I imagined made them deep.

7.  The first programs I tried writing were on the IBM 1401 that our school district used for what was then called "data processing." This was in 9th grade, so I was 13 or 14. The school district's 1401 happened to be in the basement of our junior high school, and my friend Rich Draves and I got permission to use it. It was like a mini Bond villain's lair down there, with all these alien-looking machines --- CPU, disk drives, printer, card reader --- sitting up on a raised floor under bright fluorescent lights.

9.  ...

11.  The language we used was an early version of Fortran. You had to type programs on punch cards, then stack them in the card reader and press a button to load the program into memory and run it. The result would ordinarily be to print something on the spectacularly loud printer.

13.  I was puzzled by the 1401. I couldn't figure out what to do with it. And in retrospect there's not much I could have done with it. The only form of input to programs was data stored on punched cards, and I didn't have any data stored on punched cards. The only other option was to do things that didn't rely on any input, like calculate approximations of pi, but I didn't know enough math to do anything interesting of that type. So I'm not surprised I can't remember any programs I wrote, because they can't have done much. My clearest memory is of the moment I learned it was possible for programs not to terminate, when one of mine didn't. On a machine without time-sharing, this was a social as well as a technical error, as the data center manager's expression made clear.
14.  ...

16.  Toward the end of the summer I got a big surprise: a letter from the Accademia, which had been delayed because they'd sent it to Cambridge England instead of Cambridge Massachusetts, inviting me to take the entrance exam in Florence that fall. This was now only weeks away. My nice landlady let me leave my stuff in her attic. I had some money saved from consulting work I'd done in grad school; there was probably enough to last a year if I lived cheaply. Now all I had to do was learn Italian.
17.  ...

`![](https://csdnimg.cn/release/blogv2/dist/pc/img/newCodeMoreWhite.png)
ini 复制代码
1.  documents = SimpleDirectoryReader("./data/paul_graham/").load_data()

3.  from llama_index.storage.storage_context import StorageContext

5.  vector_store = ElasticsearchStore(
6.      es_url="http://localhost:9200",
7.      # Or with Elastic Cloud
8.      # es_cloud_id="my_cloud_id",
9.      # es_user="elastic",
10.      # es_password="my_password",
11.      index_,
12.  )

14.  storage_context = StorageContext.from_defaults(vector_store=vector_store)
15.  index = VectorStoreIndex.from_documents(
16.      documents, storage_context=storage_context
17.  )

基本查询

我们将向查询引擎询问有关我们刚刚索引的数据的问题。

ini 复制代码
1.  # set Logging to DEBUG for more detailed outputs
2.  query_engine = index.as_query_engine()
3.  response = query_engine.query("what were his investments in Y Combinator?")
4.  print(response)

元数据过滤器

在这里,我们将使用元数据索引一些文档,以便我们可以将过滤器应用于查询引擎。

ini 复制代码
1.  from llama_index.schema import TextNode

3.  nodes = [
4.      TextNode(
5.          text="The Shawshank Redemption",
6.          metadata={
7.              "author": "Stephen King",
8.              "theme": "Friendship",
9.          },
10.      ),
11.      TextNode(
12.          text="The Godfather",
13.          metadata={
14.              "director": "Francis Ford Coppola",
15.              "theme": "Mafia",
16.          },
17.      ),
18.      TextNode(
19.          text="Beautiful weather",
20.          metadata={
21.              "director": "Mark shuttle",
22.              "theme": "Mafia",
23.          },
24.      ),    
25.      TextNode(
26.          text="Inception",
27.          metadata={
28.              "director": "Christopher Nolan",
29.          },
30.      ),
31.  ]

33.  # initialize the vector store
34.  vector_store_metadata_example = ElasticsearchStore(
35.      index_,
36.      es_url="http://localhost:9200",
37.  )
38.  storage_context = StorageContext.from_defaults(
39.      vector_store=vector_store_metadata_example
40.  )
41.  index1 = VectorStoreIndex(nodes, storage_context=storage_context)

44.  # Metadata filter
45.  from llama_index.vector_stores.types import ExactMatchFilter, MetadataFilters

47.  filters = MetadataFilters(
48.      filters=[ExactMatchFilter(key="theme", value="Mafia")]
49.  )

51.  retriever = index1.as_retriever(filters=filters)

53.  retriever.retrieve("weather is so beautiful")

在上面,我们搜索的是 "weather is so beautiful",从而在两个 theme 为 Mafia 的 Texnode 里,Mark shuttle 位列第一。这个是因为 "weather is so beautiful" 更和 "Beautiful weather" 更为贴近。 如果我们使用如下的查询:

arduino 复制代码
retriever.retrieve("The godfather is a nice person")

很显然,这次我们的搜索结果的排序颠倒过来了。

自定义过滤器和覆盖查询

llama-index 目前仅支持 ExactMatchFilters。 Elasticsearch 支持多种过滤器,包括范围过滤器、地理过滤器等。 要使用这些过滤器,你可以将它们作为字典列表传递给 es_filter 参数。

python 复制代码
1.  def custom_query(query, query_str):
2.      print("custom query", query)
3.      return query

5.  query_engine = index.as_query_engine(
6.      vector_store_kwargs={
7.          "es_filter": [{"match": {"content": "growing up"}}],
8.          "custom_query": custom_query,
9.      }
10.  )

12.  response = query_engine.query("what were his investments in Y Combinator?")
13.  print(response)

为了方便大家学习,我把所有的源码放到 github:github.com/liu-xiao-gu...。其中相关的文件是:

更多阅读:使用 Elasticsearch 和 LlamaIndex 进行高级文本检索:句子窗口检索

相关推荐
risc1234563 小时前
【Elasticsearch】Search Templates(搜索模板)
elasticsearch
元气满满的热码式14 小时前
logstash中的input插件(http插件,graphite插件)
网络·网络协议·http·elasticsearch·云原生
silianpan15 小时前
文档检索服务平台
elasticsearch·搜索引擎·开源
(; ̄ェ ̄)。15 小时前
在nodejs中使用ElasticSearch(二)核心概念,应用
大数据·elasticsearch·搜索引擎
boy快快长大15 小时前
【Elasticsearch】同一台服务器部署集群
服务器·elasticsearch·jenkins
一个儒雅随和的男子16 小时前
Elasticsearch除了用作查找以外,还能可以做什么?
大数据·elasticsearch·搜索引擎
跳跳的向阳花17 小时前
06、ElasticStack系列,第六章:elasticsearch设置密码
大数据·elasticsearch·jenkins
Elastic 中国社区官方博客1 天前
Elasticsearch Open Inference API 增加了对 Jina AI 嵌入和 Rerank 模型的支持
大数据·人工智能·elasticsearch·搜索引擎·ai·全文检索·jina
隔壁老王1561 天前
mysql实时同步到es
数据库·mysql·elasticsearch
SunnyRivers1 天前
关于ES中text类型时间字段范围查询的结构化解决方案
elasticsearch·时间·text·范围查询