經過上篇我們已經對59部小說文本建立了索引,詳情可見http://www.cnblogs.com/abob/archive/2006/08/26/487140.Html
1: 搜索關鍵字 using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Analysis.Cn;
namespace SearchTest
{
class SearchTest
{
private IndexSearcher searcher = null;
private Analyzer analyser = null;
public SearchTest()
{
analyser = new ChineseAnalyzer();
searcher = new IndexSearcher(IndexReader.Open("c:\\index"));
}
public Hits search(String queryString, string fIEld)
{
if (searcher != null)
{
try
{
QueryParser parser = new QueryParser(fIEld,analyser);
parser.SetOperator(QueryParser.DEFAULT_OperaTOR_AND);
Query query = parser.Parse(queryString);
return searcher.Search(query);
}
catch { }
}
return null;
}
static void Main(string[] args)
{
SearchTest searcher = new SearchTest();
DateTime start = DateTime.Now;
Hits h = searcher.search("中國", "content");
DateTime end = DateTime.Now;
long time = end.Ticks - start.Ticks;
Console.WriteLine("總共耗時:{0}毫秒",Convert.ToString(time));
Console.WriteLine("總共找到{0}個文件",h.Length());
}
}
}
由於搜索是一種注重效率的行為,因此將其構建成一個輕量級的對象能節省不少內存和時間上的開銷.在上面的代碼中,內置了一個IndexSearcher對象,並調用其search方法來檢索.
在代碼最後的main函數中,輸入了關鍵字"中國",搜索的結果是
總共耗時:1406250毫秒
總共找到22個文件
請按任意鍵繼續. . .
2:下面為了性能上的提高,我們來用多線程進行搜索
using System;
using System.Collections.Generic;
using System.Text;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using System.Threading;
namespace MuiltiSearch
{
class MultiSearch
{
static void Main(string[] args)
{
for (int i = 0; i < 50; i++)
{
SearchThread s = new SearchThread();
Thread thread=new Thread(s.run);
thread.Start();
}
}
}
public class SearchThread
{
public void run()
{
Thread.Sleep(10);
IndexSearcher searcher = new IndexSearcher(IndexReader.Open("c:\\index"));
QueryParser parser = new QueryParser("content", new ChineseAnalyzer());
parser.SetOperator(QueryParser.DEFAULT_OperaTOR_AND);
Query query = parser.Parse("中國");
DateTime start = DateTime.Now;
Hits h = searcher.Search(query);
DateTime end = DateTime.Now;
long time = start.Ticks - end.Ticks;
Console.WriteLine("用時{0}毫秒", time);
}
}
}
http://www.cnblogs.com/abob/archive/2006/08/27/487558.Html