我为我添加的每个文档创建了一个包含各种数据位的索引,每个文档的字段名称都不同。
稍后,当我来搜索索引时,我需要使用确切的字段/值来查询它 - 例如:
FieldName1 = X AND FieldName2 = Y AND FieldName3 = Z
使用Lucene .NET构建以下内容的最佳方法是什么:
字段和值来自Dictionary<string, string>
。它不是用户输入,而是由代码构建的。
谢谢,
基隆
答案 0 :(得分:7)
好吧,我最终弄清楚了 - 这是我对它的看法(这可能是完全错误的,但它适用):
public Guid? Find (Dictionary<string, string> searchTerms)
{
if (searchTerms == null)
throw new ArgumentNullException ("searchTerms");
try
{
var directory = FSDirectory.Open (new DirectoryInfo (IndexRoot));
if (!IndexReader.IndexExists (directory))
return null;
var mainQuery = new BooleanQuery ();
foreach (var pair in searchTerms)
{
var parser = new QueryParser (
Lucene.Net.Util.Version.LUCENE_CURRENT, pair.Key, GetAnalyzer ());
var query = parser.Parse (pair.Value);
mainQuery.Add (query, BooleanClause.Occur.MUST);
}
var searcher = new IndexSearcher (directory, true);
try
{
var results = searcher.Search (mainQuery, (Filter)null, 10);
if (results.totalHits != 1)
return null;
return Guid.Parse (searcher.Doc (results.scoreDocs[0].doc).Get (ContentIdKey));
}
catch
{
throw;
}
finally
{
if (searcher != null)
searcher.Close ();
}
}
catch
{
throw;
}
}