Lucene 作為 Apache 軟體基金會旗下的開源全文檢索工具包,早已成為建立站內搜尋功能的首選方案。其 .NET 移植版 Lucene.NET 完整保留了原版的查詢引擎、索引引擎與文本分析能力,讓 .NET 開發者能輕鬆在專案中整合專業級搜尋功能。本文將從套件導入、索引管理到搜尋實作,完整示範如何在 ASP.NET 專案中落地 Lucene.NET。
可透過 NuGet 安裝 Lucene.Net 及中文分詞器 Lucene.Net.Analysis.PanGu(或其他如 JiebaNet),指令如下:
Install-Package Lucene.Net
Install-Package Lucene.Net.Analysis.PanGu
索引儲存路徑建議寫在 web.config 的 <appSettings> 中,例如:
<add key="IndexPath" value="~/App_Data/LuceneIndex/" />
建立 IndexHelper 靜態類別,統一處理索引的建立、更新與刪除,關鍵點包括:
FSDirectory 管理檔案系統索引目錄IndexWriter.IsLocked / Unlock)PanGuAnalyzer 進行中文分詞id、title、url 設為 NOT_ANALYZED 以利精確比對;body 設為 ANALYZED 支援全文檢索Term("id", ...) 刪除舊文檔,確保冪等性public static class IndexHelper {
private static readonly string IndexPath = ConfigurationManager.AppSettings["IndexPath"];
private static readonly ILog Logger = LogManager.GetLogger(typeof(IndexHelper));
public static void CreateOrUpdate(IndexFileModel item) {
var dirInfo = new DirectoryInfo(Server.MapPath(IndexPath));
var directory = FSDirectory.Open(dirInfo, new NativeFSLockFactory());
bool exists = IndexReader.IndexExists(directory);
if (exists && IndexWriter.IsLocked(directory)) IndexWriter.Unlock(directory);
using (var writer = new IndexWriter(directory, new PanGuAnalyzer(), !exists, IndexWriter.MaxFieldLength.UNLIMITED)) {
writer.DeleteDocuments(new Term("id", item.FileName));
var doc = new Document {
new Field("id", item.FileName, Field.Store.YES, Field.Index.NOT_ANALYZED),
new Field("title", item.FileTitle, Field.Store.YES, Field.Index.NOT_ANALYZED),
new Field("body", item.FileContent, Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS),
new Field("url", item.FilePath, Field.Store.YES, Field.Index.NOT_ANALYZED)
};
writer.AddDocument(doc);
Logger.Debug($"索引 {item.FileName} 建立/更新成功");
}
}
public static void Delete(string id) {
var dirInfo = new DirectoryInfo(Server.MapPath(IndexPath));
var directory = FSDirectory.Open(dirInfo, new NativeFSLockFactory());
if (IndexReader.IndexExists(directory) && IndexWriter.IsLocked(directory)) IndexWriter.Unlock(directory);
using (var writer = new IndexWriter(directory, new PanGuAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED)) {
writer.DeleteDocuments(new Term("id", id));
Logger.Debug($"索引 {id} 刪除成功");
}
}
}
搜尋端使用 IndexSearcher 搭配 MultiFieldQueryParser 跨欄位查詢,支援標題與內容同時檢索。回傳結果可直接映射為 DTO,並配合 TopDocs 實作分頁:
public static List<SearchResult> Search(string keyword, int pageIndex, int pageSize, out int totalHits) {
var dirInfo = new DirectoryInfo(Server.MapPath(IndexPath));
var directory = FSDirectory.Open(dirInfo, new NativeFSLockFactory());
using (var reader = IndexReader.Open(directory, true))
using (var searcher = new IndexSearcher(reader)) {
var parser = new MultiFieldQueryParser(LuceneVersion.LUCENE_30, new[] { "title", "body" }, new PanGuAnalyzer());
var query = parser.Parse(keyword);
var collector = TopScoreDocCollector.Create(pageIndex * pageSize, true);
searcher.Search(query, collector);
totalHits = collector.TotalHits;
var topDocs = collector.TopDocs((pageIndex - 1) * pageSize, pageSize);
return topDocs.ScoreDocs.Select(sd => {
var doc = searcher.Doc(sd.Doc);
return new SearchResult {
Id = doc.Get("id"),
Title = doc.Get("title"),
Url = doc.Get("url"),
Score = sd.Score
};
}).ToList();
}
}
IndexWriter.ForceMerge(1) 合併片段,提升讀取速度。掌握上述核心流程,即可在 ASP.NET 專案中快速建置穩定、高效能的站內搜尋服務。隨著資料量增長,還可進一步引入 Lucene.NET 的分散式擴充方案(如 Solr、Elasticsearch)以應對更高併發需求。