Lucene.net多字段搜索

时间:2011-02-24 00:07:21

标签: asp.net c#-4.0 lucene.net

为了获得更多与上下文相关的搜索结果,我决定与lucene.net合作,虽然我对它很新,但我发现它不是我最直观的库碰到了。由于缺乏相关的例子来帮助我解决这个问题,这并没有帮助。

我正在使用simple lucene来构建我的索引,这似乎完美无缺:

Field f = null;
Document document = new Document();

document.Add(new Field("id", dl.Id.ToString(), Field.Store.YES, Field.Index.NOT_ANALYZED));

f = new Field("category", dl.CategoryName.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
f.SetBoost(5);
document.Add(f);

f = new Field("company_name", dl.CompanyName.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS);
f.SetBoost(2);
document.Add(f);

document.Add(new Field("description", dl.Description.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
document.Add(new Field("meta_keywords", dl.Meta_Keywords.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));
document.Add(new Field("meta_description", dl.Meta_Description.ToLowerInvariant(), Field.Store.YES, Field.Index.ANALYZED, Field.TermVector.WITH_POSITIONS_OFFSETS));

//And a few more fields

基于这个索引,我首先尝试了以下几行的查询:

var whatParser = new MultiFieldQueryParser(
    global::Lucene.Net.Util.Version.LUCENE_29,
    new string[] { "company_name", "description", "meta_keywords", "meta_description", "category" },
    analyzer);

whatQuery = whatParser.Parse("search".ToLowerInvariant());

在搜索词超过1个单词之前,这很有效。接下来是短语查询。

whatQuery = new PhraseQuery();
whatQuery.Add(new Term("company_name", what));
whatQuery.Add(new Term("description", what));
whatQuery.Add(new Term("meta_keywords", what));
whatQuery.Add(new Term("meta_description", what));
whatQuery.Add(new Term("category", what));

然后我发现了错误:All phrase terms must be in the same field

那么,我哪里错了?你对如何解决它有什么建议吗?如果有更好的建议,我愿意完全改变搜索技术。

一些可能有用的其他信息

  • 所有结果最后都是通过new Sort(new SortField[] {new SortField("is_featured", SortField.STRING, true),SortField.FIELD_SCORE})
  • 排序的
  • 还有一些额外的搜索条件,因此每个查询都会添加到布尔查询中,并且设置为SHOULD

感谢您的帮助。

1 个答案:

答案 0 :(得分:3)

我认为BooleanClause.Occur.SHOULD是个问题。我们这样使用它:

string[] fieldList = { "field1", "field2", "field3"; 

//for us the field list varies .. there are other ways to create this array of course
List<BooleanClause.Occur> occurs = new List<BooleanClause.Occur>();
foreach (string field in fieldList)
    occurs.Add(BooleanClause.Occur.SHOULD);

if(!string.IsNullOrEmpty(multiWordPhrase))
{
    Query q = MultiFieldQueryParser.Parse(multiWordPhrase, fieldList, occurs.ToArray(), new StandardAnalyzer());
    return q;
}