我一直在尝试让Lucene .NET在我的API中工作,但是它总是返回0个结果。我在这里写的所有东西都封装在一个Singleton服务中,我的API控制器使用它。
如何创建索引:
public async Task<bool> CreateSearchArtefacts()
{
var analyzer = new StandardAnalyzer(AppLuceneVersion);
var indexConfig = new IndexWriterConfig(AppLuceneVersion, analyzer);
using (var dir = FSDirectory.Open(IndexPath))
{
using (IndexWriter writer = new IndexWriter(dir, indexConfig))
{
foreach (var element in this.data)
{
Document doc = new Document
{
new TextField("Title", element.Title, Field.Store.YES),
new StringField("Author", element.Author, Field.Store.YES),
new TextField("Description", element.Description, Field.Store.NO)
};
writer.AddDocument(doc);
this.logger.LogInformation(element.Title + " added.");
}
this.logger.LogInformation("All Books added.");
writer.Commit();
};
};
return true;
}
这就是我如何搜索它:
public async Task<SearchResultsCollection> SearchSingleTerms(string term, string search, int count)
{
this.logger.LogInformation("Searching Term "+ term + " for " + search);
var phrase = new TermQuery(new Term(term, search));
var analyzer = new StandardAnalyzer(AppLuceneVersion);
var indexConfig = new IndexWriterConfig(AppLuceneVersion, analyzer);
var sendList = new List<SearchResult>();
using (var dir = FSDirectory.Open(IndexPath))
{
using (var writer = new IndexWriter(dir, indexConfig))
{
var reader = writer.GetReader(true);
var searcher = new IndexSearcher(reader);
var hits = searcher.Search(phrase, count /* top 20 */).ScoreDocs;
this.logger.LogInformation("Results found: " + hits.Length);
foreach (var item in hits)
{
var foundDoc = searcher.Doc(item.Doc);
sendList.Add(new SearchResult()
{
Author = foundDoc.Get("Author"),
Title = foundDoc.Get("Title"),
Description = foundDoc.Get("Description")
});
}
writer.Flush(triggerMerge: false, applyAllDeletes: false);
};
};
return new SearchResultsCollection() { Count = count, Results = sendList.ToArray() };
}
我使用的是Lucene.Net 4.8.0-beta 00014和.NET核心3.1
任何帮助都是感激不尽的!
1条答案
按热度按时间ykejflvf1#
找到了。我必须将短语的字符串参数转换为字符串值。