使用 LlamaIndex 和 Milvus 进行全文搜索
全文搜索采用精确关键词匹配,通常利用 BM25 等算法根据相关性对文档进行排序。在检索增强生成(RAG)系统中,该方法通过检索相关文本来增强 AI 生成的响应。
与此同时,语义搜索通过解读上下文含义来提供更广泛的搜索结果。将这两种方法结合起来,可以形成一种混合搜索,从而提升信息检索效果——特别是在单一方法难以满足需求的情况下。
借助Milvus 2.5 的稀疏 BM25 方法,原始文本会自动转换为稀疏向量。这消除了手动生成稀疏嵌入的需求,并支持一种在语义理解与关键词相关性之间取得平衡的混合搜索策略。
在本教程中,您将学习如何使用 LlamaIndex 和 Milvus,基于全文搜索和混合搜索构建 RAG 系统。我们将首先实现纯全文搜索,然后通过集成语义搜索来增强其功能,从而获得更全面的搜索结果。
在继续本教程之前,请确保您熟悉全文搜索以及在 LlamaIndex 中使用 Milvus 的基础知识。
先决条件
安装依赖项
开始之前,请确保已安装以下依赖项:
$ $pip install llama-index-vector-stores-milvus
$ $pip install llama-index-embeddings-openai
$ $pip install llama-index-llms-openai
如果您使用的是 Google Colab,可能需要重启运行时(导航至界面顶部的“Runtime”菜单,并从下拉菜单中选择“Restart session”)。
设置账户
本教程使用 OpenAI 进行文本 Embeddings 和答案生成。您需要准备OpenAI API 密钥。
import openai
openai.api_key = "sk-"
若要使用 Milvus 向量存储,请指定您的 Milvus 服务器URI (可选:TOKEN )。要启动 Milvus 服务器,您可以按照Milvus 安装指南进行配置,或者直接免费试用Zilliz Cloud。
目前,Milvus Standalone、Milvus Distributed 和 Zilliz Cloud 均支持全文搜索,但 Milvus Lite 暂不支持(计划在未来实现)。如需了解更多信息,请联系 support@zilliz.com。
URI = "http://localhost:19530"
# TOKEN = ""
下载示例数据
运行以下命令,将示例文档下载到“data/paul_graham”目录中:
$ mkdir -p 'data/paul_graham/'
$ $wget 'https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt' -O 'data/paul_graham/paul_graham_essay.txt'
--2025-03-27 07:49:01-- https://raw.githubusercontent.com/run-llama/llama_index/main/docs/docs/examples/data/paul_graham/paul_graham_essay.txt
Resolving raw.githubusercontent.com (raw.githubusercontent.com)... 185.199.108.133, 185.199.109.133, 185.199.110.133, ...
Connecting to raw.githubusercontent.com (raw.githubusercontent.com)|185.199.108.133|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 75042 (73K) [text/plain]
Saving to: ‘data/paul_graham/paul_graham_essay.txt’
data/paul_graham/pa 100%[===================>] 73.28K --.-KB/s in 0.07s
2025-03-27 07:49:01 (1.01 MB/s) - ‘data/paul_graham/paul_graham_essay.txt’ saved [75042/75042]
支持全文搜索的 RAG
将全文搜索集成到 RAG 系统中,可在语义搜索与精确且可预测的基于关键词的检索之间取得平衡。您也可以选择仅使用全文搜索,但为了获得更好的搜索结果,建议将全文搜索与语义搜索结合使用。在此演示中,我们将展示纯全文搜索和混合搜索两种模式。
开始时,请使用SimpleDirectoryReaderLoad 加载保罗·格雷厄姆(Paul Graham)的散文《我做过什么》(What I Worked On):
from llama_index.core import SimpleDirectoryReader
documents = SimpleDirectoryReader("./data/paul_graham/").load_data()
# Let's take a look at the first document
print("Example document:\n", documents[0])
Example document:
Doc ID: 16b7942f-bf1a-4197-85e1-f31d51ea25a9
Text: What I Worked On February 2021 Before college the two main
things I worked on, outside of school, were writing and programming. I
didn't write essays. I wrote what beginning writers were supposed to
write then, and probably still are: short stories. My stories were
awful. They had hardly any plot, just characters with strong feelings,
which I ...
基于 BM25 的全文搜索
LlamaIndex 的MilvusVectorStore 支持全文搜索,可实现高效的基于关键词的检索。通过使用内置函数(如sparse_embedding_function ),它会应用 BM25 评分算法对搜索结果进行排序。
在本节中,我们将演示如何使用 BM25 实现全文搜索的 RAG 系统。
from llama_index.core import VectorStoreIndex, StorageContext
from llama_index.vector_stores.milvus import MilvusVectorStore
from llama_index.vector_stores.milvus.utils import BM25BuiltInFunction
from llama_index.core import Settings
# Skip dense embedding model
Settings.embed_model = None
# Build Milvus vector store creating a new collection
vector_store = MilvusVectorStore(
uri=URI,
# token=TOKEN,
enable_dense=False,
enable_sparse=True, # Only enable sparse to demo full text search
sparse_embedding_function=BM25BuiltInFunction(),
overwrite=True,
)
# Store documents in Milvus
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(documents, storage_context=storage_context)
Embeddings have been explicitly disabled. Using MockEmbedding.
上述代码将示例文档插入 Milvus,并构建索引以启用 BM25 排序功能,从而实现全文搜索。该代码禁用了密集嵌入,并使用默认参数调用 `BM25BuiltInFunction `。
您可以在BM25BuiltInFunction 参数中指定输入和输出字段:
input_field_names (str): 输入文本字段(默认:“text”)。该字段指定BM25算法所应用的文本字段。若使用自有Collection且文本字段名称不同,请修改此参数。output_field_names (str): 用于存储此 BM25 函数输出结果的字段(默认:“sparse_embedding”)。
配置好向量存储后,您即可使用 Milvus 并设置查询模式为“sparse”或“text_search”来执行全文搜索查询:
import textwrap
query_engine = index.as_query_engine(
vector_store_query_mode="sparse", similarity_top_k=5
)
answer = query_engine.query("What did the author learn at Viaweb?")
print(textwrap.fill(str(answer), 100))
The author learned several important lessons at Viaweb. They learned about the importance of growth
rate as the ultimate test of a startup, the value of building stores for users to understand retail
and software usability, and the significance of being the "entry level" option in a market.
Additionally, they discovered the accidental success of making Viaweb inexpensive, the challenges of
hiring too many people, and the relief felt when the company was acquired by Yahoo.
自定义文本分析器
分析器在全文搜索中起着至关重要的作用,它将句子拆分为词素,并执行词汇处理(如词干提取和停用词过滤)。分析器通常具有语言特异性。更多详细信息,请参阅《Milvus 分析器指南》。
Milvus 支持两种类型的分析器:内置分析器和 自定义分析器。默认情况下,BM25BuiltInFunction 使用标准的内置分析器,该分析器基于标点符号对文本进行分词。
若要使用其他分析器或自定义现有分析器,可向analyzer_params 参数传递相应值:
bm25_function = BM25BuiltInFunction(
analyzer_params={
"tokenizer": "standard",
"filter": [
"lowercase", # Built-in filter
{"type": "length", "max": 40}, # Custom cap size of a single token
{"type": "stop", "stop_words": ["of", "to"]}, # Custom stopwords
],
},
enable_match=True,
)
结合Rerankers的混合搜索
混合搜索系统结合了语义搜索和全文搜索,可优化 RAG 系统的检索性能。
以下示例使用 OpenAI Embeddings 模型进行语义搜索,并使用 BM25 进行全文搜索:
# Create index over the documnts
vector_store = MilvusVectorStore(
uri=URI,
# token=TOKEN,
# enable_dense=True, # enable_dense defaults to True
dim=1536,
enable_sparse=True,
sparse_embedding_function=BM25BuiltInFunction(),
overwrite=True,
# hybrid_ranker="RRFRanker", # hybrid_ranker defaults to "RRFRanker"
# hybrid_ranker_params={}, # hybrid_ranker_params defaults to {}
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
documents,
storage_context=storage_context,
embed_model="default", # "default" will use OpenAI embedding
)
工作原理
该方法将文档存储在包含两个向量字段的 Milvus Collection 中:
embedding:由 OpenAI 嵌入模型生成的用于语义搜索的密集 Embeddings。sparse_embedding: 通过 BM25BuiltInFunction 计算得到的、用于全文搜索的稀疏 Embeddings。
此外,我们还应用了基于“RRFRanker”且采用默认参数的重新排序策略。若需自定义重新排序器,您可以按照《Milvus 重新排序指南》配置hybrid_ranker 和hybrid_ranker_params 。
现在,让我们通过一个示例查询来测试 RAG 系统:
# Query
query_engine = index.as_query_engine(
vector_store_query_mode="hybrid", similarity_top_k=5
)
answer = query_engine.query("What did the author learn at Viaweb?")
print(textwrap.fill(str(answer), 100))
The author learned several important lessons at Viaweb. These included the importance of
understanding growth rate as the ultimate test of a startup, the impact of hiring too many people,
the challenges of being at the mercy of investors, and the relief experienced when Yahoo bought the
company. Additionally, the author learned about the significance of user feedback, the value of
building stores for users, and the realization that growth rate is crucial for the long-term success
of a startup.
这种混合方法通过同时利用语义检索和基于关键词的检索,确保了 RAG 系统能够提供更准确、更具上下文意识的响应。