Exemple #1
0
        public ActionResult Search(string txtSearch, int id = 1)
        {
            int           pageNum       = 1;
            int           currentPageNo = id;
            IndexSearcher search        = new IndexSearcher(directory, true);
            BooleanQuery  bQuery        = new BooleanQuery();

            //总的结果条数
            List <Article> list     = new List <Article>();
            int            recCount = 0;

            //处理搜索关键词
            txtSearch = LuceneHelper.GetKeyWordsSplitBySpace(txtSearch);

            //多个字段查询 标题和内容title, content
            MultiFieldQueryParser parser = new MultiFieldQueryParser(Lucene.Net.Util.Version.LUCENE_30, new string[] { "title", "Content" }, new PanGuAnalyzer());
            Query query = parser.Parse(txtSearch);

            //Occur.Should 表示 Or , Occur.MUST 表示 and
            bQuery.Add(query, Occur.MUST);

            if (bQuery != null && bQuery.GetClauses().Length > 0)
            {
                //盛放查询结果的容器
                TopScoreDocCollector collector = TopScoreDocCollector.Create(1000, true);
                //使用query这个查询条件进行搜索,搜索结果放入collector
                search.Search(bQuery, null, collector);
                recCount = collector.TotalHits;
                //从查询结果中取出第m条到第n条的数据
                ScoreDoc[] docs = collector.TopDocs((currentPageNo - 1) * pageNum, pageNum).ScoreDocs;
                //遍历查询结果
                for (int i = 0; i < docs.Length; i++)
                {
                    //只有 Field.Store.YES的字段才能用Get查出来
                    Document doc = search.Doc(docs[i].Doc);
                    list.Add(new Article()
                    {
                        Id      = doc.Get("id"),
                        Title   = LuceneHelper.CreateHightLight(txtSearch, doc.Get("title")),  //高亮显示
                        Content = LuceneHelper.CreateHightLight(txtSearch, doc.Get("Content")) //高亮显示
                    });
                }
            }
            //分页
            PagedList <Article> plist = new PagedList <Article>(list, currentPageNo, pageNum, recCount);

            plist.TotalItemCount   = recCount;
            plist.CurrentPageIndex = currentPageNo;
            return(View("Index", plist));
        }