热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

全文检索:分词,索引

主要用到lucene索引技术及盘古分词技术,可创建索引,修改索引,删除索引等全套代码。此代码直接复制调用即可,注意生成索引文件夹(SearchIndex

主要用到lucene索引技术及盘古分词技术,可创建索引,修改索引,删除索引等全套代码。

此代码直接复制调用即可,注意生成索引文件夹(SearchIndex),如果大家有什么不明白的可以直接来问我,715417165  qq

主要业务调用:

using Lucene.api;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Lucene
{
public partial class lucene : System.Web.UI.Page
{
public List searchlist_pangu = null;
protected void Page_Load(object sender, EventArgs e)
{
var action = Request.Params["action"];
var words = Request.Params["words"];

switch (action)
{
case "createIndex":
CreateIndex();
break;
case "deleteAll":
DeleteAll();
break;
case "search":
Search(words);
break;
default:
break;
}
}

///
/// search
///

public void Search(string words)
{
if (!String.IsNullOrEmpty(words.Trim()))
{
#region 全文检索
int count = 0;
int pageIndex = 1;
int pageSize = 2;
StringBuilder str = new StringBuilder();
//List searchlist = PanGuLuceneHelper.instance.Search("超级兵王");
searchlist_pangu = PanGuLuceneHelper.instance.Search("1", Server.HtmlDecode(words), pageIndex, pageSize,false, out count);
//if (searchlist == null || searchlist.Count == 0)
//{

//}
var versioin = PanGuLuceneHelper.instance.version;
if (searchlist_pangu == null || searchlist_pangu.Count == 0)
{
str.AppendFormat("检索结果:当前检索无任何值");
}
else
{
//PanGuLuceneHelper.instance.version
}
#endregion
}
else
{

}
}

///
/// 创建索引
///

public void CreateIndex()
{
//new Random().Next(1, 100000).ToString()
List list = new List();
list.Add(new MySearchUnit("329366", "超级兵王1", "他是雇佣兵世界的王者1,他是令各国元首头疼的兵王!为朋友,他甘愿两肋插刀;为亲人,不惜血溅五步!是龙,终要翱翔于九天之上,携风云之势,一路高歌猛进,混的风生水起。", "1", "", ""));
list.Add(new MySearchUnit("80000437", "绝世邪神", "重生异世,放荡不羁的叶楚面对众多绝世天才,倾世红颜。他如何踏破苍穹,撼动诸天,世人仰望!", "1", "", ""));
list.Add(new MySearchUnit("357332", "错入豪门:老公别碰我", "他的残忍,情人的挑衅,最终将她折磨的遍体鳞伤就在要放弃的时候,他却温柔对待。以为他爱上自己的时候,他却挽着别的女人高调结婚,甩给她一张离婚协议书!", "1", "", ""));
list.Add(new MySearchUnit("358089", "一吻成瘾", "那一夜,她大胆热辣,缠绵过后,本以为两人不会再有交集,却在回国后再次重逢,而他的未婚妻,竟是自己同父异母的姐姐!", "", "", ""));
list.Add(new MySearchUnit("80000556", "腹黑谋少法医妻", "她是随时可能失业的前任女法医,他是京城贵少,胸有谋略,却黑心无比。她急于把自己嫁出去,摆脱麻烦;他需要娶个女人,给他老子找点麻烦。他掩着眸中的邪恶,“你是自愿和我结婚的吧?”她点头,很认真地和他办了结婚证。她以为,结婚不过是各取所需摆个形式罢了,可他居然……贺鎏阳,你个黑心土匪!", "1", "", ""));
list.Add(new MySearchUnit("80000789", "无敌萌妻限量版", "他是C城翻手为云覆手为雨的南宫集团首席执行官,身家过亿,却偏偏被当成牛郎睡了,为报此仇,他势要将此人大卸八块拿去喂狗。她是一枚小小设计师,胸怀梦想,无奈现实骨感,可不小心睡了上司之后竟然走了狗屎运成为顶尖设计师!她抱着总裁大腿,感激涕零。为了看牢这个金大腿,她一路过关斩将,弃渣竹马,斗情敌,终于稳固自己总裁夫人的头衔。", "1", "", ""));
PanGuLuceneHelper.instance.CreateIndex(list,true);//添加索引
}

///
/// 删除全部索引
///

public void DeleteAll()
{
PanGuLuceneHelper.instance.DeleteAll();//删除全部
}

///
/// 删除key的索引
///

///
public void DeleteID(string id)
{
PanGuLuceneHelper.instance.Delete(id);//根据id删除
}

}
}


核心处理类:

using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Web;

namespace Lucene.api
{

///
/// 盘古分词在lucene.net中的使用帮助类
/// 调用PanGuLuceneHelper.instance
///

public class PanGuLuceneHelper
{
private PanGuLuceneHelper() { }

#region 单一实例
private static PanGuLuceneHelper _instance = null;
///
/// 单一实例
///

public static PanGuLuceneHelper instance
{
get
{
if (_instance == null) _instance = new PanGuLuceneHelper();
return _instance;
}
}
#endregion

#region 分词测试
///
/// 分词测试
///

///
///
public string Token(string keyword)
{
string ret = "";
System.IO.StringReader reader = new System.IO.StringReader(keyword);
Lucene.Net.Analysis.TokenStream ts = analyzer.TokenStream(keyword, reader);
bool hasNext = ts.IncrementToken();
Lucene.Net.Analysis.Tokenattributes.ITermAttribute ita;
while (hasNext)
{
ita = ts.GetAttribute();
ret += ita.Term + "|";
hasNext = ts.IncrementToken();
}
ts.CloneAttributes();
reader.Close();
analyzer.Close();
return ret;
}
#endregion

#region 创建索引
///
/// 创建索引
///

/// 数据
/// false表示追加(true表示删除之前的重新写入),注意ID唯一
///
public bool CreateIndex(List datalist, bool indexAdd)
{
IndexWriter writer = null;
try
{
writer = new IndexWriter(directory_luce, analyzer, indexAdd, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示删除之前的重新写入)
}
catch
{
writer = new IndexWriter(directory_luce, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示删除之前的重新写入)
}
foreach (MySearchUnit data in datalist)
{
CreateIndex(writer, data);
}
writer.Optimize();
writer.Dispose();
return true;
}

///
/// 创建索引
///

///
///
public bool CreateIndex(List datalist)
{
IndexWriter writer = null;
try
{
writer = new IndexWriter(directory_luce, analyzer, false, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示删除之前的重新写入)
}
catch
{
writer = new IndexWriter(directory_luce, analyzer, true, IndexWriter.MaxFieldLength.LIMITED);//false表示追加(true表示删除之前的重新写入)
}
foreach (MySearchUnit data in datalist)
{
CreateIndex(writer, data);
}
writer.Optimize();
writer.Dispose();
return true;
}

public bool CreateIndex(IndexWriter writer, MySearchUnit data)
{
try
{

if (data == null) return false;
Document doc = new Document();
Type type = data.GetType();//assembly.GetType("Reflect_test.PurchaseOrderHeadManageModel", true, true); //命名空间名称 + 类名

//创建类的实例
//object obj = Activator.CreateInstance(type, true);
//获取公共属性
PropertyInfo[] Propertys = type.GetProperties();
for (int i = 0; i {
//Propertys[i].SetValue(Propertys[i], i, null); //设置值
PropertyInfo pi = Propertys[i];
string name = pi.Name;
object objval = pi.GetValue(data, null);
string value = objval == null ? "" : objval.ToString(); //值
if (name == "id" || name == "flag")//id在写入索引时必是不分词,否则是模糊搜索和删除,会出现混乱
{
doc.Add(new Field(name, value, Field.Store.YES, Field.Index.NOT_ANALYZED));//id不分词
}
else
{
doc.Add(new Field(name, value, Field.Store.YES, Field.Index.ANALYZED));
}
}
writer.AddDocument(doc);
}
catch (System.IO.FileNotFoundException fnfe)
{
throw fnfe;
}
return true;
}
#endregion

#region 在title和content字段中查询数据
///
/// 在title和content字段中查询数据
///

///
///
public List Search(string keyword)
{

string[] fileds = { "title", "content" };//查询字段
//Stopwatch st = new Stopwatch();
//st.Start();
QueryParser parser = null;// new QueryParser(Lucene.Net.Util.Version.LUCENE_30, field, analyzer);//一个字段查询
parser = new MultiFieldQueryParser(version, fileds, analyzer);//多个字段查询
Query query = parser.Parse(keyword);
int n = 1000;
IndexSearcher searcher = new IndexSearcher(directory_luce, true);//true-表示只读
TopDocs docs = searcher.Search(query, (Filter)null, n);
if (docs == null || docs.TotalHits == 0)
{
return null;
}
else
{
List list = new List();
int counter = 1;
foreach (ScoreDoc sd in docs.ScoreDocs)//遍历搜索到的结果
{
try
{
Document doc = searcher.Doc(sd.Doc);
string id = doc.Get("id");
string title = doc.Get("title");
string cOntent= doc.Get("content");
string flag = doc.Get("flag");
string imageurl = doc.Get("imageurl");
string updatetime = doc.Get("updatetime");

string createdate = doc.Get("createdate");
PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter("", "");
PanGu.HighLight.Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new PanGu.Segment());
highlighter.FragmentSize = 50;
cOntent= highlighter.GetBestFragment(keyword, content);
string titlehighlight = highlighter.GetBestFragment(keyword, title);
if (titlehighlight != "") title = titlehighlight;
list.Add(new MySearchUnit(id, title, content, flag, imageurl, updatetime));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
counter++;
}
return list;
}
//st.Stop();
//Response.Write("查询时间:" + st.ElapsedMilliseconds + " 毫秒
");

}
#endregion

#region 在不同的分类下再根据title和content字段中查询数据(分页)
///
/// 在不同的类型下再根据title和content字段中查询数据(分页)
///

/// 分类,传空值查询全部
///
///
///
///
///
public List Search(string _flag, string keyword, int PageIndex, int PageSize, bool Highlight, out int TotalCount)
{
if (PageIndex <1) PageIndex = 1;
//Stopwatch st = new Stopwatch();
//st.Start();
BooleanQuery bq = new BooleanQuery();
if (_flag != "")
{
QueryParser qpflag = new QueryParser(version, "flag", analyzer);
Query qflag = qpflag.Parse(_flag);
bq.Add(qflag, Occur.MUST);//与运算
}
if (keyword != "")
{
string[] fileds = { "title", "content" };//查询字段
QueryParser parser = null;// new QueryParser(version, field, analyzer);//一个字段查询
parser = new MultiFieldQueryParser(version, fileds, analyzer);//多个字段查询
Query queryKeyword = parser.Parse(keyword);
bq.Add(queryKeyword, Occur.MUST);//与运算
}

TopScoreDocCollector collector = TopScoreDocCollector.Create(PageIndex * PageSize, false);
IndexSearcher searcher = new IndexSearcher(directory_luce, true);//true-表示只读
searcher.Search(bq, collector);
if (collector == null || collector.TotalHits == 0)
{
TotalCount = 0;
return null;
}
else
{
int start = PageSize * (PageIndex - 1);
//结束数
int limit = PageSize;
ScoreDoc[] hits = collector.TopDocs(start, limit).ScoreDocs;
List list = new List();
int counter = 1;
TotalCount = collector.TotalHits;
foreach (ScoreDoc sd in hits)//遍历搜索到的结果
{
try
{
Document doc = searcher.Doc(sd.Doc);
string id = doc.Get("id");
string title = doc.Get("title");
string cOntent= doc.Get("content");
string flag = doc.Get("flag");
string imageurl = doc.Get("imageurl");
string updatetime = doc.Get("updatetime");
string font_0 = "";
string font_1 = "";
if (Highlight) { font_0 = ""; font_1 = ""; }
PanGu.HighLight.SimpleHTMLFormatter simpleHTMLFormatter = new PanGu.HighLight.SimpleHTMLFormatter(font_0, font_1);
PanGu.HighLight.Highlighter highlighter = new PanGu.HighLight.Highlighter(simpleHTMLFormatter, new PanGu.Segment());
highlighter.FragmentSize = 50;
cOntent= highlighter.GetBestFragment(keyword, content);
string titlehighlight = highlighter.GetBestFragment(keyword, title);
if (titlehighlight != "") title = titlehighlight;
list.Add(new MySearchUnit(id, title, content, flag, imageurl, updatetime));
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
counter++;
}
return list;
}
//st.Stop();
//Response.Write("查询时间:" + st.ElapsedMilliseconds + " 毫秒
");

}
#endregion

#region 删除索引数据(根据id)
///
/// 删除索引数据(根据id)
///

///
///
public bool Delete(string id)
{
bool IsSuccess = false;
Term term = new Term("id", id);
//Analyzer analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
//Version version = new Version();
//MultiFieldQueryParser parser = new MultiFieldQueryParser(version, new string[] { "name", "job" }, analyzer);//多个字段查询
//Query query = parser.Parse("小王");

//IndexReader reader = IndexReader.Open(directory_luce, false);
//reader.DeleteDocuments(term);
//Response.Write("删除记录结果: " + reader.HasDeletions + "
");
//reader.Dispose();

IndexWriter writer = new IndexWriter(directory_luce, analyzer, false, IndexWriter.MaxFieldLength.LIMITED);
writer.DeleteDocuments(term); // writer.DeleteDocuments(term)或者writer.DeleteDocuments(query);
////writer.DeleteAll();
writer.Commit();
//writer.Optimize();//
IsSuccess = writer.HasDeletions();
writer.Dispose();
return IsSuccess;
}
#endregion

#region 删除全部索引数据
///
/// 删除全部索引数据
///

///
public bool DeleteAll()
{
bool IsSuccess = true;
try
{
IndexWriter writer = new IndexWriter(directory_luce, analyzer, false, IndexWriter.MaxFieldLength.LIMITED);
writer.DeleteAll();
writer.Commit();
//writer.Optimize();//
IsSuccess = writer.HasDeletions();
writer.Dispose();
}
catch
{
IsSuccess = false;
}
return IsSuccess;
}
#endregion

#region directory_luce
private Lucene.Net.Store.Directory _directory_luce = null;
///
/// Lucene.Net的目录-参数
///

public Lucene.Net.Store.Directory directory_luce
{
get
{
if (_directory_luce == null) _directory_luce = Lucene.Net.Store.FSDirectory.Open(directory);
return _directory_luce;
}
}
#endregion

#region directory
private System.IO.DirectoryInfo _directory = null;
///
/// 索引在硬盘上的目录
///

public System.IO.DirectoryInfo directory
{
get
{
if (_directory == null)
{
string dirPath = AppDomain.CurrentDomain.BaseDirectory + "SearchIndex";
if (System.IO.Directory.Exists(dirPath) == false) _directory = System.IO.Directory.CreateDirectory(dirPath);
else _directory = new System.IO.DirectoryInfo(dirPath);
}
return _directory;
}
}
#endregion

#region analyzer
private Analyzer _analyzer = null;
///
/// 分析器
///

public Analyzer analyzer
{
get
{
//if (_analyzer == null)
{
_analyzer = new Lucene.Net.Analysis.PanGu.PanGuAnalyzer();//
//_analyzer = new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_30);
}
return _analyzer;
}
}
#endregion

#region version
private static Lucene.Net.Util.Version _version = Lucene.Net.Util.Version.LUCENE_30;
///
/// 版本号枚举类
///

public Lucene.Net.Util.Version version
{
get
{
return _version;
}
}
#endregion
}

#region 索引的一个行单元,相当于数据库中的一行数据
///
/// 索引的一个行单元,相当于数据库中的一行数据
///

public class MySearchUnit
{
public MySearchUnit(string _id, string _title, string _content, string _flag, string _imageurl, string _updatetime)
{
this.id = _id;
this.title = _title;
this.cOntent= _content;
this.flag = _flag;
this.imageurl = _imageurl;
this.updatetime = _updatetime;
}
///
/// 唯一的id号
///

public string id { get; set; }
///
/// 标题
///

public string title { get; set; }
///
/// 内容
///

public string content { get; set; }
///
/// 其他信息
///

public string flag { get; set; }
///
/// 图片路径
///

public string imageurl { get; set; }
///
/// 时间
///

public string updatetime { get; set; }
}
#endregion
}





推荐阅读
  • XML介绍与使用的概述及标签规则
    本文介绍了XML的基本概念和用途,包括XML的可扩展性和标签的自定义特性。同时还详细解释了XML标签的规则,包括标签的尖括号和合法标识符的组成,标签必须成对出现的原则以及特殊标签的使用方法。通过本文的阅读,读者可以对XML的基本知识有一个全面的了解。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • Go Cobra命令行工具入门教程
    本文介绍了Go语言实现的命令行工具Cobra的基本概念、安装方法和入门实践。Cobra被广泛应用于各种项目中,如Kubernetes、Hugo和Github CLI等。通过使用Cobra,我们可以快速创建命令行工具,适用于写测试脚本和各种服务的Admin CLI。文章还通过一个简单的demo演示了Cobra的使用方法。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • Spring源码解密之默认标签的解析方式分析
    本文分析了Spring源码解密中默认标签的解析方式。通过对命名空间的判断,区分默认命名空间和自定义命名空间,并采用不同的解析方式。其中,bean标签的解析最为复杂和重要。 ... [详细]
  • SpringBoot uri统一权限管理的实现方法及步骤详解
    本文详细介绍了SpringBoot中实现uri统一权限管理的方法,包括表结构定义、自动统计URI并自动删除脏数据、程序启动加载等步骤。通过该方法可以提高系统的安全性,实现对系统任意接口的权限拦截验证。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • Java容器中的compareto方法排序原理解析
    本文从源码解析Java容器中的compareto方法的排序原理,讲解了在使用数组存储数据时的限制以及存储效率的问题。同时提到了Redis的五大数据结构和list、set等知识点,回忆了作者大学时代的Java学习经历。文章以作者做的思维导图作为目录,展示了整个讲解过程。 ... [详细]
  • 本文介绍了使用PHP实现断点续传乱序合并文件的方法和源码。由于网络原因,文件需要分割成多个部分发送,因此无法按顺序接收。文章中提供了merge2.php的源码,通过使用shuffle函数打乱文件读取顺序,实现了乱序合并文件的功能。同时,还介绍了filesize、glob、unlink、fopen等相关函数的使用。阅读本文可以了解如何使用PHP实现断点续传乱序合并文件的具体步骤。 ... [详细]
  • eclipse学习(第三章:ssh中的Hibernate)——11.Hibernate的缓存(2级缓存,get和load)
    本文介绍了eclipse学习中的第三章内容,主要讲解了ssh中的Hibernate的缓存,包括2级缓存和get方法、load方法的区别。文章还涉及了项目实践和相关知识点的讲解。 ... [详细]
  • 有没有一种方法可以在不继承UIAlertController的子类或不涉及UIAlertActions的情况下 ... [详细]
  • CSS3选择器的使用方法详解,提高Web开发效率和精准度
    本文详细介绍了CSS3新增的选择器方法,包括属性选择器的使用。通过CSS3选择器,可以提高Web开发的效率和精准度,使得查找元素更加方便和快捷。同时,本文还对属性选择器的各种用法进行了详细解释,并给出了相应的代码示例。通过学习本文,读者可以更好地掌握CSS3选择器的使用方法,提升自己的Web开发能力。 ... [详细]
  • 树莓派Linux基础(一):查看文件系统的命令行操作
    本文介绍了在树莓派上通过SSH服务使用命令行查看文件系统的操作,包括cd命令用于变更目录、pwd命令用于显示当前目录位置、ls命令用于显示文件和目录列表。详细讲解了这些命令的使用方法和注意事项。 ... [详细]
  • 1,关于死锁的理解死锁,我们可以简单的理解为是两个线程同时使用同一资源,两个线程又得不到相应的资源而造成永无相互等待的情况。 2,模拟死锁背景介绍:我们创建一个朋友 ... [详细]
author-avatar
手机用户2602887045_745
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有