基本信息
源码名称:Lucene+jieba.net实现全文检索
源码大小:60.04M
文件格式:.rar
开发语言:C#
更新时间:2019-10-30
   友情提示:(无需注册或充值,赞助后即可获取资源下载链接)

     嘿,亲!知识可是无价之宝呢,但咱这精心整理的资料也耗费了不少心血呀。小小地破费一下,绝对物超所值哦!如有下载和支付问题,请联系我们QQ(微信同号):78630559

本次赞助数额为: 2 元 
   源码介绍

lucene jieba.net,将数据库换成自己的数据库即可




#region 创建索引
        protected void btnCreateIndex_Click(object sender, EventArgs e)
        {
            string indexPath = Context.Server.MapPath("~/Indexs");
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
            bool isUpdate = IndexReader.IndexExists(directory);
            if (isUpdate)
            {
                // 如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁                 // Lucene.Net在写索引库之前会自动加锁,在close的时候会自动解锁                 // 不能多线程执行,只能处理意外被永远锁定的情况                 if (IndexWriter.IsLocked(directory))
                {
                    IndexWriter.Unlock(directory);
                }
            }
            // 创建向索引库写操作对象  IndexWriter(索引目录,指定使用盘古分词进行切词,最大写入长度限制)             // 补充:使用IndexWriter打开directory时会自动对索引库文件上锁             IndexWriter writer = new IndexWriter(directory, new jieba.Common.JiebaAnalyzer(), !isUpdate, IndexWriter.MaxFieldLength.UNLIMITED);
 
            // 读取所有文件,读取的文件为数据库中数据生成的文件             string[] filelist = System.IO.Directory.GetFiles(Server.MapPath("~/Upload/"));
            // 防止重复索引,如果不存在删除0条             writer.DeleteAll();
            foreach (string item in filelist)
            {
                if (!File.Exists(item))
                {
                    continue;
                }
                StreamReader sr = new StreamReader(item);
                string content = sr.ReadToEnd();
                string[] strlist = System.Text.RegularExpressions.Regex.Split(content, "<换行>", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
 
                // 创建索引                 string txt = File.ReadAllText(item);
                // 一条Document相当于一条记录                 Document document = new Document();
                // 每个Document可以有自己的属性(字段),所有字段名都是自定义的,值都是string类型                 // Field.Store.YES不仅要对文章进行分词记录,也要保存原文,就不用去数据库里查一次了                 document.Add(new Field("id", strlist[0], Field.Store.YES, Field.Index.NOT_ANALYZED));
                // 需要进行全文检索的字段加 Field.Index. ANALYZED                 // Field.Index.ANALYZED:指定文章内容按照分词后结果保存,否则无法实现后续的模糊查询                  // WITH_POSITIONS_OFFSETS:指示不仅保存分割后的词,还保存词之间的距离                 document.Add(new Field("title", strlist[1], Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                document.Add(new Field("content", strlist[2], Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
                // 把文档写入索引库                 writer.AddDocument(document);
            }
 
            writer.Close();
            directory.Close();
        }
        #endregion
#region 加载内容
        protected void LoadContent(string keyword)
        {
            string content = "";
            string indexPath = Context.Server.MapPath("~/Indexs");
            FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
            IndexReader reader = IndexReader.Open(directory, true);
            List<searchResult> list = new List<searchResult>();
            PhraseQuery query = new PhraseQuery();
 
            jieba.Common.JiebaAnalyzer analyzer = new jieba.Common.JiebaAnalyzer();
            BooleanQuery bq = new BooleanQuery();
            Lucene.Net.Util.Version version = Lucene.Net.Util.Version.LUCENE_30;
            string _flag = "3";
            if (_flag != "")
            {
                QueryParser queryParser = new QueryParser(version, "flag", analyzer);
                Query qflag = queryParser.Parse(_flag);
                bq.Add(qflag, Occur.SHOULD);
            }
            Query queryKeyword = null;
            if (keyword != "")
            {
                string[] arr = CutWords(keyword);
                string[] fields = new string[arr.Length];
                for (int i = 0; i < fields.Length; i  )
                {
                    fields[i] = "title";
                }
                queryKeyword = MultiFieldQueryParser.Parse(version, arr, fields, analyzer);
                bq.Add(queryKeyword, Occur.SHOULD);
            }
 
 
 
 
            TopScoreDocCollector collector = TopScoreDocCollector.Create(100false);
            IndexSearcher searcher = new IndexSearcher(reader);
            searcher.Search(bq, collector);
 
            if (collector == null || collector.TotalHits == 0)
            {
                list = null;
            }
            else             {
                ScoreDoc[] hits = collector.TopDocs().ScoreDocs;
                int counter = 1;
                foreach (ScoreDoc item in hits)
                {
                    try                     {
                        Document doc = searcher.Doc(item.Doc);
                        searchResult s = new searchResult()
                        {
                            id = Convert.ToInt32(doc.Get("id")),
                            title = doc.Get("title"),
                            //content = HighlightHelper.HighLight(keyword, doc.Get("content"))                             content = doc.Get("content")
                        };
                        list.Add(s);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }
                rptSearchResult.DataSource = list;
                rptSearchResult.DataBind();
                
            }
        }
        #endregion
#region 获取列表
        public List<PageInfo> GetList()
        {
            List<PageInfo> list = new List<PageInfo>();
            string sql = "select * from PageInfo";
            SqlConnection conn = new SqlConnection(constr);
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);
            SqlDataReader sdr = cmd.ExecuteReader();
            if (sdr.HasRows)
            {
                while (sdr.Read())
                {
                    PageInfo p = new PageInfo()
                    {
                        id = Convert.ToInt32(sdr["id"]),
                        altertime = Convert.ToDateTime(sdr["altertime"]),
                        pageconintroduce = sdr["pageconintroduce"].ToString(),
                        pagecontent = sdr["pagecontent"].ToString(),
                        pageid = Convert.ToInt32(sdr["pageid"]),
                        pageimg = sdr["pageimg"].ToString(),
                        pagetitle = sdr["pagetitle"].ToString()
                    };
                    list.Add(p);
                }
                conn.Close();
            }
            return list;
        }
        #endregion