ElasticSearch BM25
Elasticsearch 是一个分布式的、基于 RESTful 的搜索和分析引擎。它提供了一个分布式且多租户的全文搜索引擎,具有 HTTP 网页界面和无模式的 JSON 文档。
在信息检索中,Okapi BM25(BM是最佳匹配的缩写)是一种用于搜索引擎的排名函数,用于估计文档与给定搜索查询的相关性。它基于由Stephen E. Robertson、Karen Spärck Jones等人在20世纪70年代和80年代开发的概率检索框架。
The name of the actual ranking function is BM25. The fuller name, Okapi BM25, includes the name of the first system to use it, which was the Okapi information retrieval system, implemented at London's City University in the 1980s and 1990s. BM25 and its newer variants, e.g. BM25F (a version of BM25 that can take document structure and anchor text into account), represent TF-IDF-like retrieval functions used in document retrieval.
这个笔记本展示了如何使用一个基于ElasticSearch和BM25的检索器。
对于BM25的详细信息,请参见这篇博客文章。
%pip install --upgrade --quiet elasticsearch
from langchain_community.retrievers import (
ElasticSearchBM25Retriever,
)
创建新的检索器
elasticsearch_url = "http://localhost:9200"
retriever = ElasticSearchBM25Retriever.create(elasticsearch_url, "langchain-index-4")
# Alternatively, you can load an existing index
# import elasticsearch
# elasticsearch_url="http://localhost:9200"
# retriever = ElasticSearchBM25Retriever(elasticsearch.Elasticsearch(elasticsearch_url), "langchain-index")
添加文本(如果需要)
我们也可以选择性地向检索器添加文本(如果它们尚未包含在其中)
retriever.add_texts(["foo", "bar", "world", "hello", "foo bar"])
['cbd4cb47-8d9f-4f34-b80e-ea871bc49856',
'f3bd2e24-76d1-4f9b-826b-ec4c0e8c7365',
'8631bfc8-7c12-48ee-ab56-8ad5f373676e',
'8be8374c-3253-4d87-928d-d73550a2ecf0',
'd79f457b-2842-4eab-ae10-77aa420b53d7']
使用检索器
我们现在已经可以使用检索器了!
result = retriever.invoke("foo")
result
[Document(page_content='foo', metadata={}),
Document(page_content='foo bar', metadata={})]