使用NuGet的NET6.0和Lucene.NET-4.8.0-beta00016
我在实现网站上的快速入门示例时遇到了问题。在文档中使用TextField时,该字段没有被索引。稍后在BuildIndex方法中的搜索不会检索到任何结果。如果TextField更改为StringField,则该示例有效,并且搜索返回有效结果。
为什么StringField工作而TextField不工作?我读到StringField没有被分析,但TextField是,所以也许这与标准分析器有关?
public class LuceneFullTextSearchService {
private readonly IndexWriter _writer;
private readonly Analyzer _standardAnalyzer;
public LuceneFullTextSearchService(string indexName)
{
// Compatibility version
const LuceneVersion luceneVersion = LuceneVersion.LUCENE_48;
string indexPath = Path.Combine(Environment.CurrentDirectory, indexName);
Directory indexDir = FSDirectory.Open(indexPath);
// Create an analyzer to process the text
_standardAnalyzer = new StandardAnalyzer(luceneVersion);
// Create an index writer
IndexWriterConfig indexConfig = new IndexWriterConfig(luceneVersion, _standardAnalyzer)
{
OpenMode = OpenMode.CREATE_OR_APPEND,
};
_writer = new IndexWriter(indexDir, indexConfig);
}
public void BuildIndex(string searchPath)
{
Document doc = new Document();
TextField docText = new TextField("title", "Apache", Field.Store.YES);
doc.Add(docText);
_writer.AddDocument(doc);
//Flush and commit the index data to the directory
_writer.Commit();
// Parse the user's query text
Query query = new TermQuery(new Term("title", "Apache"));
// Search
using DirectoryReader reader = _writer.GetReader(applyAllDeletes: true);
IndexSearcher searcher = new IndexSearcher(reader);
TopDocs topDocs = searcher.Search(query, n: 2);
// Show results
Document resultDoc = searcher.Doc(topDocs.ScoreDocs[0].Doc);
string title = resultDoc.Get("title");
}
}
Standard ardAnalyzer
包含一个LowerCaseFilter
,因此您的文本以小写形式存储在索引中。
但是,当您构建查询时,您使用的文本是“Apache”而不是“apache”,因此它不会产生任何命中。
// Parse the user's query text
Query query = new TermQuery(new Term("title", "Apache"));
小写您的搜索词。
// Parse the user's query text
Query query = new TermQuery(new Term("title", "Apache".ToLowerInvariant()));
将QueryParser
与用于构建索引的相同分析器一起使用。
QueryParser parser = new QueryParser(luceneVersion, "title", _standardAnalyzer);
Query query = parser.Parse("Apache");
Lucene.Net。QueryParser
包包含几个实现(上面的示例使用了Lucene.Net。QueryParser. Classic.QueryParser
)。