初识Lucene.net
最近想提高下自己的能力,也是由于自己的项目中需要用到Lucene,所以开始接触这门富有挑战又充满新奇的技术。。
刚刚开始,只是写了个小小的demo,用了用lucene,确实很好
创建索引
DataTable dt = DB.SqlHelper.ExecuteDataset(connectionString, CommandType.Text, "select top 1000 id,title,productsummary from dbo.products").Tables[0];
Lucene.Net.Store.FSDirectory fs = Lucene.Net.Store.FSDirectory.GetDirectory(basePath);
if (Lucene.Net.Index.IndexReader.IsLocked(fs))
Lucene.Net.Index.IndexReader.Unlock(fs);
Lucene.Net.Index.IndexWriter iw = new Lucene.Net.Index.IndexWriter(basePath, new Lucene.Net.Analysis.Standard.StandardAnalyzer());
foreach (DataRow dr in dt.Rows)
{
Lucene.Net.Documents.Document doc = new Lucene.Net.Documents.Document();
doc.Add(new Lucene.Net.Documents.Field("id", dr["id"].ToString(), Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.NO));
doc.Add(new Lucene.Net.Documents.Field("title", dr["title"].ToString(), Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
doc.Add(new Lucene.Net.Documents.Field("productsummary", dr["productsummary"].ToString(), Lucene.Net.Documents.Field.Store.YES, Lucene.Net.Documents.Field.Index.ANALYZED));
iw.AddDocument(doc);
}
iw.Optimize();
iw.Close();
搜索结果
System.Text.StringBuilder sb = new System.Text.StringBuilder();
Lucene.Net.Store.FSDirectory dir = Lucene.Net.Store.FSDirectory.GetDirectory(basePath);
Lucene.Net.Analysis.PanGu.PanGuAnalyzer pgAnalyzer = new Lucene.Net.Analysis.PanGu.PanGuAnalyzer();
Lucene.Net.Search.IndexSearcher search = new Lucene.Net.Search.IndexSearcher(dir);
Lucene.Net.QueryParsers.QueryParser qp = new Lucene.Net.QueryParsers.QueryParser("title", pgAnalyzer);
Lucene.Net.Search.Query query = qp.Parse(this.txtKeywords.Text);
//第一种结果,使用Hits集合
Lucene.Net.Search.Hits hits = search.Search(query);
for (int i = 0; i < hits.Length(); i++)
{
Lucene.Net.Documents.Document doc = hits.Doc(i);
sb.Append(doc.GetField("title").StringValue()+"<br />");
}
//第二种结果,使用TopDocs(最精确的结果)
Lucene.Net.Search.TopDocs topDocs = search.Search(query, 100);//100为返回的结果数目,必须是大于0的数字,分页的时候会用到
Lucene.Net.Search.ScoreDoc[] result = topDocs.scoreDocs;
for (int i = 0; i < result.Length; i++)
{
Lucene.Net.Documents.Document doc = search.Doc(result[i].doc);
sb.Append((i+1).ToString() + "\t" + highter.GetBestFragment(this.txtKeywords.Text, doc.Get("title")) + "<br />");
}
Lucene.Net.Search.ScoreDoc[] result = topDocs.scoreDocs;
for (int i = 0; i < result.Length; i++)
{
Lucene.Net.Documents.Document doc = search.Doc(result[i].doc);
sb.Append((i+1).ToString() + "\t" + highter.GetBestFragment(this.txtKeywords.Text, doc.Get("title")) + "<br />");
}
Response.Write(sb.ToString());
dir.Close();
结果