[C#] 透過Lucene.net 進行關鍵字搜尋 - 關於 Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int) instead

2012-10-05

 

前幾天提到如何透過 Lucene.net 進行建立索引,還有進行關鍵字搜尋

建立索引: 如何從大量 JSON 檔案中找尋關鍵字 (Lucene.net 篇 - 建立索引)

搜尋: 如何從大量 JSON 檔案中找尋關鍵字 (Lucene.net 篇 - 關鍵字搜尋)

 

雖然搜尋結果很快,但是地表上最強 IDE Visual Stuio 2012 一直在那邊一一歪歪..

Warning    1    'Lucene.Net.Search.Searcher.Search(Lucene.Net.Search.Query)' is obsolete: 'Hits will be removed in Lucene 3.0. Use Search(Query, Filter, int) instead'    c:\users\dracula\documents\visual studio 2012\Projects\Lucene_Keyword_Search\Lucene_Keyword_Search\Sample1.aspx.cs    74    24    Lucene_Keyword_Search

 

2012-08-04_230637_2

 

因為新版的做法,這樣寫法在未來 3.0 將不支援..

所以進行小修正…

C# Code:

// 啟用監看
Stopwatch sw = new Stopwatch();
sw.Start();
 
// 讀取索引
string indexPath = AppDomain.CurrentDomain.BaseDirectory.ToString() + "\\Index1\\";
DirectoryInfo dirInfo = new DirectoryInfo(indexPath);
FSDirectory dir = FSDirectory.Open(dirInfo);
IndexSearcher search = new IndexSearcher(dir, true);
// 針對 Memo 欄位進行搜尋
QueryParser parser = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "Memo", new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
// 搜尋的關鍵字
Query query = parser.Parse(txtKeyword.Text);
// 開始搜尋
var hits = search.Search(query, null, search.MaxDoc()).ScoreDocs;
          
sw.Stop();
Response.Write("花費時間:" + sw.Elapsed + "<br /><hr />");
Response.Write("資料比數:" + hits.Length + "<br /><hr />");
Response.Write("Result:<br />");
 
foreach (var res in hits) 
{
    // 支援 Lucene.net 3.0 的做法
    Response.Write("Id:" + search.Doc(res.doc).Get("Id") + "  Memo=" + search.Doc(res.doc).Get("Memo").ToString().Replace(txtKeyword.Text, "<span style='color:red'>" + txtKeyword.Text + "</span>") + "<br />");
}
 
// 以前的寫法
// for (int i = 0; i < hits.Length; i++)
// {
//    Response.Write("Id:" + search.Doc(i).Get("Id").ToString() + "  Memo=" + search.Doc(i).Get("Memo").ToString().Replace(txtKeyword.Text, "<span style='color:red'>" + txtKeyword.Text + "</span>") + "<br />");
// }

 


修正一段寫法 讓之後 3.0 版 可以支援,因為網路上面寫到 Lucene.net  文件有些是舊的


讓有撞牆的人,也可以找到解答…


當麻許的超技八 2014 | Donma Hsu Design.