sulin LuceneNet 搜索二
阅读原文时间:2023年07月11日阅读:1

1.添加引用dll

using Lucene.Net.Search;
using Lucene.Net.Analysis.PanGu;
using PanGu;
using PanGu.HighLight;
using Lucene.Net.Documents;
using Lucene.Net.Store;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;

2.查询代码

///

/// 从索引搜索结果 ///
private void SearchIndex()
{
Dictionary dic = new Dictionary();
BooleanQuery bQuery = new BooleanQuery();
CachingWrapperFilter filter = null;
TermQuery query2 = null;
string title = string.Empty;
string content = string.Empty;
if ((Request["title"] != null && Request["title"].ToString() != "") || !string.IsNullOrEmpty(txtTitle))
{
string searchkey = Request["title"]==null?"":Request["title"].ToString();
if(!string.IsNullOrEmpty(txtTitle)){
searchkey=txtTitle;
}
foreach (string word in GetKeyWordsSplitBySpace(searchkey))
{
query2 = new TermQuery(new Term("Title", word));
bQuery.Add(query2, BooleanClause.Occur.SHOULD);//这里设置 条件为Or关系
query2 = new TermQuery(new Term("SimpleDesc", word));
bQuery.Add(query2, BooleanClause.Occur.SHOULD);//这里设置 条件为Or关系
query2 = new TermQuery(new Term("Tags", word));
bQuery.Add(query2, BooleanClause.Occur.SHOULD);//这里设置 条件为Or关系
//query2 = new TermQuery(new Term("ContextDesc", word));
//bQuery.Add(query2, BooleanClause.Occur.SHOULD);//这里设置 条件为Or关系
}
dic.Add("Title", searchkey);
dic.Add("SimpleDesc", searchkey);
txtTitle = searchkey;

             if(this.hfradchecked.Value!="全部"){  
                 //TermQuery query1 = new TermQuery(new Term("Types", this.hfradchecked.Value));  
                 txttype = this.hfradchecked.Value;  
                 query2 = new TermQuery(new Term("Types", this.hfradchecked.Value.ToString()));  
                 QueryWrapperFilter oldFilter = new QueryWrapperFilter(query2);  
                 filter = new CachingWrapperFilter(oldFilter);

             }  
             if (bQuery != null && bQuery.GetClauses().Length > )  
             {  
                 GetSearchResult(bQuery, dic, filter);  
             }  
         }

     }  
     /// <summary>  
     /// 获取  
     /// </summary>  
     /// <param name="bQuery"></param>  
     private void GetSearchResult(BooleanQuery bQuery, Dictionary<string, string> dicKeywords, CachingWrapperFilter filter)  
     {  
         try  
         {  
             //IndexSearcher search = new IndexSearcher(IndexDic, true);  
             FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NoLockFactory());  
             IndexReader reader = IndexReader.Open(directory, true);  
             //IndexSearcher是进行搜索的类  
             IndexSearcher search = new IndexSearcher(reader);  
             Stopwatch stopwatch = Stopwatch.StartNew();  
             //SortField构造函数第三个字段true为降序,false为升序  
             Sort sort = new Sort(new SortField("UploadTime", SortField.DOC, true));  
             TopDocs docs = search.Search(bQuery, filter, PageSize \* PageIndex, sort);  
             stopwatch.Stop();  
             if (docs != null && docs.totalHits > )  
             {  
                 lSearchTime = stopwatch.ElapsedMilliseconds;  
                 txtPageFoot = GetPageFoot(PageIndex, PageSize, docs.totalHits, "sabrosus");  
                 for (int i = ; i < docs.totalHits; i++)  
                 {  
                     if (i >= (PageIndex - ) \* PageSize && i < PageIndex \* PageSize)  
                     {  
                         Document doc = search.Doc(docs.scoreDocs\[i\].doc);  
                         ResourcesModel model = new ResourcesModel()  
                         {  
                             ID = doc.Get("ID").ToString(),  
                             Title = doc.Get("Title").ToString(),  
                             Tags = doc.Get("Tags").ToString(),  
                             CreaetBy = doc.Get("CreaetBy").ToString(),  
                             UploadTime = doc.Get("UploadTime").ToString(),  
                             Types = doc.Get("Types").ToString(),  
                             SimpleDesc = doc.Get("SimpleDesc").ToString(),  
                             ContextDesc = doc.Get("ContextDesc").ToString()  
                         };  
                         list.Add(SetHighlighter(dicKeywords, model));  
                     }  
                 }  
             }  
         }  
         catch (Exception ex)  
         {  
             LogHelper.SaveLogError("",ex.ToString());

         }

     }

     /// <summary>  
     /// 处理关键字为索引格式  
     /// </summary>  
     /// <param name="keywords"></param>  
     /// <returns></returns>  
     private string\[\] GetKeyWordsSplitBySpace(string keywords)  
     {  
         PanGuTokenizer ktTokenizer = new PanGuTokenizer();  
         StringBuilder result = new StringBuilder();  
         List<string> listarry = new List<string>();  
         ICollection<WordInfo> words = ktTokenizer.SegmentToWordInfos(keywords);

         foreach (WordInfo word in words)  
         {  
             if (word == null)  
             {  
                 continue;  
             }  
             listarry.Add(word.Word);  
         }  
         return listarry.ToArray();  
     }

     /// <summary>  
     /// 设置关键字高亮  
     /// </summary>  
     /// <param name="dicKeywords">关键字列表</param>  
     /// <param name="model">返回的数据模型</param>  
     /// <returns></returns>  
     private ResourcesModel SetHighlighter(Dictionary<string, string> dicKeywords, ResourcesModel model)  
     {  
         SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color=\\"red\\">", "</font>");  
         Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new Segment());  
         highlighter.FragmentSize = ;  
         string strTitle = string.Empty;  
         string strContent = string.Empty;  
         string Title = model.Title;  
         string SimpleDesc = model.SimpleDesc;  
         dicKeywords.TryGetValue("Title", out strTitle);  
         dicKeywords.TryGetValue("SimpleDesc", out strContent);

         if (!string.IsNullOrEmpty(strTitle))  
         {  
             model.Title = highlighter.GetBestFragment(strTitle, model.Title);  
             if (model.Title == "" || model.Title==null)  
             {  
                 model.Title = Title;  
             }  
         }

         if (!string.IsNullOrEmpty(strContent))  
         {  
             model.SimpleDesc = highlighter.GetBestFragment(strContent, model.SimpleDesc);  
             if (model.SimpleDesc == "" || model.SimpleDesc == null)  
             {  
                 model.SimpleDesc = SimpleDesc;  
             }  
             model.SimpleDesc = GetContextSubstring(model.SimpleDesc, );  
         }  
         return model;  
     }