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 必須至少有一個 MUST
或 SHOULD
子句,否則它將不匹配。這一點,例如,將不工作:
//***This does NOT work!***
Query forbidQuery = new TermQuery(new Term("fieldname", "forbidden"));
BooleanQuery getEverythingElseQuery = new BooleanQuery.Builder()
.add(forbidQuery, BooleanClause.Occur.MUST_NOT)
.build();