public static IEnumerable <VM.SearchModel> Search(string keyWord) { try { List <VM.SearchModel> result = new List <VM.SearchModel>(); Dictionary <string, string> dic = new Dictionary <string, string>(); /*加入时间统计*/ Stopwatch sw = new Stopwatch(); sw.Start(); /*创建 Lucene.net 搜索实例*/ string IndexDic = GetMapPath("~/SearchData/IndexData"); string PanGuXmlPath = GetMapPath("~/SearchData/PanGu/PanGu.xml"); PanGu.Segment.Init(PanGuXmlPath); FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NoLockFactory()); IndexReader reader = IndexReader.Open(directory, true); IndexSearcher searcher = new IndexSearcher(reader); /*为搜索实例 加入搜索分词规则 来源 盘古分词*/ keyWord = GetKeyWordsSplitBySpace(keyWord, new PanGuTokenizer()); PhraseQuery query = new PhraseQuery(); if (!string.IsNullOrEmpty(keyWord)) { dic.Add("Content", keyWord); foreach (string word in keyWord.Split('/')) { if (word == "") { continue; } query.Add(new Term("Content", word)); } } query.Slop = 100; TopScoreDocCollector collector = TopScoreDocCollector.Create(1024, true); //最大1024条记录 searcher.Search(query, null, collector); int totalCount = collector.TotalHits; //返回总条数 ScoreDoc[] docs = collector.TopDocs(0, 10).ScoreDocs; //分页,下标应该从0开始吧,0是第一条记录 ///*指定排序方式 按 PostScore 字段来排序*/ //List<SortField> sorts = new List<SortField>(); //SortField sf = new SortField("ID", SortField.INT, true); //sorts.Add(sf); //Sort sort = new Sort(sorts.ToArray()); //TopFieldDocs docs = searcher.Search(bq, null, searcher.MaxDoc, sort); //int allCount = docs.TotalHits; ///*获取匹配的前10条*/ //ScoreDoc[] hits = TopDocs(0, 10, docs); foreach (ScoreDoc sd in docs)//遍历搜索到的结果 { try { Document doc = searcher.Doc(sd.Doc); var model = new VM.SearchModel(); model.ID = int.Parse(doc.Get("ID")); model.Title = doc.Get("Title"); model.Contents = doc.Get("Content"); //SetHighlighter(null, model); result.Add(SetHighlighter(dic, model)); } catch { } } searcher.Close(); searcher.Dispose(); sw.Stop(); return(result); } catch (Exception) { return(null); } }
private static VM.SearchModel SetHighlighter(Dictionary <string, string> dicKeywords, VM.SearchModel model) { PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>"); PanGu.HighLight.Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new Segment()); highlighter.FragmentSize = 100; string strContent = string.Empty; dicKeywords.TryGetValue("Content", out strContent); if (!string.IsNullOrEmpty(strContent)) { model.Contents = highlighter.GetBestFragment(strContent, model.Contents) + "..."; //model.Content = string.Join("...", (highlighter.GetFragments(strContent, model.Content,3).ToList())); } return(model); }