lucene.net mysql_使用Lucene.net+盘古分词实现搜索查询

usingLucene.Net.Documents;usingLucene.Net.Index;usingLucene.Net.Analysis;usingSystem.Collections.Generic;usingSystem.IO;usingLucene.Net.Search;usingSystem;usingLucene.Net.Store;usingLucene.Net.QueryParsers;usingLuceneNetTest.Models;usingLuceneNetTest.Helpers;usingMongoDB.Bson;namespaceLuceneNetTest

{///

///信息///

public classPanGuLuceneHelper

{public static Analyzer analyzer = new PanGuAnalyzer();//指定使用盘古 PanGuAnalyzer 分词算法

///

///初始化盘古分词的xml引用路径///

///

public static void InitPanGuXmlPath(stringPanGuXmlPath)

{//定义盘古分词的xml引用路径

PanGu.Segment.Init(PanGuXmlPath);

}///

///建立索引///

/// 目录地址

/// 是否从新建立

public static Result CreateIndex(string IndexDic,List list = null)

{

IndexWriter writer;var result = newResult();try{//建立索引目录

FSDirectory directory = FSDirectory.Open(new DirectoryInfo(IndexDic), newNativeFSLockFactory());//IndexReader:对索引库进行读取的类//是否存在索引库文件夹以及索引库特征文件//若是索引目录被锁定(好比索引过程当中程序异常退出或另外一进程在操做索引库),则解锁

if(IndexWriter.IsLocked(directory))

{

IndexWriter.Unlock(directory);

}//IndexWriter第三个参数:true指从新建立索引,false指从当前索引追加....此处为新建索引因此为true

writer = newIndexWriter(directory, analyzer, Lucene.Net.Index.IndexWriter.MaxFieldLength.LIMITED);

AddIndex(writer, list);

writer.Optimize();

writer.Dispose();

result= newResult()

{

Success= true};

}catch(Exception ex)

{

result= newResult()

{

Success= false,

Message=ex.Message

};

}returnresult;

}///

///建立索引///

///

///

///

private static void AddIndex(IndexWriter writer, List list = null)

{try{//for (int i = 0; i < 10; i++)//{//Document doc = new Document();//doc.Add(new Field("Name", "大贲科技" + i, Field.Store.YES, Field.Index.ANALYZED));//存储且索引//writer.AddDocument(doc);//}

MongoDbHelper mg = new MongoDbHelper();var customerList =mg.QueryToLucene();if (list != null)

{

customerList=list;

}foreach (var item incustomerList)

{

Document doc= newDocument();

doc.Add(new Field("Name", item.Name == null ? "" : item.Name, Field.Store.YES, Field.Index.ANALYZED));//存储且索引

doc.Add(new Field("TaxCode", item.Code == null ? "" : item.Code, Field.Store.YES, Field.Index.ANALYZED));//存储且索引

doc.Add(new Field("AddressPhone", item.AddressPhone == null ? "" : item.AddressPhone, Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("BankAccount", item.BankAccount == null ? "" : item.BankAccount, Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("State", item.State, Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("Id", item.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("CreateTime", item.CreateTime.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("UpdateTime", item.UpdateTime.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

if (item.State == "n")//修改

{

Term t= new Term("Id", item.Id.ToString());

writer.DeleteDocuments(t);

writer.AddDocument(doc);

}else if (item.State == "y")//新增

{

writer.AddDocument(doc);

}//修改mongodb状态为ok,下次就不操做到索引了。

mg.Modify(item.Id.ToString(), "State", "ok");

}

}catch(FileNotFoundException fnfe)

{throwfnfe;

}catch(Exception ex)

{throwex;

}

}///

///建立索引///

///

///

///

private static voidAddIndexNew(IndexWriter writer)

{try{

MongoDbHelper mg = new MongoDbHelper();var customerList =mg.QueryToLucene();foreach (var item incustomerList)

{

Document doc= newDocument();

doc.Add(new Field("Name", item.Name == null ? "" : item.Name, Field.Store.YES, Field.Index.ANALYZED));//存储且索引

doc.Add(new Field("TaxCode", item.Code == null ? "" : item.Code, Field.Store.YES, Field.Index.ANALYZED));//存储且索引

doc.Add(new Field("AddressPhone", item.AddressPhone == null ? "" : item.AddressPhone, Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("BankAccount", item.BankAccount == null ? "" : item.BankAccount, Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("State", item.State, Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("Id", item.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("CreateTime", item.CreateTime.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

doc.Add(new Field("UpdateTime", item.UpdateTime.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));//存储且索引

if (item.State == "n")//修改

{

Term t= new Term("Id", item.Id.ToString());

writer.DeleteDocuments(t);

writer.AddDocument(doc);

}else if (item.State == "y")//新增

{

writer.AddDocument(doc);

}//修改mongodb状态为ok,下次就不操做到索引了。

mg.Modify(item.Id.ToString(), "State", "ok");

}

}catch(FileNotFoundException fnfe)

{throwfnfe;

}catch(Exception ex)

{throwex;

}

}///

///分词方法///

/// 待分词内容

///

///

private static string cutWords(stringwords, Analyzer analyzer)

{string resultStr = "";

System.IO.StringReader reader= newSystem.IO.StringReader(words);

Lucene.Net.Analysis.TokenStream ts=analyzer.TokenStream(words, reader);bool hasNext =ts.IncrementToken();

Lucene.Net.Analysis.Tokenattributes.ITermAttribute ita;while(hasNext)

{

ita= ts.GetAttribute();

resultStr+= ita.Term + "|";

hasNext=ts.IncrementToken();

}

ts.CloneAttributes();

reader.Close();

analyzer.Close();returnresultStr;

}///

///从索引搜索结果///

public static List SearchIndex(string content, stringIndexDic)

{try{var str =cutWords(content, analyzer);

FSDirectory directory= FSDirectory.Open(new DirectoryInfo(IndexDic), newNoLockFactory());

IndexReader reader= IndexReader.Open(directory, true);

IndexSearcher search= new IndexSearcher(directory, true);//建立查询

PerFieldAnalyzerWrapper wrapper = newPerFieldAnalyzerWrapper(analyzer);

wrapper.AddAnalyzer("Name", analyzer);

QueryParser parser= new QueryParser(Lucene.Net.Util.Version.LUCENE_30, "Name", wrapper);

Query query=parser.Parse(content);

TopScoreDocCollector collector= TopScoreDocCollector.Create(4, true);//10--默认查询4条数

BooleanQuery bQuery= newBooleanQuery();

bQuery.Add(query,newOccur());

search.Search(bQuery, collector);var hits =collector.TopDocs().ScoreDocs;int numTotalHits =collector.TotalHits;

List list = new List();for (int i = 0; i < hits.Length; i++)

{var hit =hits[i];

Document doc=search.Doc(hit.Doc);var model = newLuceneTestData()

{

Name= doc.Get("Name").ToString(),

Code= doc.Get("TaxCode").ToString(),

AddressPhone= doc.Get("AddressPhone").ToString(),

BankAccount= doc.Get("BankAccount").ToString(),

State= doc.Get("State").ToString(),

Id= ObjectId.Parse(doc.Get("Id")),

CreateTime= doc.Get("CreateTime").ToString(),

UpdateTime= doc.Get("UpdateTime").ToString()

};

list.Add(model);

}returnlist;

}catch(Exception ex)

{throwex;

}

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1、 修改字典格式,提高字典加载速度 2、 增加对英文专业名词的支持 如C++,C#等只要加入字典就可以被分出来 3、 增加词频判断功能,在无法取舍时根据词频取舍 4、 增加优先优先词频选项,通过这个选项动态决定分词粒度 需打开 FreqFirst 5、 增加中文人名前后缀统计和根据该统计定位人名的功能 6、 增加中文人名和未登录词出现频率统计功能 7、 增加自动更新字典功能,对超过阈值的人名和未登录词自动插入字典 需打开 AutoInsertUnknownWords 开关 并设置 UnknownWordsThreshold,(不推荐自动插入,推荐手工插入) 8、 增加定期保存字典和统计结果功能 需设置 AutoSaveInterval 9、 增加KTDictSeg.xml配置文件来配置分词参数 10、增加对Lucene.net 的支持,提供 KTDictSegAnalyzer 分析器给Lucene.net 11、增加字典管理功能,可以添加删除修改字典 12、字典管理中提供从未登录词中批量插入字典功能,可帮助使用者手工选择合适的未登录词插入字典(推荐) 13、提供一个新闻搜索的简单例子,采用Lucene.net+KTDictSegAnalyzer+KTDictSeg,项目名为Demo.KTDictSegAnalyzer 14、将所有ArrayList 改为List 其中 src_V1.3.01是源码 rel_V1.3.01 包含所有的可执行文件,配置文件;Data目录下是词库,停用词表,以及我目前统计的人名前后缀词表;News 目录下是Lucene.net为 新闻搜索的例子建的索引。 News.zip 是上图中批量插入时要输入的XML文件,它包含3万条从新浪和中华网抓下来的过时的新闻,大约2000万字左右,可供各位朋友学习使用。 注意:如果要导入news.xml,这个文件必须要和Demo.KTDictSegAnalyzer.exe放在同一个目录下!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值