我做了一个简单的站内搜索,但是创建索引后无法搜索到数据,不知道为什么
#region 创建索引
public void createIndex()
{
SqlConnection conn = new SqlConnection("server=localhost;database=news;uid=sa;pwd=intellitrans");
FSDirectory directory;
IndexWriter writer;
string indexPath = Context.Server.MapPath("~/IndexData");
System.IO.Directory.Delete(indexPath, true);
directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NativeFSLockFactory());
writer = new IndexWriter(directory, new PanGuAnalyzer(), true, IndexWriter.MaxFieldLength.UNLIMITED);
try
{
conn.Open();
string sql = "select newsid,title,url,time,newsContent from news";
SqlCommand comm = new SqlCommand(sql, conn);
SqlDataReader dataReader = comm.ExecuteReader();
while (dataReader.Read())
{
Document document = new Document();
document.Add(new Field("newsid", dataReader[0].ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));
document.Add(new Field("title", dataReader[0].ToString(), Field.Store.YES, Field.Index.ANALYZED));
document.Add(new Field("url", dataReader[1].ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
document.Add(new Field("time", dataReader[2].ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED_NO_NORMS));
document.Add(new Field("newsContent", dataReader[3].ToString(), Field.Store.YES, Field.Index.ANALYZED));
writer.AddDocument(document);
}
}
catch (Exception ex)
{
this.Label1.Text = "创建索引失败" + ex.Message;
}
finally
{
conn.Close();
writer.Close();
directory.Close();
}
}
#endregion
#region 搜索
private void SearchIndex()
{
string indexPath = Context.Server.MapPath("~/IndexData");
FSDirectory directory = FSDirectory.Open(new DirectoryInfo(indexPath), new NoLockFactory());
IndexReader reader = IndexReader.Open(directory, true);
IndexSearcher searcher = new IndexSearcher(reader);
// PhraseQuery query = new PhraseQuery();
TermQuery query = null;
BooleanQuery queryOr = new BooleanQuery();
foreach (string word in SplitWords(this.TextBox1.Text))
{
// query.Add(new Term("title", word));
query = new TermQuery(new Term("title", word));
queryOr.Add(query, BooleanClause.Occur.SHOULD);
query = new TermQuery(new Term("newsContent", word));
queryOr.Add(query, BooleanClause.Occur.SHOULD);
//query.Add(new Term("newsContent", word));
}
TopScoreDocCollector collector = TopScoreDocCollector.create(1000, true);
searcher.Search(query, null, collector);
//Hits hit = searcher.Search(query);
ScoreDoc[] docs = collector.TopDocs(0, collector.GetTotalHits()).scoreDocs;
List<News> newResult = new List<News>();
for (int i = 0; i < docs.Length; i++)
{
int docId = docs[i].doc;
Document doc = searcher.Doc(docId);
News news = new News();
news.Title = doc.Get("title");
news.ContentDescription = HightLight(this.TextBox1.Text, doc.Get("newsContent"));
newResult.Add(news);
}
this.rptSearch.DataSource = newResult;
this.rptSearch.DataBind();
}
#endregion