我正在将Lucene.Net版本4.8.0与.NET Core 3.1一起使用。在下面的示例代码中,我编写了一个新索引并向其中添加了三个文档。每个文档都包含字段ProjectName
,Customer
和Country
。
当我解析查询"Germany"
时,对于在其任何字段中包含单词“ Germany”的文档,搜索将返回2次匹配。但是,当我解析查询"Country:Germany"
时,搜索会返回0次命中,尽管显然在Country
字段中有一个值为“德国”的文档。
我在做什么错?
我还通过Luke工具(https://github.com/DmitryKey/luke/releases/tag/4.8.0)检查了索引。使用Luke,对于相同的索引目录,搜索可以正常进行。
我的C#代码在这里:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.QueryParsers.Classic;
using Lucene.Net.Search;
using Lucene.Net.Store;
using Lucene.Net.Util;
using Directory = System.IO.Directory;
namespace LuceneTestApp
{
class Program
{
static string CreateTestIndex()
{
string indexDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
if(Directory.Exists(indexDir))
throw new IOException("Random index directory already exists. Please try again.");
using var dir = FSDirectory.Open(indexDir);
using var analyzer = new StandardAnalyzer(LuceneVersion.LUCENE_48);
var indexConfig = new IndexWriterConfig(LuceneVersion.LUCENE_48, analyzer);
using var writer = new IndexWriter(dir, indexConfig);
AddDocumentTo(writer, "AwesomeProject_1", "Volkswagen", "Germany");
AddDocumentTo(writer, "AwesomeProject_2", "Ford", "USA");
AddDocumentTo(writer, "AwesomeProject_3", "Audi Germany", "France");
writer.Commit();
return indexDir;
}
static void AddDocumentTo(IndexWriter writer, string projectName, string customer, string country)
{
var doc = new Document();
doc.Add(new StringField( "ProjectName", projectName, Field.Store.YES));
doc.Add(new TextField( "Customer", customer, Field.Store.YES));
doc.Add(new TextField( "Country", country, Field.Store.YES));
writer.AddDocument(doc);
}
static IList<string> Search(string indexDir, string queryString)
{
using var dir = FSDirectory.Open(indexDir);
using var reader = DirectoryReader.Open(dir);
using var analyzer = new StandardAnalyzer(LuceneVersion.LUCENE_48);
var searcher = new IndexSearcher(reader);
string[] searchFields = {"ProjectName", "Customer", "Country"};
var queryParser = new MultiFieldQueryParser(LuceneVersion.LUCENE_48, searchFields, analyzer);
queryParser.DefaultOperator = Operator.AND;
var query = queryParser.Parse(queryString.ToLowerInvariant());
int maxNumHits = 10;
var topDocs = searcher.Search(query, maxNumHits);
return topDocs.ScoreDocs.Select(hit => $"Score {hit.Score,5:0.000} DocId {hit.Doc}").ToList();
}
static void Main(string[] args)
{
Console.WriteLine("=================");
string indexDir = CreateTestIndex();
IList<string> hitsOne = Search(indexDir, "Germany");
IList<string> hitsTwo = Search(indexDir, "Country:Germany");
Console.WriteLine($"Search one yields {hitsOne.Count} hits.");
Console.WriteLine($"Search two yields {hitsTwo.Count} hits.");
Console.WriteLine("=================\n\n");
}
}
}
ToLowerInvariant()
的呼叫。