Lucene.net应用
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应用的更多相关文章
- lucene 基础知识点
部分知识点的梳理,参考<lucene实战>及网络资料 1.基本概念 lucence 可以认为分为两大组件: 1)索引组件 a.内容获取:即将原始的内容材料,可以是数据库.网站(爬虫).文本 ...
- 用lucene替代mysql读库的尝试
采用lucene对mysql中的表建索引,并替代全文检索操作. 备注:代码临时梳理很粗糙,后续修改. import java.io.File; import java.io.IOException; ...
- Lucene的评分(score)机制研究
首先,需要学习Lucene的评分计算公式—— 分值计算方式为查询语句q中每个项t与文档d的匹配分值之和,当然还有权重的因素.其中每一项的意思如下表所示: 表3.5 评分公式中的因子 评分因子 描 述 ...
- Lucene的分析资料【转】
Lucene 源码剖析 1 目录 2 Lucene是什么 2.1.1 强大特性 2.1.2 API组成- 2.1.3 Hello World! 2.1.4 Lucene roadmap 3 索引文件结 ...
- Lucene提供的条件判断查询
第一.按词条搜索 - TermQuery query = new TermQuery(new Term("name","word1"));hits = sear ...
- Lucene 单域多条件查询
在Lucene 中 BooleanClause用于表示布尔查询子句关系的类,包括:BooleanClause.Occur.MUST表示and,BooleanClause.Occur.MUST_NOT表 ...
- lucene自定义过滤器
先介绍下查询与过滤的区别和联系,其实查询(各种Query)和过滤(各种Filter)之间非常相似,可以这样说只要用Query能完成的事,用过滤也都可以完成,它们之间可以相互转换,最大的区别就是使用过滤 ...
- lucene+IKAnalyzer实现中文纯文本检索系统
首先IntelliJ IDEA中搭建Maven项目(web):spring+SpringMVC+Lucene+IKAnalyzer spring+SpringMVC搭建项目可以参考我的博客 整合Luc ...
- 全文检索解决方案(lucene工具类以及sphinx相关资料)
介绍两种全文检索的技术. 1. lucene+ 中文分词(IK) 关于lucene的原理,在这里可以得到很好的学习. http://www.blogjava.net/zhyiwww/archive/ ...
- MySQL和Lucene索引对比分析
MySQL和Lucene都可以对数据构建索引并通过索引查询数据,一个是关系型数据库,一个是构建搜索引擎(Solr.ElasticSearch)的核心类库.两者的索引(index)有什么区别呢?以前写过 ...
随机推荐
- 使用Hibernate SQLQuery(转)
原文地址:http://itindex.net/detail/51776-hibernate-sqlquery-sql,重新排了一下版 Hibernate对原生SQL查询的支持和控制是通过SQLQue ...
- 在Windows 10下启用旧的照片查看器
从Windows 10开始,默认只能通过“照片”来查看图片了,非常不方便!通过将下列文本保存在.reg文件后导入,即可找回Windows XP时代的“照片查看器”. Windows Registry ...
- 【emWin】例程八:绘制位图
实验指导书及代码包下载: 链接:http://pan.baidu.com/s/1bpeMYpp 密码:wgtp 实验现象:
- 【5集iCore3_ADP演示视频】5-1 iCore3应用开发平台开箱视频
iCore3双核心应用开发平台基于iCore3双核心板,包含ARM.FPGA.7寸液晶屏.双通道数字示波器.任意波发生器.电压表等模块,是一款专为电子爱好者设计的综合性电子学习系统. [视频简介]本视 ...
- PHP 天巡机票接口
一个旅游网站项目,网站需要机票预订接入了天巡机票接口,获取机票信息,不搞不知道,一搞吓一跳比较麻烦. 搜索机票信息需要分2步,首先POST获得一个SESSION,2秒之后,根据这个SESSION,从一 ...
- Java学习路线
总体思路:由表及里,勤于实践,纵横交错,融会贯通 Java语言----->JDK----->Java虚拟机原理----->编译原理----->操作系统原理----->计算 ...
- x86指令集同频性能提升
x86近5000条指令,迄今为止最复杂的指令集.这里不研究CISC & RISC,也不考虑process制程变化,主要是看最近几代IA架构对于同频率下性能的提升. x86指令集nasm文档 h ...
- redis服务器
Redis是一个Key-Value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括 string(字符串 ). list(链表). set(集合)和 zset(有序集合). ...
- js中网页高度与宽度那些事
网页可见区域宽:document.body.clientWidth; 网页可见区域高:document.body.clientHeight; 网页可见区域宽:document.body.offsetW ...
- SQL DEFAULT 约束
DEFAULT 约束用于向列中插入默认值. 如果没有规定其他的值,那么会将默认值添加到所有的新记录. 下面的 SQL 在 "Persons" 表创建时为 "City&qu ...