1、加入盘古分词方法

  /// <summary>
/// 对输入的搜索的条件进行分词
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static List<string> GetPanGuWord(string str)
{
Analyzer analyzer = new PanGuAnalyzer();
TokenStream tokenStream = analyzer.TokenStream("", new StringReader(str));
Lucene.Net.Analysis.Token token = null;
List<string> list = new List<string>();
while ((token = tokenStream.Next()) != null)
{
list.Add(token.TermText());
}
return list;
}

2、创建视图显示的MODEL(ViewModel)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web; namespace CZBK.ItcastOA.WebApp.Models
{
public class ViewSarchContentModel
{
public string Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
}
}

3、根据数据库表中字段创建索引

       /// <summary>
/// 负责向写数据
/// </summary>
private void CreateSearchIndex()
{
string indexPath = @"C:\lucenedir";//注意和磁盘上文件夹的大小写一致,否则会报错。将创建的分词内容放在该目录下。
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());//指定索引文件(打开索引目录) FS指的是就是FileSystem
bool isUpdate = IndexReader.IndexExists(directory);//IndexReader:对索引进行读取的类。该语句的作用:判断索引库文件夹是否存在以及索引特征文件是否存在。
if (isUpdate)
{
//同时只能有一段代码对索引库进行写操作。当使用IndexWriter打开directory时会自动对索引库文件上锁。
//如果索引目录被锁定(比如索引过程中程序异常退出),则首先解锁(提示一下:如果我现在正在写着已经加锁了,但是还没有写完,这时候又来一个请求,那么不就解锁了吗?这个问题后面会解决)
if (IndexWriter.IsLocked(directory))
{
IndexWriter.Unlock(directory);
}
}
IndexWriter writer = new IndexWriter(directory, new PanGuAnalyzer(), !isUpdate, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);//向索引库中写索引。这时在这里加锁。
List<Books>list= BookService.LoadEntities(c=>true).ToList(); foreach (Books bookModel in list)
{
writer.DeleteDocuments(new Term("Id",bookModel.Id.ToString()));
Document document = new Document();//表示一篇文档。
//Field.Store.YES:表示是否存储原值。只有当Field.Store.YES在后面才能用doc.Get("number")取出值来.Field.Index. NOT_ANALYZED:不进行分词保存
document.Add(new Field("Id",bookModel.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED)); //Field.Index. ANALYZED:进行分词保存:也就是要进行全文的字段要设置分词 保存(因为要进行模糊查询) //Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS:不仅保存分词还保存分词的距离。
document.Add(new Field("Title", bookModel.Title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS)); document.Add(new Field("Content", bookModel.ContentDescription, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS)); writer.AddDocument(document);
} writer.Close();//会自动解锁。
directory.Close();//不要忘了Close,否则索引结果搜不到 }

4、搜索

       private List<ViewSarchContentModel> SearchBookContent()
{
string indexPath = @"C:\lucenedir";
List<string> kw =Common.WebCommon.GetPanGuWord(Request["txtContent"]); FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
IndexReader reader = IndexReader.Open(directory, true);
IndexSearcher searcher = new IndexSearcher(reader);
//搜索条件
PhraseQuery query = new PhraseQuery();
foreach (string word in kw)//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
{
query.Add(new Term("Content", word));
}
//query.Add(new Term("body","语言"));--可以添加查询条件,两者是add关系.顺序没有关系.
//query.Add(new Term("body", "大学生"));
//query.Add(new Term("body", kw));//body中含有kw的文章
query.SetSlop();//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
//TopScoreDocCollector是盛放查询结果的容器
TopScoreDocCollector collector = TopScoreDocCollector.create(, true);
searcher.Search(query, null, collector);//根据query查询条件进行查询,查询结果放入collector容器
ScoreDoc[] docs = collector.TopDocs(, collector.GetTotalHits()).scoreDocs;//得到所有查询结果中的文档,GetTotalHits():表示总条数 TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
//可以用来实现分页功能 List<ViewSarchContentModel> list = new List<ViewSarchContentModel>();
for (int i = ; i < docs.Length; i++)
{
ViewSarchContentModel viewModel = new ViewSarchContentModel();
//
//搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document. int docId = docs[i].doc;//得到查询结果文档的id(Lucene内部分配的id)
Document doc = searcher.Doc(docId);//找到文档id对应的文档详细信息
viewModel.Id = doc.Get("Id");
viewModel.Title = doc.Get("Title");
viewModel.Content =Common.WebCommon.CreateHightLight(Request["txtContent"], doc.Get("Content"));//搜索内容关键字高亮显示
list.Add(viewModel); }
return list;
}

5、返回给VIEW

 public ActionResult SearchContent()
{
if (!string.IsNullOrEmpty(Request["btnSearch"]))
{
List<ViewSarchContentModel>list= SearchBookContent();
ViewData["searchList"] = list;
ViewData["searchWhere"] = Request["txtContent"];
return View("Index");
}
else
{
CreateSearchIndex();
}
return Content("ok");
}

6、视图表现

