|
Lucene.net 实现全文搜索(7) //解析索引的text字段以便搜索 Query query = QueryParser.Parse(this.Q, "text", new StandardAnalyzer()); //将搜索结果放在hits中 Hits hits = searcher.Search(query); //统计搜索的总记录数 this.total = hits.Length(); //高亮显示 QueryHighlightExtractor highlighter = new QueryHighlightExtractor(query, new StandardAnalyzer(), "<font color=red>", "</font>"); 第一步利用IndexSearcher打开索引文件用于后面搜索,其中的参数是索引文件的路径.
第二步使用QueryParser将可读性较好的查询语句(比如查询的词lucene ,以及一些高级方式lucene AND .net)转化为Lucene内部使用的查询对象.
第三步执行搜索.并将结果返回到hits集合.需要注意的是Lucene并不是一次将所有的结果放入hits中而是采取一次放一部分的方式.出于空间考虑.
然后将搜索的结果进行处理并在页面上显示出来:
for (int i = startAt; i < resultsCount; i++) { Document doc = hits.Doc(i); string path = doc.Get("path");
string location =Server.MapPath("documents")+"\\"+path; string exname=Path.GetExtension (path); string plainText ; string str=doc.Get ("title"); if(exname==".html" exname ==".htm" exname ==".txt") { using (StreamReader sr = new StreamReader(location, System.Text.Encoding.Default)) { plainText = parseHtml(sr.ReadToEnd()); } } else { using (StreamReader sr = new StreamReader(location, System.Text.Encoding.Unicode )) { plainText = sr.ReadToEnd(); }
|