BooleanQuery

BooleanQuery 用于组合其他查询。

它们可以使用三个 BooleanClause.Occur 参数组合:

  • BooleanClause.Occur.MUST - 子查询必须匹配。
  • BooleanClause.Occur.SHOULD - 子查询可能不匹配,但如果是,则得分更高。如果没有 MUST 子句,则必须至少匹配一个 SHOULD 子句。
  • BooleanClause.Occur.MUST_NOT - 子查询必须与文档不匹配。

在此示例中,文档将匹配,如果它具有重要,但不是 禁止,并且如果它也具有有用,则将获得更高的分数。

Query importantQuery = new TermQuery(new Term("fieldname", "important"));
Query optionalQuery = new TermQuery(new Term("fieldname", "helpful"));
Query forbidQuery = new TermQuery(new Term("fieldname", "forbidden"));
BooleanQuery query = new BooleanQuery.Builder()
        .add(importantQuery, BooleanClause.Occur.MUST) 
        .add(optionalQuery, BooleanClause.Occur.SHOULD) 
        .add(forbidQuery, BooleanClause.Occur.MUST_NOT) 
        .build();

或者,你也可以指定必须匹配的最小子句数:

Query query1 = new TermQuery(new Term("fieldname", "one"));
Query query2 = new TermQuery(new Term("fieldname", "two"));
Query query3 = new TermQuery(new Term("fieldname", "three"));
BooleanQuery query = new BooleanQuery.Builder()
        .add(query1, BooleanClause.Occur.SHOULD) 
        .add(query2, BooleanClause.Occur.SHOULD) 
        .add(query3, BooleanClause.Occur.SHOULD)
        .setMinimumNumberShouldMatch(2)
        .build();

问:与 BooleanClause.Occur.MUST_NOT 的条款匹配其他所有内容,它们只消除匹配。你的 BooleanQuery 必须至少有一个 MUSTSHOULD 子句,否则它将不匹配。这一点,例如,将工作:

//***This does NOT work!***
Query forbidQuery = new TermQuery(new Term("fieldname", "forbidden"));
BooleanQuery getEverythingElseQuery = new BooleanQuery.Builder()
        .add(forbidQuery, BooleanClause.Occur.MUST_NOT) 
        .build();