Lucene查询 - "匹配x,y,z中的一个"

tha*_*att 5 lucene lucene.net

我有一个Lucene索引,其中包含具有"类型"字段的文档,该字段可以是"文章","论坛"或"博客"三个值中的一个.我希望用户能够在这些类型中进行搜索(每个文档类型都有一个复选框)

如何根据用户选择的类型创建Lucene查询?

一些先决条件是:

  • 如果用户没有选择的类型之一,我想没有该类型的结果.
  • 限制类型字段不应影响结果的排序.

如果我在SQL中写这个(对于"博客或论坛搜索")我会写:

SELECT * FROM Docs
WHERE [type] in ('blog', 'forum')
Run Code Online (Sandbox Code Playgroud)

tha*_*att 5

作为参考,如果其他人也遇到这个问题,这是我的解决方案:

IList<string> ALL_TYPES = new[] { "article", "blog", "forum" };
string q = ...; // The user's search string
IList<string> includeTypes = ...; // List of types to include
Query searchQuery = parser.Parse(q);
Query parentQuery = new BooleanQuery();
parentQuery.Add(searchQuery, BooleanClause.Occur.SHOULD);
// Invert the logic, exclude the other types
foreach (var type in ALL_TYPES.Except(includeTypes))
{
    query.Add(
        new TermQuery(new Term("type", type)),
        BooleanClause.Occur.MUST_NOT
    );
}
searchQuery = parentQuery;
Run Code Online (Sandbox Code Playgroud)

我颠倒了逻辑(即排除用户未选择的类型),因为如果不这样做,结果的顺序就会丢失。我不知道为什么......!这是一种耻辱,因为它使代码不太清晰/可维护,但至少它有效!