Skip to main content
Elasticsearch 是一个分布式的 RESTful 搜索和分析引擎。它提供了一个分布式的、支持多租户的全文搜索引擎,具有 HTTP Web 接口和无模式的 JSON 文档支持。
在信息检索领域,Okapi BM25(BM 是”最佳匹配”的缩写)是一种排名函数,搜索引擎用它来估计文档与给定搜索查询的相关性。它基于 Stephen E. Robertson、Karen Spärck Jones 等人在 1970 至 1980 年代开发的概率检索框架。
实际排名函数名为 BM25。其更完整的名称 Okapi BM25 包含了第一个使用它的系统名称——Okapi 信息检索系统,该系统于 1980 至 1990 年代在伦敦城市大学实现。BM25 及其较新的变体(如 BM25F——一种可以考虑文档结构和锚文本的 BM25 版本)代表了文档检索中使用的类 TF-IDF 检索函数。
本 notebook 演示如何使用基于 ElasticSearchBM25 的检索器。 有关 BM25 详细信息,请参阅这篇博客文章
pip install -qU  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={})]