DotLucene搜索索引(上)
主要就两个方法,一个search()方法,主要是显示当前页的搜索记录
1protected void search()
2 {
3 DateTime start = DateTime.Now;//搜索的开始时间
4 //得到索引所在的目录,我们在上个console程序里把索引放到了index目录下
5 string indexDirectory = Server.MapPath("index");
6 //创建个索引搜索器
7 IndexSearcher searcher = new IndexSearcher(indexDirectory);
8 //分词并解析索引的text字段以便搜索
9 Query thisQuery = QueryParser.Parse(this.Query,"text",new StandardAnalyzer());
10 //为要绑定输出到页面的results建立几列
11 this.Results.Columns.Add("path",typeof(string));
12 this.Results.Columns.Add("sample",typeof(string));
13 this.Results.Columns.Add("title",typeof(string));
14 //开始搜索
15 Hits hits = searcher.Search(thisQuery);
16 //得到搜索返回的记录总数
17 this.total = hits.Length();
18 //创建一个高亮
19 QueryHighlightExtractor highlighter = new QueryHighlightExtractor(thisQuery, new StandardAnalyzer(), "<B>", "</B>");
20 //初始化startAt,以便得到要显示的结果集
21 this.startAt = initStartAt();
22 //得到当前页要显示的记录数量,包括以前所有页的记录数,这样把他与this.startAt结合就能够很好的知道当前页要显示的记录数了
23 int resultsCount = smallOf(this.total,this.startAt+this.maxResults);
24 //开始循环得到当前页要显示的记录
25 for (int i = this.startAt; i < resultsCount; i++)
26 {
27 //得到每一行Hits的Document,因为Hits的没一行都是个Document对象
28 Document doc = hits.Doc(i);
29 //得到doc里面的列path的值
30 string path = doc.Get("path");
31 //再得到这个路径在web程序的路径,我们原来把文档放到了web根目录的documents目录下的
32 string location = Server.MapPath(@"documents\"+path);
33 //用StreamReader读取文档,因为我们不能够直接从索引中得到text字段的值,因为我们建立索引的时候没有存储他的
34 string plainText;
35 using (StreamReader sr = new StreamReader(location, System.Text.Encoding.Default))
36 {
37 plainText = ParseHtml(sr.ReadToEnd());
38 }
39 //为结果集DataTable,Results添加个新行
40 DataRow dr = this.Results.NewRow();
41 dr["title"] = doc.Get("title");
42 dr["path"] = @"documents/" + path;
43 dr["sample"] = highlighter.GetBestFragment(plainText,80);
44 //把行添加进DataTable
45 this.Results.Rows.Add(dr);
46 }
47 //循环完毕,关闭搜索
48 searcher.Close();
49 //搜索花费多少时间
50 this.duration = DateTime.Now - start;
51 //给fromItem赋值,他总是startAt+1
52 this.fromItem = this.startAt + 1;
53 //给toItem赋值
54 this.toItem = smallOf(this.total,this.startAt+this.maxResults);
55
56 }
本文来自博客园,作者:古道轻风,转载请注明原文链接:https://www.cnblogs.com/88223100/archive/2008/08/18/1270624.html
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 一个奇形怪状的面试题:Bean中的CHM要不要加volatile?
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析