@{
Layout = null;
}
@using CZBK.ItcastOA.WebApp.Models
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>文档搜索</title>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<style type="text/css">
.search-text2{ display:block; width:528px; height:26px; line-height:26px; float:left; margin:3px 5px; border:1px solid; font-family:'Microsoft Yahei'; font-size:14px;}
.search-btn2{width:102px; height:32px; line-height:32px; cursor:pointer; border:0px; background-color:#d6000f;font-family:'Microsoft Yahei'; font-size:16px;color:#f3f3f3;}
.search-list{width:600px; overflow:hidden; margin:10px 20px 0px 20px;}
.search-list dt{font-family:'Microsoft Yahei'; font-size:16px; line-height:20px; margin-bottom:7px; font-weight:normal;}
.search-list .search-detail{font-size:12px; color:#666666;margin-bottom:5px; font-family:Arial;line-height:16px;}
.search-list dt a{color:#2981a9;}
</style> </head>
<body> <!-- JiaThis Button BEGIN -->
<script type="text/javascript" >
var jiathis_config = {
data_track_clickback: true,
showClose: true,
hideMore: false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jiathis_r.js?uid=1986459&type=left&btn=l.gif&move=0" charset="utf-8"></script>
<!-- JiaThis Button END -->
<div>
<form method="get" action="/Search/SearchContent">
<input type="text" value="@ViewData["searchWhere"]" name="txtContent" autocomplete="off" class="search-text2"/>
<input type="submit" value="搜一搜" name="btnSearch" class="search-btn2" />
<input type="submit" value="创建索引库" name="btnCreate" />
</form> <dl class="search-list">
@if (ViewData["searchList"] != null)
{
foreach (ViewSarchContentModel viewModel in (List<ViewSarchContentModel>)ViewData["searchList"])
{
<dt><a href="/Book/ShowDetail/?id=@viewModel.Id"> @viewModel.Title</a></dt>
<dd class="search-detail">@MvcHtmlString.Create(viewModel.Content)</dd>
}
}
</dl> </div>
</body>
</html>

改变输入框、按钮样式,高亮显示

 <style type="text/css">
.search-text2{ display:block; width:528px; height:26px; line-height:26px; float:left; margin:3px 5px; border:1px solid; font-family:'Microsoft Yahei'; font-size:14px;}
.search-btn2{width:102px; height:32px; line-height:32px; cursor:pointer; border:0px; background-color:#d6000f;font-family:'Microsoft Yahei'; font-size:16px;color:#f3f3f3;}
.search-list{width:600px; overflow:hidden; margin:10px 20px 0px 20px;}
.search-list dt{font-family:'Microsoft Yahei'; font-size:16px; line-height:20px; margin-bottom:7px; font-weight:normal;}
.search-list .search-detail{font-size:12px; color:#666666;margin-bottom:5px; font-family:Arial;line-height:16px;}
.search-list dt a{color:#2981a9;}
</style>

盘古分词的高亮组件PanGu.HighLight.dll,引用高亮显示组件

    // /创建HTMLFormatter,参数为高亮单词的前后缀
public static string CreateHightLight(string keywords, string Content)
{
PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter =
new PanGu.HighLight.SimpleHTMLFormatter("<font color=\"red\">", "</font>");
//创建Highlighter ,输入HTMLFormatter 和盘古分词对象Semgent
PanGu.HighLight.Highlighter highlighter =
new PanGu.HighLight.Highlighter(simpleHTMLFormatter,
new Segment());
//设置每个摘要段的字符数
highlighter.FragmentSize = ;
//获取最匹配的摘要段
return highlighter.GetBestFragment(keywords, Content); }

keywords搜索关键词,Content搜索结果

viewModel.Content =Common.WebCommon.CreateHightLight(Request["txtContent"], doc.Get("Content"));//搜索内容关键字高亮显示

视图中

<dd class="search-detail">@MvcHtmlString.Create(viewModel.Content)</dd>

@输出进行了编码,用@会输出HTML标签

Lucene每次生成索引不会删除、覆盖以前生成的,会造成搜索时搜索到重复的记录,所以生成前先要删除一次(实质没有删除文件,只是给文件个删除标记)

writer.DeleteDocuments(new Term("Id",bookModel.Id.ToString()));

搜索页面采用<form method="get" .............>,并采用静态页面:有利于网站推广

分享到

加<script src="~/Scripts/jquery-1.7.1.min.js"></script>

并将以下代码放入body
<!-- JiaThis Button BEGIN -->
<script type="text/javascript" >
var jiathis_config = {
data_track_clickback: true,
showClose: true,
hideMore: false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jiathis_r.js?uid=1986459&type=left&btn=l.gif&move=0" charset="utf-8"></script>
<!-- JiaThis Button END -->

Lucene.net应用的更多相关文章

  1. lucene 基础知识点

    部分知识点的梳理,参考<lucene实战>及网络资料 1.基本概念 lucence 可以认为分为两大组件: 1)索引组件 a.内容获取:即将原始的内容材料,可以是数据库.网站(爬虫).文本 ...

  2. 用lucene替代mysql读库的尝试

    采用lucene对mysql中的表建索引,并替代全文检索操作. 备注:代码临时梳理很粗糙,后续修改. import java.io.File; import java.io.IOException; ...

  3. Lucene的评分(score)机制研究

    首先,需要学习Lucene的评分计算公式—— 分值计算方式为查询语句q中每个项t与文档d的匹配分值之和,当然还有权重的因素.其中每一项的意思如下表所示: 表3.5 评分公式中的因子 评分因子 描 述 ...

  4. Lucene的分析资料【转】

    Lucene 源码剖析 1 目录 2 Lucene是什么 2.1.1 强大特性 2.1.2 API组成- 2.1.3 Hello World! 2.1.4 Lucene roadmap 3 索引文件结 ...

  5. Lucene提供的条件判断查询

    第一.按词条搜索 - TermQuery query = new TermQuery(new Term("name","word1"));hits = sear ...

  6. Lucene 单域多条件查询

    在Lucene 中 BooleanClause用于表示布尔查询子句关系的类,包括:BooleanClause.Occur.MUST表示and,BooleanClause.Occur.MUST_NOT表 ...

  7. lucene自定义过滤器

    先介绍下查询与过滤的区别和联系,其实查询(各种Query)和过滤(各种Filter)之间非常相似,可以这样说只要用Query能完成的事,用过滤也都可以完成,它们之间可以相互转换,最大的区别就是使用过滤 ...

  8. lucene+IKAnalyzer实现中文纯文本检索系统

    首先IntelliJ IDEA中搭建Maven项目(web):spring+SpringMVC+Lucene+IKAnalyzer spring+SpringMVC搭建项目可以参考我的博客 整合Luc ...

  9. 全文检索解决方案(lucene工具类以及sphinx相关资料)

    介绍两种全文检索的技术. 1.  lucene+ 中文分词(IK) 关于lucene的原理,在这里可以得到很好的学习. http://www.blogjava.net/zhyiwww/archive/ ...

  10. MySQL和Lucene索引对比分析

    MySQL和Lucene都可以对数据构建索引并通过索引查询数据,一个是关系型数据库,一个是构建搜索引擎(Solr.ElasticSearch)的核心类库.两者的索引(index)有什么区别呢?以前写过 ...

随机推荐

  1. baiduMap

    1.把百度地图定位API(下载地址:http://lbsyun.baidu.com/sdk/download?selected=location),里面的lib福祉到自己的项目中 2,进行相关配置(官 ...

  2. vm安装centos 老是出现 grub.conf 配置问题

    vm 环境 11  centos 6.5 最开始用的是vm12 发现安装软件一会就出现 客户机操作系统已禁用 cpu.请关闭或重置虚拟机 以为是新机器的cpu或者主板有问题,换vm,换系统依然会出现这 ...

  3. PHP $_SERVER['SCRIPT_FILENAME'] 与 __FILE__ 的区别 有点像static 和 self的意思 !

    PHP $_SERVER['SCRIPT_FILENAME'] 与 __FILE__ 通常情况下,PHP $_SERVER['SCRIPT_FILENAME'] 与 __FILE__ 都会返回 PHP ...

  4. asp.net identity 3.0.0 在MVC下的基本使用(一)

    注册时信箱转为用户名. 本人习惯使用用户名做注册用户,因为不管是什么终端起码都能少输入几个字符,可以提高用户体验. 这里需要更改控制器,模型和视图 1.打开Controllers目录下的Account ...

  5. [archlinux][hardware] ThankPad T450自带SSD做bcache之后的使用寿命分析

    这个分析的起因,是由于我之前干了这两个事: [troubleshoot][archlinux][bcache] 修改linux文件系统 / 分区方案 / 做混合硬盘 / 系统转生大!手!术!(调整底层 ...

  6. H5 FormData对象的使用

    XMLHttpRequest Level2 添加了一个新的接口--FormData .[ 主要用于发送表单数据,但也可以独立使用于传输键控数据.与普通的Ajax相比,它能异步上传二进制文件 ] 利用F ...

  7. libgdx 裁剪多边形(clip polygon、masking polygon)

    直接放例子代码,代码中以任意四边形为例,如果需要做任意多边形,注意libgdx不能直接用ShapeRender填充多边形,需要先切割成三角形. public static void drawClip( ...

  8. 【转】24Cxx 系列EEPROM通用程序及应用

    关于I2C 学习的时候介绍得最多的就是24C02 这里存储EEPROM了,但学的时候基本只是讲讲简单的I2C 的总线数据传输而已,即使先gooogle上搜索也绝大部分这这样的文章,很少有说到如何在实际 ...

  9. 安装springboot时遇到 LoggerFactory is not a Logback LoggerContext but Logback is on the classpath.问题

    将工程外部jar包删除slf4j就可以运行.

  10. 【OpenWRT】【RT5350】【三】MakeFile文件编写规则和OpenWRT驱动开发步骤

    一.Makefile文件编写 http://www.cnblogs.com/majiangjiang/articles/3218002.html 可以看下上面的博客,总结的比较全了,在此不再复述 二. ...