Skip to content

Commit

Permalink
LUCENE-8810: Honor MaxClausesCount in BooleanQuery (#787)
Browse files Browse the repository at this point in the history
During Flattening, BooleanQuery will always try to flatten
nested clauses during rewrite. However, this can cause the
maximum number of clauses to be violated by the new query.
This commit disables flattening in the specific case.
  • Loading branch information
atris authored and jpountz committed Jul 15, 2019
1 parent 4c83fbb commit 8739d5e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 12 deletions.
28 changes: 16 additions & 12 deletions lucene/core/src/java/org/apache/lucene/search/BooleanQuery.java
Original file line number Diff line number Diff line change
Expand Up @@ -481,23 +481,27 @@ public Query rewrite(IndexReader reader) throws IOException {
BooleanQuery.Builder builder = new BooleanQuery.Builder();
builder.setMinimumNumberShouldMatch(minimumNumberShouldMatch);
boolean actuallyRewritten = false;
for (BooleanClause clause : clauses) {
if (clause.getOccur() == Occur.SHOULD && clause.getQuery() instanceof BooleanQuery) {
BooleanQuery innerQuery = (BooleanQuery) clause.getQuery();
if (innerQuery.isPureDisjunction()) {
actuallyRewritten = true;
for (BooleanClause innerClause : innerQuery.clauses()) {
builder.add(innerClause);
try {
for (BooleanClause clause : clauses) {
if (clause.getOccur() == Occur.SHOULD && clause.getQuery() instanceof BooleanQuery) {
BooleanQuery innerQuery = (BooleanQuery) clause.getQuery();
if (innerQuery.isPureDisjunction()) {
actuallyRewritten = true;
for (BooleanClause innerClause : innerQuery.clauses()) {
builder.add(innerClause);
}
} else {
builder.add(clause);
}
} else {
builder.add(clause);
}
} else {
builder.add(clause);
}
}
if (actuallyRewritten) {
return builder.build();
if (actuallyRewritten) {
return builder.build();
}
} catch (TooManyClauses exception) {
// No-op : Do not flatten when the new query will violate max clause count
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -598,4 +598,19 @@ public void testDiscardShouldClauses() throws IOException {
w.close();
dir.close();
}

public void testFlattenInnerDisjunctionsWithMoreThan1024Terms() throws IOException {
IndexSearcher searcher = newSearcher(new MultiReader());

BooleanQuery.Builder builder1024 = new BooleanQuery.Builder();
for(int i = 0; i < 1024; i++) {
builder1024.add(new TermQuery(new Term("foo", "bar-" + i)), Occur.SHOULD);
}
Query inner = builder1024.build();
Query query = new BooleanQuery.Builder()
.add(inner, Occur.SHOULD)
.add(new TermQuery(new Term("foo", "baz")), Occur.SHOULD)
.build();
assertSame(query, searcher.rewrite(query));
}
}

0 comments on commit 8739d5e

Please sign in to comment.