将 Term 添加到 MultiPhraseQuery 发现进行的是完全匹配搜索,比如下面的 C# 代码
var phrase = new MultiPhraseQuery
{
new Term("title", word)
};
using var reader = writer.GetReader(applyAllDeletes: true);
var searcher = new IndexSearcher(reader);
var hits = searcher.Search(phrase, 20).ScoreDocs;
lucenet.net 版本是 4.8.0-beta00016
需要使用 QueryParser
var queryParser = new QueryParser(LuceneVersion.LUCENE_48, "title", analyzer);
var query = queryParser.Parse(word);
另外需要注意的是,创建 Document 时要使用 TextField
,不能使用 StringField
var doc = new Document
{
new TextField(nameof(source.Title).ToLower(), source.Title, Field.Store.YES)
};
完整代码
const LuceneVersion appLuceneVersion = LuceneVersion.LUCENE_48;
using var dir = FSDirectory.Open("./index");
var analyzer = new StandardAnalyzer(appLuceneVersion);
var indexConfig = new IndexWriterConfig(appLuceneVersion, analyzer);
using var writer = new IndexWriter(dir, indexConfig);
var source = new
{
Title = "Understanding PathBase in ASP.NET Core"
};
var doc = new Document
{
new TextField(nameof(source.Title), source.Title, Field.Store.YES)
};
writer.AddDocument(doc);
writer.Flush(triggerMerge: false, applyAllDeletes: false);
var queryParser = new QueryParser(appLuceneVersion, nameof(source.Title), analyzer);
var word = "ASP.NET Core";
var query = queryParser.Parse(word);
using var reader = writer.GetReader(applyAllDeletes: true);
var searcher = new IndexSearcher(reader);
var hits = searcher.Search(query, 10).ScoreDocs;
foreach (var hit in hits)
{
var foundDoc = searcher.Doc(hit.Doc);
Console.WriteLine($"{hit.Score:f8} {foundDoc.Get(nameof(source.Title))}");
}
writer.DeleteAll();