创建索引库
//读取文件,存储到索引库
public string CreateDatebase()
{
//获取索引库的路径
var indexPath = AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["IndexDateBase"];
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
IndexReader reader = IndexReader.Open(directory, true);
var searcher = new IndexSearcher(reader);
//搜索条件
var query = new PhraseQuery();
foreach (string word in GetPanGuAnalyzer(str))//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
{
query.Add(new Term("body", word));
}
//组成词的字之间可以允许的距离
query.SetSlop(5);
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(结束)的文档内容.
var list = new List<string>();
for (int i = 0; i < docs.Length; i++)
{
int docId = docs[i].doc;//得到查询结果文档的id(Lucene内部分配的id)
Document doc = searcher.Doc(docId);//找到文档id对应的文档详细信息
var _str = doc.Get("body");
list.Add(_str);
}
ViewBag.List = list;
return View();
}
进行搜索
public ActionResult List(string str)
{
//获取索引库的路径
var indexPath = AppDomain.CurrentDomain.BaseDirectory + ConfigurationManager.AppSettings["IndexDateBase"];
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
IndexReader reader = IndexReader.Open(directory, true);
var searcher = new IndexSearcher(reader);
//搜索条件
var query = new PhraseQuery();
foreach (string word in GetPanGuAnalyzer(str))//先用空格,让用户去分词,空格分隔的就是词“计算机 专业”
{
query.Add(new Term("body", word));
}
//组成词的字之间可以允许的距离
query.SetSlop(5);
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(结束)的文档内容.
var list = new List<string>();
for (int i = 0; i < docs.Length; i++)
{
int docId = docs[i].doc;//得到查询结果文档的id(Lucene内部分配的id)
Document doc = searcher.Doc(docId);//找到文档id对应的文档详细信息
var _str = doc.Get("body");
list.Add(_str);
}
ViewBag.List = list;
return View();
}
/// 对传递过来的字符串进行盘古分词
/// </summary>
/// <returns></returns>
public static List<string> GetPanGuAnalyzer(string txt)
{
List<string> list = new List<string>();
Analyzer analyzer = new PanGuAnalyzer();
TokenStream tokenStream = analyzer.TokenStream("", new StringReader(txt));
Lucene.Net.Analysis.Token token = null;
while ((token = tokenStream.Next()) != null)
{
list.Add(token.TermText());
}
return list;
}
要添加的文件