Skip to main content
BM25(维基百科)也称为 Okapi BM25,是信息检索系统中用于估计文档与给定搜索查询相关性的排名函数。 BM25Retriever 检索器使用 rank_bm25 包。
pip install -qU  rank_bm25
from langchain_community.retrievers import BM25Retriever

从文本创建新检索器

retriever = BM25Retriever.from_texts(["foo", "bar", "world", "hello", "foo bar"])

从文档创建新检索器

现在你可以用创建的文档创建新的检索器。
from langchain_core.documents import Document

retriever = BM25Retriever.from_documents(
    [
        Document(page_content="foo"),
        Document(page_content="bar"),
        Document(page_content="world"),
        Document(page_content="hello"),
        Document(page_content="foo bar"),
    ]
)

使用检索器

现在我们可以使用检索器了!
result = retriever.invoke("foo")
result
[Document(metadata={}, page_content='foo'),
 Document(metadata={}, page_content='foo bar'),
 Document(metadata={}, page_content='hello'),
 Document(metadata={}, page_content='world')]

预处理函数

向检索器传递自定义预处理函数以改善搜索结果。在单词级别对文本进行分词可以增强检索效果,尤其是在使用 Chroma、Pinecone 或 Faiss 等向量存储处理分块文档时。
import nltk

nltk.download("punkt_tab")
from nltk.tokenize import word_tokenize

retriever = BM25Retriever.from_documents(
    [
        Document(page_content="foo"),
        Document(page_content="bar"),
        Document(page_content="world"),
        Document(page_content="hello"),
        Document(page_content="foo bar"),
    ],
    k=2,
    preprocess_func=word_tokenize,
)

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

BM25Plus 变体

  • BM25Retriever 还支持 BM25Plus 变体,该变体旨在减少标准 BM25 中对短文档的偏向。
  • BM25Plus 确保匹配词总能贡献正分,这对于检索增强生成(RAG)工作流中常用的短文本、段落或分块文档可以改善召回率。
默认情况下,BM25Retriever 使用标准 BM25(BM25Okapi)。BM25Plus 必须明确启用。

示例:使用 BM25Plus

from langchain_community.retrievers import BM25Retriever
from langchain_core.documents import Document

docs = [
    Document(
        page_content=(
            "LangChain provides tools for building applications with large language models. "
            "It supports retrieval augmented generation and agents."
        )
    ),

    Document(
        page_content="LangChain retrieval augmented generation"
    ),
]

retriever = BM25Retriever.from_documents(
    docs,
    bm25_variant="plus",
    bm25_params={"delta": 0.5},
)

result = retriever.invoke("retrieval augmented generation")
result
BM25Plus 在以下情况下特别有用:
  • 短文档或段落
  • RAG 系统中的分块文本
  • 文档长度差异较大的语料库
对于长度较为均匀的长文档,标准 BM25 可能提供略高的精确率。