利用Lucene.Net進行文檔遞歸查詢

如何在項目中分析建立索引

1.添加引用lucene.net dll和名字空間

using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using ClassLibrary1.Icons;
using ClassLibrary1.Parsing;

2.在page load事件中聲明保存索引文件的路徑.程序會在頁面生存週期內記住文件的路徑.然後調用IndexBuilt和Search函數來實現查詢.

this.pathIndex = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "test");
IndexBuilt();
search();

3.以下是IndexBuilt函數的內容.他將遞歸的添加文件夾.然後索引目錄信息

private void IndexBuilt()
{
// 以下的代碼在磁盤上創建一個新的索引.
indexWriter = new IndexWriter(this.pathIndex, new StandardAnalyzer(), true);
bytesTotal = 0;
countTotal = 0;
countSkipped = 0;

DirectoryInfo di = new DirectoryInfo(@"C:/Inetpub/wwwroot/test/Resumes");
DateTime start = DateTime.Now;
addFolder(di);

string summary = String.Format("Done. Indexed {0} files ({1} bytes). Skipped {2} files.", countTotal, bytesTotal, countSkipped);
summary += String.Format(" Took {0}", (DateTime.Now - start));

indexWriter.Optimize();
indexWriter.Close();
}

4.search函數

private void search()
{
DateTime start = DateTime.Now;

try
{
searcher = new IndexSearcher(this.pathIndex);
}
catch (IOException ex)
{
MessageBox.Show("The index doesn't exist or is damaged. Please rebuild the index./r/n/r/nDetails:/r/n" + ex.Message);
return;
}
Query query = QueryParser.Parse("test", "text", new StandardAnalyzer());

Hits hits = searcher.Search(query);
for (int i = 0; i < hits.Length(); i++)
{
// 從索引獲取文檔
Document doc = hits.Doc(i);

// 在結果集裏創建新的行
string filename = doc.Get("title");
string path = doc.Get("path");
string folder = Path.GetDirectoryName(path);
DirectoryInfo di = new DirectoryInfo(folder);
str += filename + ","

}
searcher.Close();
Response.Write(str);
string searchReport = String.Format("Search took {0}. Found {1} items.", (DateTime.Now - start), hits.Length());
}

http://www.dotlucene.net/
 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章