我正在使用Lucene开发一个Windows应用程序。我想获取所有已索引的关键词,并将它们用作搜索字段自动建议的来源。如何在Lucene中收集所有已索引的关键词?我在C#方面还很新手,如果有代码示例就更好了。谢谢。
您是否想从索引中提取所有术语?
private void GetIndexTerms(string indexFolder)
{
List<String> termlist = new ArrayList<String>();
IndexReader reader = IndexReader.open(indexFolder);
TermEnum terms = reader.terms();
while (terms.next())
{
Term term = terms.term();
String termText = term.text();
int frequency = reader.docFreq(term);
termlist.add(termText);
}
reader.close();
}
如果需要关于Apache Lucene.Net版本4.8方面的灵感,你可以参考GitHubmsigut/LuceneNet48Demo。使用以下类: SearcherManager、*QueryParser和IndexWriter 来构建索引。
// you favorite Query parser (MultiFieldQueryParser for example)
_queryParser = new MultiFieldQueryParser(...
// Execute the search with a fresh indexSearcher
_searchManager.MaybeRefreshBlocking();
var searcher = _searchManager.Acquire();
try
{
var q = _queryParser.Parse(query);
var topDocs = searcher.Search(q, 10);
foreach (var scoreDoc in topDocs.ScoreDocs)
{
var document = searcher.Doc(scoreDoc.Doc);
var hit = new QueryHit
{
Title = document.GetField("title")?.GetStringValue(),
// ... you logic to read data from index ...
};
}
}
finally
{
_searchManager.Release(searcher);
searcher = null;
}