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;

}

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值