Skip to main content
Open In Colab在 GitHub 上打开

弹性搜索 BM25

Elasticsearch 是一个分布式 RESTful 搜索和分析引擎。它提供了一个分布式、支持多租户的全文搜索引擎,具有 HTTP Web 界面和无架构的 JSON 文档。

在信息检索中,Okapi BM25(BM 是 best matching 的缩写)是搜索引擎用来估计文档与给定搜索查询的相关性的排名函数。它基于 Stephen E. Robertson、Karen Spärck Jones 等人在 1970 年代和 1980 年代开发的概率检索框架。

实际排名函数的名称是 BM25。更完整的名称 Okapi BM25 包括第一个使用它的系统的名称,即 1980 年代和 1990 年代在伦敦城市大学实施的 Okapi 信息检索系统。BM25 及其较新的变体,例如 BM25F(BM25 的一个版本,可以考虑文档结构和锚文本),代表文档检索中使用的类似 TF-IDF 的检索函数。

此笔记本演示如何使用使用ElasticSearchBM25.

有关 BM25 详细信息的更多信息,请参阅此博客文章

%pip install --upgrade --quiet  elasticsearch
from langchain_community.retrievers import (
ElasticSearchBM25Retriever,
)

Create New Retriever (创建新检索器)

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']

使用 Retriever

我们现在可以使用检索器了!

result = retriever.invoke("foo")
result
[Document(page_content='foo', metadata={}),
Document(page_content='foo bar', metadata={})]