经过上篇我们已对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);
}
}
}