程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> 基於ASP.NET的lucene.net全文搜索實現步驟

基於ASP.NET的lucene.net全文搜索實現步驟

編輯:ASP.NET基礎

在做項目的時候,需求添加全文搜索,選擇了lucene.net方向,調研了一下,基本實現了需求,現在將它分享給大家。理解不深請多多包涵。

在完成需求的時候,查看的大量的資料,本文不介紹詳細的lucene.net工程建立,只介紹如何對文檔進行全文搜索。對於如何建立lucene.net的工程請大家訪問

使用lucene.net搜索分為兩個部分,首先是創建索引,創建文本內容的索引,其次是根據創建的索引進行搜索。那麼如何對文檔進行索引呢,主要是對文檔的內容進行索引,關鍵是提取出文檔的內容,按照常規實現,由簡到難,提取txt格式的文本相對比較簡單,如果實現了提取txt文本,接下來就容易多了,萬丈高樓平地起,這就是地基。

1.首先創建ASP.NET頁面。

這是一個極其簡單的頁面,創建頁面之後,雙擊各個按鈕生成相應的點擊事件,在相應的點擊事件中實現程序設計。

2.實現索引部分。

前面已經說到了,索引主要是根據文本內容建立索引,所以要提取文本內容。創建提取txt格式文檔文本內容的函數。
復制代碼 代碼如下: 
//提取txt文件
public static string FileReaderAll(FileInfo fileName)
{
//讀取文本內容,並且默認編碼格式,防止出現亂碼
StreamReader reader = new StreamReader(fileName.FullName, System.Text.Encoding.Default);
string line = "";
string temp = "";
//循環讀取文本內容
while ((line = reader.ReadLine()) != null)
{
temp += line;
}
reader.Close();
//返回字符串,用於lucene.net生成索引
return temp;
}

文本內容已經提取出來了,接下來要根據提取的內容建立索引
復制代碼 代碼如下: 
protected void Button2_Click(object sender, EventArgs e)
{
//判斷存放文本的文件夾是否存在
if (!System.IO.Directory.Exists(filesDirectory))
{
Response.Write("<script>alert('指定的目錄不存在');</script>");
return;
}
//讀取文件夾內容
DirectoryInfo dirInfo = new DirectoryInfo(filesDirectory);
FileInfo[] files = dirInfo.GetFiles("*.*");
//文件夾判空
if (files.Count() == 0)
{
Response.Write("<script>alert('Files目錄下沒有文件');</script>");
return;
}
//判斷存放索引的文件夾是否存在,不存在創建
if (!System.IO.Directory.Exists(indexDirectory))
{
System.IO.Directory.CreateDirectory(indexDirectory);
}
//創建索引
IndexWriter writer = new IndexWriter(FSDirectory.Open(new DirectoryInfo(indexDirectory)),
analyzer, true, IndexWriter.MaxFieldLength.LIMITED);

for (int i = 0; i < files.Count(); i++)
{
string str = "";
FileInfo fileInfo = files[i];
//判斷文件格式,為以後其他文件格式做准備
if (fileInfo.FullName.EndsWith(".txt") || fileInfo.FullName.EndsWith(".xml"))
{
//獲取文本
str = FileReaderAll(fileInfo);
}
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
doc.Add(new Lucene.Net.Documents.Field("FileName", fileInfo.Name, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
//根據文本生成索引
doc.Add(new Lucene.Net.Documents.Field("Content", str, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
doc.Add(new Lucene.Net.Documents.Field("Path", fileInfo.FullName, Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NO));
//添加生成的索引
writer.AddDocument(doc);
writer.Optimize();
}
writer.Dispose();
Response.Write("<script>alert('索引創建成功');</script>");
}

3.索引創建完了,接下來就是搜索,搜索只要按照固定的格式書寫不會出現錯誤。
復制代碼 代碼如下: 
protected void Button1_Click(object sender, EventArgs e)
{
//獲取關鍵字
string keyword = TextBox1.Text.Trim();
int num = 10;
//關鍵字判空
if (string.IsNullOrEmpty(keyword))
{
Response.Write("<script>alert('請輸入要查找的關鍵字');</script>");
return;
}

IndexReader reader = null;
IndexSearcher searcher = null;
try
{
reader = IndexReader.Open(FSDirectory.Open(new DirectoryInfo(indexDirectory)), true);
searcher = new IndexSearcher(reader);
//創建查詢
PerFieldAnalyzerWrapper wrapper = new PerFieldAnalyzerWrapper(analyzer);
wrapper.AddAnalyzer("FileName", analyzer);
wrapper.AddAnalyzer("Path", analyzer);
wrapper.AddAnalyzer("Content", analyzer);
string[] fields = { "FileName", "Path", "Content" };

QueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, fields, wrapper);
//根據關鍵字查詢
Query query = parser.Parse(keyword);

TopScoreDocCollector collector = TopScoreDocCollector.Create(num, true);

searcher.Search(query, collector);
//這裡會根據權重排名查詢順序
var hits = collector.TopDocs().ScoreDocs;

int numTotalHits = collector.TotalHits;

//以後就可以對獲取到的collector數據進行操作
for (int i = 0; i < hits.Count(); i++)
{
var hit = hits[i];
Lucene.Net.Documents.Document doc = searcher.Doc(hit.Doc);
Lucene.Net.Documents.Field fileNameField = doc.GetField("FileName");
Lucene.Net.Documents.Field pathField = doc.GetField("Path");
Lucene.Net.Documents.Field contentField = doc.GetField("Content");
//在頁面循環輸出表格
strTable.Append("<tr>");
strTable.Append("<td>" + fileNameField.StringValue + "</td>");
strTable.Append("</tr>");
strTable.Append("<tr>");
strTable.Append("<td>" + pathField.StringValue + "</td>");
strTable.Append("</tr>");
strTable.Append("<tr>");
strTable.Append("<td>" + contentField.StringValue.Substring(0, 300) + "</td>");
strTable.Append("</tr>");
}
}
finally
{
if (searcher != null)
searcher.Dispose();

if (reader != null)
reader.Dispose();
}
}

現在整個lucene.net搜索全文的過程就建立完了,現在可以搜索txt格式的文件,搜索其他格式的文件在以後添加,主要核心思想就是提取各個不同格式文件的文本內容。

顯示效果如下:

在以後的博文裡繼續接受搜索其他格式的文檔。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved