各位朋友,谢谢你们的支持,因为文件过大,有考虑到版权的问题,故没有提供下载,本人已创建一个搜索技术交流群:77570783,源代码已上传至群共享,须要的朋友,请自行下载!html
首先自问自答几个问题,以让各位看官了解写此文的目的web
什么是站内搜索?与通常搜索的区别?
不少网站都有搜索功能,不少都是用SQL语句的Like实现的,可是Like没法作到模糊匹配(例如我搜索“.net学习”,若是有“.net的学习”,Like就没法搜索到,这明显不符合需求,可是站内搜索就能作到),另外Like会形成全盘扫描,会对数据库形成很大压力,为何不用数据库全文检索,跟普通SQL同样,很傻瓜,灵活性不行数据库
为何不用百度、google的站内搜索?
毕竟是别人的东西,用起来确定会受制于人(哪天你的网站火了,它看你不爽了,就可能被K),主要仍是索引的不够及时,网站新的内容,须要必定时间才能被索引到,而且用户的体验也不太好函数
最近改造了《动力起航》的站内搜索的功能,它其实已经有站内搜索的功能,可是是用like来实现的,改造此功能是本着在尽量少的修改网站的源代码的状况下去改造此功能以及此站内搜索功能能够很好的移植到其余项目的原则来编写!本文有借鉴其余大神及园友的技术,在此谢谢!学习
站内搜索使用的技术
Log4Net 日志记录网站
lucene.Net 全文检索开发包,只能检索文本信息ui
分词(lucene.Net提供StandardAnalyzer一元分词,按照单个字进行分词,一个汉字一个词)google
盘古分词 基于词库的分词,能够维护词库spa
首先咱们新增的SearchHelper类须要将其作成一个单例,使用单例是由于:有许多地方须要使用使用,但咱们同时又但愿只有一个对象去操做,具体代码以下:.net
#region 建立单例 // 定义一个静态变量来保存类的实例 private static SearchHelper uniqueInstance; // 定义一个标识确保线程同步 private static readonly object locker = new object(); // 定义私有构造函数,使外界不能建立该类实例 private SearchHelper() { } /// <summary> /// 定义公有方法提供一个全局访问点,同时你也能够定义公有属性来提供全局访问点 /// </summary> /// <returns></returns> public static SearchHelper GetInstance() { // 当第一个线程运行到这里时,此时会对locker对象 "加锁", // 当第二个线程运行该方法时,首先检测到locker对象为"加锁"状态,该线程就会挂起等待第一个线程解锁 // lock语句运行完以后(即线程运行完以后)会对该对象"解锁" lock (locker) { // 若是类的实例不存在则建立,不然直接返回 if (uniqueInstance == null) { uniqueInstance = new SearchHelper(); } } return uniqueInstance; } #endregion
其次,使用Lucene.Net须要将被搜索的进行索引,而后保存到索引库以便被搜索,咱们引入了“生产者,消费者模式”. 生产者就是当咱们新增,修改或删除的时候咱们就须要将其在索引库进行相应的操做,咱们将此操做交给另外一个线程去处理,这个线程就是咱们的消费者,使用“生产者,消费者模式”是由于:索引库使用前需解锁操做,使用完成以后必须解锁,因此只能有一个对象对索引库进行操做,避免数据混乱,因此要使用生产者,消费者模式
首先咱们来看生产者,代码以下:
private Queue<IndexJob> jobs = new Queue<IndexJob>(); //任务队列,保存生产出来的任务和消费者使用,不使用list避免移除时数据混乱问题 /// <summary> /// 任务类,包括任务的Id ,操做的类型 /// </summary> class IndexJob { public int Id { get; set; } public JobType JobType { get; set; } } /// <summary> /// 枚举,操做类型是增长仍是删除 /// </summary> enum JobType { Add, Remove } #region 任务添加 public void AddArticle(int artId) { IndexJob job = new IndexJob(); job.Id = artId; job.JobType = JobType.Add; logger.Debug(artId + "加入任务列表"); jobs.Enqueue(job);//把任务加入商品库 } public void RemoveArticle(int artId) { IndexJob job = new IndexJob(); job.JobType = JobType.Remove; job.Id = artId; logger.Debug(artId + "加入删除任务列表"); jobs.Enqueue(job);//把任务加入商品库 } #endregion
下面是消费者,消费者咱们单独一个线程来进行任务的处理:
/// <summary> /// 索引任务线程 /// </summary> private void IndexOn() { logger.Debug("索引任务线程启动"); while (true) { if (jobs.Count <= 0) { Thread.Sleep(5 * 1000); continue; } //建立索引目录 if (!System.IO.Directory.Exists(IndexDic)) { System.IO.Directory.CreateDirectory(IndexDic); } FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NativeFSLockFactory()); bool isUpdate = IndexReader.IndexExists(directory); logger.Debug("索引库存在状态" + isUpdate); if (isUpdate) { //若是索引目录被锁定(好比索引过程当中程序异常退出),则首先解锁 if (IndexWriter.IsLocked(directory)) { logger.Debug("开始解锁索引库"); IndexWriter.Unlock(directory); logger.Debug("解锁索引库完成"); } } IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED); ProcessJobs(writer); writer.Close(); directory.Close();//不要忘了Close,不然索引结果搜不到 logger.Debug("所有索引完毕"); } } private void ProcessJobs(IndexWriter writer) { while (jobs.Count != 0) { IndexJob job = jobs.Dequeue(); writer.DeleteDocuments(new Term("number", job.Id.ToString())); //若是“添加文章”任务再添加, if (job.JobType == JobType.Add) { BLL.article bll = new BLL.article(); Model.article art = bll.GetArticleModel(job.Id); if (art == null)//有可能刚添加就被删除了 { continue; } string channel_id = art.channel_id.ToString(); string title = art.title; DateTime time = art.add_time; string content = Utils.DropHTML(art.content.ToString()); string Addtime = art.add_time.ToString("yyyy-MM-dd"); Document document = new Document(); //只有对须要全文检索的字段才ANALYZED document.Add(new Field("number", job.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("title", title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS)); document.Add(new Field("channel_id", channel_id, Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("Addtime", Addtime, Field.Store.YES, Field.Index.NOT_ANALYZED)); document.Add(new Field("content", content, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(document); logger.Debug("索引" + job.Id + "完毕"); } } } #endregion
以上咱们就把索引库创建完毕了,接下来就是进行搜索了,搜索操做里面包括对搜索关键词进行分词,其次是搜索内容搜索词高亮显示,下面就是搜索的代码:
#region 从索引搜索结果 /// <summary> /// 从索引搜索结果 /// </summary> public List<Model.article> SearchIndex(string Words, int PageSize, int PageIndex, out int _totalcount) { _totalcount = 0; Dictionary<string, string> dic = new Dictionary<string, string>(); BooleanQuery bQuery = new BooleanQuery(); string title = string.Empty; string content = string.Empty; title = GetKeyWordsSplitBySpace(Words); QueryParser parse = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "title", new PanGuAnalyzer()); Query query = parse.Parse(title); parse.SetDefaultOperator(QueryParser.Operator.AND); bQuery.Add(query, BooleanClause.Occur.SHOULD); dic.Add("title", Words); content = GetKeyWordsSplitBySpace(Words); QueryParser parseC = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "content", new PanGuAnalyzer()); Query queryC = parseC.Parse(content); parseC.SetDefaultOperator(QueryParser.Operator.AND); bQuery.Add(queryC, BooleanClause.Occur.SHOULD); dic.Add("content", Words); if (bQuery != null && bQuery.GetClauses().Length > 0) { return GetSearchResult(bQuery, dic, PageSize, PageIndex, out _totalcount); } return null; } /// <summary> /// 获取 /// </summary> /// <param name="bQuery"></param> private List<Model.article> GetSearchResult(BooleanQuery bQuery, Dictionary<string, string> dicKeywords, int PageSize, int PageIndex, out int totalCount) { List<Model.article> list = new List<Model.article>(); FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), new NoLockFactory()); IndexReader reader = IndexReader.Open(directory, true); IndexSearcher searcher = new IndexSearcher(reader); TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true); Sort sort = new Sort(new SortField("Addtime", SortField.DOC, true)); searcher.Search(bQuery, null, collector); totalCount = collector.GetTotalHits();//返回总条数 TopDocs docs = searcher.Search(bQuery, (Filter)null, PageSize * PageIndex, sort); if (docs != null && docs.totalHits > 0) { for (int i = 0; i < docs.totalHits; i++) { if (i >= (PageIndex - 1) * PageSize && i < PageIndex * PageSize) { Document doc = searcher.Doc(docs.scoreDocs[i].doc); Model.article model = new Model.article() { id = int.Parse(doc.Get("number").ToString()), title = doc.Get("title").ToString(), content = doc.Get("content").ToString(), add_time = DateTime.Parse(doc.Get("Addtime").ToString()), channel_id = int.Parse(doc.Get("channel_id").ToString()) }; list.Add(SetHighlighter(dicKeywords, model)); } } } return list; } /// <summary> /// 设置关键字高亮 /// </summary> /// <param name="dicKeywords">关键字列表</param> /// <param name="model">返回的数据模型</param> /// <returns></returns> private Model.article SetHighlighter(Dictionary<string, string> dicKeywords, Model.article model) { SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>"); Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new Segment()); highlighter.FragmentSize = 250; string strTitle = string.Empty; string strContent = string.Empty; dicKeywords.TryGetValue("title", out strTitle); dicKeywords.TryGetValue("content", out strContent); if (!string.IsNullOrEmpty(strTitle)) { string title = model.title; model.title = highlighter.GetBestFragment(strTitle, model.title); if (string.IsNullOrEmpty(model.title)) { model.title = title; } } if (!string.IsNullOrEmpty(strContent)) { string content = model.content; model.content = highlighter.GetBestFragment(strContent, model.content); if (string.IsNullOrEmpty(model.content)) { model.content = content; } } return model; } /// <summary> /// 处理关键字为索引格式 /// </summary> /// <param name="keywords"></param> /// <returns></returns> private string GetKeyWordsSplitBySpace(string keywords) { PanGuTokenizer ktTokenizer = new PanGuTokenizer(); StringBuilder result = new StringBuilder(); ICollection<WordInfo> words = ktTokenizer.SegmentToWordInfos(keywords); foreach (WordInfo word in words) { if (word == null) { continue; } result.AppendFormat("{0}^{1}.0 ", word.Word, (int)Math.Pow(3, word.Rank)); } return result.ToString().Trim(); } #endregion
以上咱们的站内搜索的SearchHelper类就创建好了,下面来说讲如何使用,此类提供如下几个方法对外使用:
在Global里面启动消费者线程:
protected void Application_Start(object sender, EventArgs e) { //启动索引库的扫描线程(生产者) SearchHelper.GetInstance().CustomerStart(); }
在需被搜索的新增或修改处添加下面方法:
SearchHelper.GetInstance().AddArticle(model.id);
在需被搜索的删除处添加下面方法:
SearchHelper.GetInstance().RemoveArticle(model.id);
搜索的时候使用下面的方法便可:
public List<Model.article> SearchIndex(string Words, int PageSize, int PageIndex, out int _totalcount)
以上就是整个站内搜索的所有代码,SearchHelper帮助类下载地址:http://files.cnblogs.com/beimeng/SearchHelper.rar
原本想直接提供改造了《动力起航》的源代码,这样就能够直接看到效果了,一方面因为文件过大,另外一方面不知道是否是会侵权,全部没有提供下载.若是有须要的朋友能够留下邮箱我将发给你,但仅供学习交流之用,误用作商业用途,以上若是有侵权等问题还请及时告知我,以便我及时更正!
很荣幸此文能上最多推荐,多谢你们的支持,因为索要改造了《动力起航》的源代码的园友不少,一一发给你们有点麻烦,在考虑是否放到网盘提供你们下载是否是更方便一些,可是不知道这样会不会有侵权之嫌啊,求各位给个建议,若是能够我就上传网盘了,不行的话就只能一个一个发给你们了!
最好若是以为好的话!请给个推荐啊~~~~亲!!!!