Open In Colab GitHub Repository

使用 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 進行文字嵌入與答案生成。您需要準備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 系統中,可平衡語義搜尋與精確且可預測的關鍵字檢索。您亦可選擇僅使用全文搜尋,但為獲得更佳的搜尋結果,建議將全文搜尋與語義搜尋結合使用。在此示範中,我們將分別展示純全文搜尋與混合搜尋。

開始之前,請使用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 演算法應套用的文字欄位。若您使用的是文字欄位名稱不同的自訂集合,請變更此參數。
  • 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,
)

結合重新排序器的混合搜尋

混合搜尋系統結合了語義搜尋與全文搜尋,可優化 RAG 系統中的檢索效能。

以下範例使用 OpenAI 嵌入模型進行語義搜尋,並採用 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 集合中,並包含以下兩種向量場:

  • embedding:由 OpenAI 嵌入模型生成的密集嵌入,用於語義搜尋。
  • sparse_embedding:使用 BM25BuiltInFunction 計算的稀疏嵌入,用於全文檢索。

此外,我們已採用「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 系統能提供更精準且具語境意識的回應。

翻譯者DeepL

免費嘗試托管的 Milvus

Zilliz Cloud 無縫接入,由 Milvus 提供動力,速度提升 10 倍。

開始使用
反饋

這個頁面有幫助嗎?