Skip to main content
Elasticsearch 是一个分布式的、RESTful 搜索和分析引擎。它提供了一个分布式的、支持多租户的全功能搜索引擎,具有 HTTP Web 界面和模式无关的 JSON 文档。
在信息检索领域,[Okapi BM25](https://en.wikipedia.org/wiki/Okapi BM25)(BM 是最佳匹配的缩写)是搜索引擎用于估计文档与给定搜索查询相关性的排名函数。它基于 20 世纪 70 年代和 80 年代由 Stephen E. Robertson、Karen Spärck Jones 等人开发的概率检索框架。
实际排名函数的名称是 BM25。更完整的名称 Okapi BM25 包含了第一个使用该功能的系统的名称,即 Okapi 信息检索系统,该系统于 20 世纪 80 年代和 90 年代在伦敦城市大学实现。BM25 及其更新的变体,例如 BM25F(一种考虑文档结构和锚文本的 BM25 版本),代表了文档检索中使用的类似 TF-IDF 的检索函数。
本笔记本展示了如何使用使用 ElasticSearchBM25 的检索器。 有关 BM25 详情的更多信息,请参见 this blog post
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={})]