为了方便的学习站内搜索,下面我来演示一个MVC项目。

1.首先在项目中【添加引入】三个程序集和【Dict】文件夹,并新建一个【分词内容存放目录】

Lucene.Net.dll、PanGu.dll、PanGu.Lucene.Analyzer.dll

链接:http://pan.baidu.com/s/1eS6W8s6 密码:ds8b

链接:链接:http://pan.baidu.com/s/1geYyDnt 密码:8rq4

2.建立Search控制器,并转到Index界面写入如下内容:

PS:VS有问题,波浪号由他去吧,,,

----------后台语句-------

->创建索引语句

      public ActionResult SearchContent(){//首先根据name区分是点击的哪个按钮if (!String.IsNullOrEmpty(Request.Form["btnSearch"]))//执行搜索{}else//创建索引{CreateSearchIndex();//调用创建索引语句}return Content("OK");}//创建索引语句public void CreateSearchIndex(){string indexPath = @"H:\lucenedir";//注意和磁盘上文件夹的大小写一致,否则会报错。将创建的分词内容放在该目录下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);//un-否定。强制解锁}}IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);//-------调用业务层拿到所有的数据Search.BLL.UserGUIDBll bll = new Search.BLL.UserGUIDBll();List<Search.Model.UserInfo> list=bll.SelectAll();foreach (UserInfo item in list){Document document = new Document();//一条Document相当于一条记录document.Add(new Field("id",item.UserId.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//每个Document可以有自己的属性(字段),所有字段名都是自定义的,值都是string类型//想给用户展示什么就往词库里面添加什么document.Add(new Field("title",item.UserName, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));document.Add(new Field("content", item.UserContent, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));writer.AddDocument(document);}       writer.Close();//会自动解锁directory.Close();//不要忘了Close,否则索引结果搜不到}

  执行创建索引语句,将看到分词内容文件夹里面将多一些东西,这些就是用来以后检索的

->执行索引语句

    public ActionResult SearchContent(){//首先根据name区分是点击的哪个按钮if (!String.IsNullOrEmpty(Request.Form["btnSearch"]))//执行搜索{List<ViewSearchContentModel> recList=SearchBookContent();ViewData["searchList"] = recList;              return View("Index");}else//创建索引{CreateSearchIndex();//调用创建索引语句}return Content("OK");}

SearchBookContent类:

   //执行索引语句public List<ViewSearchContentModel> SearchBookContent(){string indexPath = @"H:\lucenedir"; //lucene存数据的路径string searchTxt = Request.Form["txtContent"];//获取用户输入的内容//将用户输入的内容进行分词List<string> kw=SearchController.GetPanGuWord(searchTxt);//string kw = "没有";FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());IndexReader reader = IndexReader.Open(directory, true);IndexSearcher searcher = new IndexSearcher(reader);PhraseQuery query = new PhraseQuery();//查询条件//query.Add(new Term("msg", kw));//where contains("msg",kw)  这里的msg对应上面的msgforeach (string word in kw)//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”{query.Add(new Term("content", word));//contains("msg",word)}query.SetSlop(100);//两个词的距离大于100(经验值)就不放入搜索结果,因为距离太远相关度就不高了TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);//盛放查询结果的容器searcher.Search(query, null, collector);//使用query这个查询条件进行搜索,搜索结果放入collector//collector.GetTotalHits()总的结果条数ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;//从查询结果中取出第m条到第n条的数据List<ViewSearchContentModel> list = new List<ViewSearchContentModel>();for (int i = 0; i < docs.Length; i++)//遍历查询结果{ViewSearchContentModel viewModel = new ViewSearchContentModel();int docId = docs[i].doc;//拿到文档的id。因为Document可能非常占内存(DataSet和DataReader的区别)//所以查询结果中只有id,具体内容需要二次查询Document doc = searcher.Doc(docId);//根据id查询内容。放进去的是Document,查出来的还是DocumentviewModel.Id = doc.Get("id");viewModel.Title = doc.Get("title");viewModel.Content = doc.Get("content");list.Add(viewModel);}return list;}class SearchResult{public int Id { get; set; }public string Msg { get; set; }}//利用盘古分词对用户输入的内容进行分词public static List<string> GetPanGuWord(string str){List<string> list=new List<string>();Analyzer analyzer = new PanGuAnalyzer();TokenStream tokenStream = analyzer.TokenStream("", new StringReader(str));Lucene.Net.Analysis.Token token = null;while ((token = tokenStream.Next()) != null){list.Add(token.TermText());// Console.WriteLine(token.TermText());}return list;}

ViewSearchContentModel类:(这个类定义在MVC中的Model里面的,视图要展示啥数据,这里就定义什么)

  

->前台修改如下:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server"><title>文档搜索</title>
</head>
<body><div><form method="post" action="/Search/SearchContent">请输入搜索的条件:<input type="text" name="txtContent" /><input type="submit" value="搜索" name="btnSearch"/><input type="submit" value="创建索引库" name="btnCreate"/></form> <table><tbody><%if (ViewData["searchList"] != null){foreach (站内搜索2.Models.ViewSearchContentModel item in (List<站内搜索2.Models.ViewSearchContentModel>)ViewData["searchList"]){%><tr><td><%=item.Id%></td><td><%=item.Title%></td><td><%=item.Content%></td></tr> <%  }          }    %></tbody></table></div>
</body>
</html>

-----这时基本搜索功能就实现了,接下来实现高亮显示-------

1.添加或引入PanGu.HighLight和PanGu.HighLight.pdb

链接:http://pan.baidu.com/s/1eS6W8s6 密码:ds8b

创建一个Common文件夹,并在里面建立一个WebCommon类

  

代码如下:(这个类中参数keyworkds就是要高亮显示的值,content就是返回的内容,这样在搜索结果中调用这个类就能实现高亮)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PanGu.HighLight;
using PanGu;namespace 站内搜索2.Common
{public  class WebCommon{public static string CreateHighLight(string keywords, string content){SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter("<font style='color:red'>", "</font>");Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new Segment());//设置每个摘要的字符数highlighter.FragmentSize = 150;return highlighter.GetBestFragment(keywords, content);}}
}

在搜索结果中调用这个类:

    //  viewModel.Content = doc.Get("content");viewModel.Content = Common.WebCommon.CreateHighLight(Request["txtContent"], doc.Get("content"));

写到这先放张效果图吧:

注意:有的时候我们使用razor引擎,会发生自动编码问题,为了正常显示,我们可以这样写:@MVCHtmlString.Create(item.Title)

JS侧栏分享代码:

<!-- JiaThis Button BEGIN -->
<script type="text/javascript" src="http://v3.jiathis.com/code/jiathis_r.js?move=0&btn=r4.gif" charset="utf-8"></script>
<!-- JiaThis Button END -->

最后再补充一下分词工具使用方式:

站内搜索源码下载:链接:http://pan.baidu.com/s/1o8IlAZK 密码:0gwf

转载于:https://www.cnblogs.com/shuai7boy/p/5564384.html

站内搜索——Lucene +盘古分词相关推荐

  1. Lucene.net站内搜索—5、搜索引擎第一版实现

    目录 Lucene.net站内搜索-1.SEO优化 Lucene.net站内搜索-2.Lucene.Net简介和分词 Lucene.net站内搜索-3.最简单搜索引擎代码 Lucene.net站内搜索 ...

  2. ajax+lucene pdf,基于Ajax/Lucene的站内搜索技术研究

    摘要: 站内搜索引擎是找出网站重要信息的必要工具,高效的站内搜索将有助于提升网站的价值,发挥网站应有的作用.虽然现在一些网络巨头已开始研究并应用这类工具,但整个互联网行业中,受制于技术的门槛,真正的站 ...

  3. 一步步开发自己的博客 .NET版(5、Lucenne.Net 和 必应站内搜索)

    前言 这次开发的博客主要功能或特点:     第一:可以兼容各终端,特别是手机端.     第二:到时会用到大量html5,炫啊.     第三:导入博客园的精华文章,并做分类.(不要封我)     ...

  4. 站内搜索--3--之Lucene.Net使用

    上一篇 站内搜索---2----之Log4Net使用 Lucene.Net是由Java版本的Lucene移植过来的,所有的类.方法都几乎和Lucene一模一样. Lucene.Net只是一个全文检索开 ...

  5. 用全文检索构建站内搜索和大数据搜索引擎

    全文检索首先对要搜索的文档进行分词,然后形成索引,通过查询索引来查询文档.全文检索是目前搜索引擎,大数据搜索的关键技术.全文检索系统可实现亚秒级的检索速度以及每秒上百次的并发检索支持. 需求: 实现淘 ...

  6. PHP站内搜索功能(laravel自带Scout驱动+elasticsearch)

    站内搜索 由于最近做的网站需要用到网站的站内搜索,我也是偷偷摸摸学了一手,希望有需要的朋友也可以看看 搜索引擎 Elasticsearch 官方网站 https://www.elastic.co/cn ...

  7. ElasticSearch技术方案(二)——站内搜索

    文章目录 背景 ES实现站内搜索 ES实现站内搜索 流程图 站内搜索实现分析 SpringBoot整合SpringData ElasticSearch 1. 引入依赖: 2.配置application ...

  8. java实现站内搜索

    1.站内搜索 在以往的网站建设,企业系统的搭建过程中,因为信息比较简单,比较少,站内搜索可能不是必要的选项,而今,时代的发展, 信息量的增大,网站逻辑的复杂,企业自身对信息架构.管理.发布的需求,以及 ...

  9. 站内搜索应用的方案设计的分析和总结

    http://www.poluoluo.com/jzxy/200907/63759.html 我为银杏泰克站内搜索服务商做产品顾问期间,经手了十几个站点的站内搜索应用的方案设计,略作一些分析和总结. ...

最新文章

  1. LNMP_ 配置文件
  2. CentOS下yum安装nginx服务
  3. cd命令无法切换路径(Windows下)
  4. python测验9_荐 测验9: Python计算生态纵览 (第9周)
  5. opencv4.2.0 视频去抖动算法代码
  6. vue mxgraph渲染xml页面_Vue的两个版本
  7. web提升服务器性能,开启一个参数就能让你的WEB性能提升3倍
  8. ZooKeeper分布式应用程序的分布式协调服务:概述,入门,发布版本
  9. tf.app.flags的使用教程
  10. 阿里云、腾讯云、UCloud 、华为云云主机对比测试报告
  11. day3--numpy
  12. POJ_3740 Easy Finding ——精确覆盖问题,DLX模版
  13. 一次Nginx 502问题解决
  14. 什么是DNS Spoofing, DNS Hijacking, and DNS Cache Poisoning?
  15. Android相机对焦问题
  16. Windows Dll 动态加载
  17. 雪浪数制CEO王峰:关于雪浪制造大脑的三大拷问 | 2018雪浪大会
  18. 软件工程——(1)软件与软件工程 思维导图
  19. Mac 媒体格式转换软件Permute
  20. Centos7 定时关机

热门文章

  1. flutter DateTime 日期时间详细解析 Dart语言基础
  2. Flutter透明度渐变动画FadeTransition实现透明度渐变动画效果
  3. C# Tostring 格式化输出字符串全解
  4. python -sorted 学习
  5. rails再体验(第一个程序)
  6. 地铁建设 (Standard IO)
  7. 使用java 遍历文件夹
  8. vs2010下载链接中国简体(中国含msdn)
  9. Codeforces Round #242 (Div. 2)C(找规律,异或运算)
  10. Android获取MAC地址