将log4net.dll、Lucene.Net.dll、PanGu.dll、PanGu.HighLight.dll、PanGu.Lucene.Analyzer.dll 复制到项目目录下,并添加其引用。
将盘古算法的词库Dict/.... 文件复制到项目目录下,并右击--属性--如果较新则复制。
Views/Search/Index.cshtml (view视图):
@{
Layout = null;
}
@using MyWeb.WebApp.Models
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>搜索</title>
<style type="text/css">
.search-text2{ display:block; width:528px; height:26px; line-height:26px; float:left; margin:3px 5px; border:1px solid gray; outline:none; 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-con{width:640px; background-color:#fff; overflow:hidden; margin-top:0px; padding-bottom:15px; padding-top:5px;}
.search-list{width:600px; overflow:hidden; margin:15px 20px 0px 20px;}
.search-list dt{font-family:'Microsoft Yahei'; font-size:16px; line-height:20px; margin-bottom:7px; font-weight:normal;}
.search-list dt a{color:#2981a9;}
.search-list dt a em{ font-style:normal; color:#cc0000;}
</style>
</head>
<body>
<div>
<form method="get" action="/Search/SearchContent">
<input type="text" name="txtSearch" class="search-text2" />
<input type="submit" value="搜一搜" name="btnSearch" class="search-btn2" />
@* <input type="submit" value="创建索引库" name="btnCreate" />*@
</form>
<br />
<div class="search-list-con">
<dl class="search-list">
@if(ViewData["list"]!=null)
{
foreach (ViewModelContent viewModel in (List<ViewModelContent>)ViewData["list"])
{
<dt><a href="javascript:void(0)"> @viewModel.Title</a></dt>
<dd>@MvcHtmlString.Create(viewModel.Content)</dd> <!--MvcHtmlString不会将内容再进行HTML编码(高亮显示)-->
}
}
</dl>
</div>
</div>
</body>
</html>
Controllers/SearchController(控制器):
using MyWeb.Model;
using MyWeb.WebApp.Models;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MyWeb.WebApp.Controllers
{
public class SearchController : Controller
{
//
// GET: /Search/
IBLL.IBooksService BooksService { get; set; }
public ActionResult Index()
{
return View();
}
/// <summary>
/// 表单中有多个Submit,单击每个Submit都会提交表单,但是只会将用户所单击的提交按钮元素的value值提交到服务端。
/// </summary>
/// <returns></returns>
public ActionResult SearchContent()
{
if (!string.IsNullOrEmpty(Request["btnSearch"])) //如果用户点击的是搜索
{
List<ViewModelContent>list=ShowSearchContent();
ViewData["list"] = list;
return View("Index");
}
else //否则 则是创建Lucene.net索引库
{
CreateSerachContent();
}
return Content("ok");
}
private List<ViewModelContent> ShowSearchContent()
{
string indexPath = @"C:\lucenedir"; //Lucene.net索引库的目录。
List<string> list =Common.WebCommon.PanGuSplitWord(Request["txtSearch"]);//对用户输入的搜索条件进行拆分。
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 list)//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
{
query.Add(new Term("Content", word)); //添加查询条件(查询关键字(分词))。
}
//query.Add(new Term("body","语言"));--可以添加查询条件,两者是add关系.顺序没有关系.查询含有"语言"的body。
// query.Add(new Term("body", "大学生"));
// query.Add(new Term("body", kw));//body中含有kw的文章
query.SetSlop(100);//多个查询条件的词之间的最大距离.在文章中相隔太远 也就无意义.(例如 “大学生”这个查询条件和"简历"这个查询条件之间如果间隔的词太多也就没有意义了。)
//TopScoreDocCollector是盛放查询结果的容器
TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
searcher.Search(query, null, collector);//根据query查询条件进行查询,查询结果放入collector容器
ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;//得到所有查询结果中的文档,GetTotalHits():表示总条数 TopDocs(300, 20);//表示得到300(从300开始),到320(结束)的文档内容.
//可以用来实现分页功能
List<ViewModelContent> viewModelList = new List<ViewModelContent>();
for (int i = 0; i < docs.Length; i++)
{
//
//搜索ScoreDoc[]只能获得文档的id,这样不会把查询结果的Document一次性加载到内存中。降低了内存压力,需要获得文档的详细内容的时候通过searcher.Doc来根据文档id来获得文档的详细内容对象Document.
ViewModelContent viewModel = new ViewModelContent();
int docId = docs[i].doc;//得到查询结果文档的id(Lucene内部分配的id)
Document doc = searcher.Doc(docId);//找到文档id对应的文档详细信息
viewModel.Id=Convert.ToInt32(doc.Get("Id"));//取出放进ID字段的值
viewModel.Title=doc.Get("Title");
viewModel.Content =Common.WebCommon.CreateHightLight(Request["txtSearch"],doc.Get("Content"));//将搜索的关键字高亮显示。
viewModelList.Add(viewModel);
}
return viewModelList;
}
//创建Lucene.net索引库,该方法未考虑并发修改索引库的情况。(添加索引实体Model(新闻、商品)时,先添加到数据库,在添加到Lucene.net中(更新索引库))
private void CreateSerachContent()
{
//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=BooksService.LoadEntities(b=>true).ToList();
//foreach (var bookModel in list)
//{
// 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,否则索引结果搜不到
}
}
}
MyWeb.WebApp/Models/IndexManager.cs(通过队列解决并发修改Lucene.net索引库的问题(生产者消费者,线程,Global全局类文件开启线程)):
using MyWev.Model.EnumType;
using Lucene.Net.Analysis.PanGu;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Store;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
namespace MyWeb.WebApp.Models
{
public sealed class IndexManager //该类做成单例模式的,使用的是同一个公共的队列。sealed表示不可以被继承。
{
private static readonly IndexManager indexManager = new IndexManager();
private IndexManager() //构造方法
{
}
public static IndexManager GetInstance() //单例模式,获取实例
{
return indexManager;
}
//通过队列(生产者消费者模式),来解决并发创建索引库的问题。(每一次添加索引实体Model时,都要保存到数据库,然后再保存到Lucene.net中(创建索引库))
public Queue<ViewModelContent> queue = new Queue<ViewModelContent>();
//要添加和修改(先删除再添加)的数据放入队列。
public void AddQueue(int id, string title, string content)
{
ViewModelContent viewModel = new ViewModelContent();
viewModel.Id = id;
viewModel.Title = title;
viewModel.Content = content;
viewModel.LuceneTypeEnum = LuceneTypeEnum.Add; //用于区别是添加还是删除的枚举类型。
queue.Enqueue(viewModel);
}
/// 要删除的数据也放入队列。
public void DeleteQueue(int id)
{
ViewModelContent viewModel = new ViewModelContent();
viewModel.Id = id;
viewModel.LuceneTypeEnum = LuceneTypeEnum.Delete;//用于区别是添加还是删除的枚举类型。
queue.Enqueue(viewModel);
}
/// 开始一个线程。线程在Global.asax.cs中开启。
public void StartThread()
{
Thread thread = new Thread(WriteIndexContent);
thread.IsBackground = true;
thread.Start();
}
/// 检查队列中是否有数据,如果有数据就获取。
private void WriteIndexContent()
{
while (true)
{
if (queue.Count > 0)
{
CreateIndexContent();
}
else
{
Thread.Sleep(3000);
}
}
}
//如果队列中有数据,就保存到Lucene.net中。
private void CreateIndexContent()
{
string indexPath = @"C:\lucenedir"; //Lucene.net索引库的目录。注意和磁盘上文件夹的大小写一致,否则会报错。将创建的分词内容放在该目录下。//将路径写到配置文件中。
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);//向索引库中写索引。这时在这里加锁。
//如果队列中有数据,获取队列中的数据写到Lucene.Net中。
while (queue.Count > 0)
{
ViewModelContent viewModel = queue.Dequeue(); //ViewModelContent是自定义的输出显示的Model实体类型。
writer.DeleteDocuments(new Term("Id", viewModel.Id.ToString()));//删除。根据document中"Id"字段删除。
if (viewModel.LuceneTypeEnum == LuceneTypeEnum.Delete)
{
continue; //如果是删除,就直接进行下一次循环,不继续向下执行添加的操作。
}
Document document = new Document();//表示一篇文档。
//Field.Store.YES:表示是否存储原值。只有当Field.Store.YES在后面才能用doc.Get("Id")取出值来。Field.Index.NOT_ANALYZED:表示Id不需要进行盘古分词
document.Add(new Field("Id", viewModel.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", viewModel.Title, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
document.Add(new Field("Content", viewModel.Content, Field.Store.YES, Field.Index.ANALYZED, Lucene.Net.Documents.Field.TermVector.WITH_POSITIONS_OFFSETS));
writer.AddDocument(document); //添加。
}
writer.Close();//会自动解锁。
directory.Close();//不要忘了Close,否则索引结果搜不到
}
}
}
MyWeb.WebApp/Models/ViewModelContent.cs(用于显示搜索结果的自定义的搜索实体Model):
using MyWeb.Model.EnumType;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace MyWeb.WebApp.Models
{
public class ViewModelContent
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public LuceneTypeEnum LuceneTypeEnum { get; set; } //用于区别是用于删除还是添加(或修改)(添加之前先删除一遍)的枚举类型。(修改就是先删除再添加)
}
}
MyWeb.Common/WebCommon.cs(用于将用户的搜索条件进行盘古分词,将搜索结果高亮显示的工具类):
using Lucene.Net.Analysis;
using Lucene.Net.Analysis.PanGu;
using PanGu;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace MyWeb.Common
{
public class WebCommon
{
//将msg进行盘古分词,返回所有分词的List。(将用户的检索条件进行盘古分词)
public static List<string> PanGuSplitWord(string msg)
{
Analyzer analyzer = new PanGuAnalyzer();
TokenStream tokenStream = analyzer.TokenStream("", new StringReader(msg));
Lucene.Net.Analysis.Token token = null;
List<string> list = new List<string>();
while ((token = tokenStream.Next()) != null)
{
list.Add(token.TermText());
}
return list;
}
//创建HTMLFormatter,参数为高亮单词的前后缀。keywords表示要高亮显示的关键字,Content是要显示处理的文本摘要。
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 = 150;
//获取最匹配的摘要段
return highlighter.GetBestFragment(keywords, Content);
}
}
}
Global.asax.cs(全局应用程序类,开启线程读取队列):
using MyWeb.WebApp.Models;
using log4net;
using Spring.Web.Mvc;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace MyWeb.WebApp
{
public class MvcApplication : SpringMvcApplication //System.Web.HttpApplication
{
protected void Application_Start()
{
IndexManager.GetInstance().StartThread();//开始线程扫描LuceneNet对应的数据队列。
//。。。。。。。。
}
}
}
生产者消费者模式(队列,线程,Global全局文件开启线程)可以参考异常捕获和异常日志记录:
捕获异常:http://blog.csdn.net/houyanhua1/article/details/79050120
异常日志记录:http://blog.csdn.net/houyanhua1/article/details/79052264
注:本文不对快速排序作任何解释,建议在对快速排序有一定了解后再阅览一、问题分析最简单的做法应该是直接选择先将集合排序(比如快速排序),然后直接以k为下标从有序集合中获取。但是这样做时间复杂度其实是比较大的。如果要想要提升一下效率,可以考虑在快速排序的原理下稍微做点修改。二、修改快排1、主元素的位置特殊性在快速排序中,第一步是选取主元素(这里记为x),然后将小于主元素x的数放在x左边,剩下的所有大于...
ethercat数据帧是基于ethernet数据帧的,整体来讲也就是:ethernet数据报头 + ethernet数据 + FCS这样的格式;而ethercat子报文则填充在ethernet数据部分进行发送,具体来说呢,整体的格式如下:先暂时只讨论子报文数据部分,具体的整个的报文组成放在之后描述,那么在子报文中,他的构成也可以大体明白了,就是 子报文头+子报文数据+WKC,先了解子报...
ROS的安装教程1.配置ubuntu的软件和更新首先打开“软件和更新”对话框,打开后按照下图进行配置(确保你的"restricted", “universe,” 和 "multiverse."前是打上勾的)可切换到最佳服务器,有利于后续下载(打开上图所示“下载自”,点击选择最佳服务器)2.安装源清华的安装源sudo sh -c '. /etc/lsb-release && echo "deb http://mirrors.tuna.tsinghua.edu.cn/ros/
Office365 删除自定义域我们前面介绍了很多关于Azure及Office365的功能,今天我们主要介绍如何快速删除自定义域,删除自定义域我们需要介绍Azure Powershell来完成整个操作。具体见下下载powershellPowerShell connect to Windows Azure AD请您直接打开以下链接,https://technet.microsoft.com/zh-...
1、npm install --global vue-cli报错:reason: getaddrinfo ENOTFOUND “xxxxxxxx”【解决方案】:通过npm get registry查看当前镜像;进行切换为淘宝镜像( npm config set registry https://registry.npm.taobao.org);再重新尝试即可2、npm install -g cnpm registry=https://registry.npm.taobao.org报错:"regis
acl概述acl (全称Advanced C Library)是一个跨平台(支持LINUX,WIN32,Solaris,MacOS,FreeBSD)的网络通信库及服务器编程框架,同时提供更多的实用功能库。用户通过该库可以非常容易地编写支持多种模式(多线程、多进程、非阻塞、触发器、UDP方式、协程方式)的服务器程序,WEB 应用程序,数据库应用程序。此外,该库还提供了常见应用的客户端通信库(如:HT...
最近偶尔有人问我程序员网上有什么好的学习网站,说实话,现在网上资源比较多,也比较杂乱,我这里给大家推荐几个,希望大家喜欢,如果觉得不错的话,文末请点赞顺手加个关注。1、哔哩哔哩登录网址:https://www.bilibili.com/bilibili 是国内知名的视频弹幕网站,通过动漫打出了名声,最近几年发展势头迅猛,里面有不少有创意的 Up 主,不乏一些有趣的程序员,也有很多免费的视频学...
简介:Shopro商城 uniapp前端开源代码,一款落地生产的 基于uni-app的多端商城。目前适配了微信小程序 + 微信公众号 + H5 +网盘下载地址:http://kekewl.net/6QrTWAxrvY90图片:
第7章 排序一、选择题1.某内排序方法的稳定性是指( D )。 A.该排序算法不允许有相同的关键字记录 B.该排序算法允许有相同的关键字记录C.平均时间为0(n log n)的排序方法 D.以上都不对 2.下面给出的四种排序法中( D )排序法是不稳定性排序法。 A. 插入 B. 冒泡 C.
以4.21版本为例1、复制steam程序中的dll文件至本地引擎文件内*\UE_4.21\Engine\Binaries\ThirdParty\Steamworks\Steamv1392、最终结果如下3、打开工程文件内的Engine.ini配置文件添加如下代码 1 [/Script/Engine.GameEngine] 2 +NetDriverDe...
一、数据库https://www.cnblogs.com/wenxiaofei/p/9853682.htmlQ:数据库中的事务了解吗?事务的四大特性?数据库事务是数据库运行中的逻辑工作单位,单个逻辑工作单元所执行的一系列操作,要么都执行,要么都不执行。例如银行取款事务分为2个步骤(1)存折减款(2)提取现金,2个步骤必须同时完成或者都不完成。数据库事务的四大特性(ACID):(...