optimize boolean queries when possible
This commit is contained in:
parent
4dbc167966
commit
7709c68f63
|
@ -111,6 +111,6 @@ public class BoolJsonQueryParser extends AbstractIndexComponent implements JsonQ
|
|||
if (minimumNumberShouldMatch != -1) {
|
||||
query.setMinimumNumberShouldMatch(minimumNumberShouldMatch);
|
||||
}
|
||||
return fixNegativeQueryIfNeeded(query);
|
||||
return optimizeQuery(fixNegativeQueryIfNeeded(query));
|
||||
}
|
||||
}
|
||||
|
|
|
@ -159,7 +159,7 @@ public class FieldJsonQueryParser extends AbstractIndexComponent implements Json
|
|||
try {
|
||||
Query query = queryParser.parse(queryString);
|
||||
query.setBoost(boost);
|
||||
return fixNegativeQueryIfNeeded(query);
|
||||
return optimizeQuery(fixNegativeQueryIfNeeded(query));
|
||||
} catch (ParseException e) {
|
||||
throw new QueryParsingException(index, "Failed to parse query [" + queryString + "]", e);
|
||||
}
|
||||
|
|
|
@ -156,7 +156,7 @@ public class QueryStringJsonQueryParser extends AbstractIndexComponent implement
|
|||
try {
|
||||
Query query = queryParser.parse(queryString);
|
||||
query.setBoost(boost);
|
||||
return fixNegativeQueryIfNeeded(query);
|
||||
return optimizeQuery(fixNegativeQueryIfNeeded(query));
|
||||
} catch (ParseException e) {
|
||||
throw new QueryParsingException(index, "Failed to parse query [" + queryString + "]", e);
|
||||
}
|
||||
|
|
|
@ -37,6 +37,35 @@ public final class QueryParsers {
|
|||
|
||||
}
|
||||
|
||||
/**
|
||||
* Optimizes the given query and returns the optimized version of it.
|
||||
*/
|
||||
public static Query optimizeQuery(Query q) {
|
||||
if (q instanceof BooleanQuery) {
|
||||
return optimizeBooleanQuery((BooleanQuery) q);
|
||||
}
|
||||
return q;
|
||||
}
|
||||
|
||||
public static BooleanQuery optimizeBooleanQuery(BooleanQuery q) {
|
||||
BooleanQuery optimized = new BooleanQuery(q.isCoordDisabled());
|
||||
optimized.setMinimumNumberShouldMatch(q.getMinimumNumberShouldMatch());
|
||||
optimizeBooleanQuery(optimized, q);
|
||||
return optimized;
|
||||
}
|
||||
|
||||
public static void optimizeBooleanQuery(BooleanQuery optimized, BooleanQuery q) {
|
||||
for (BooleanClause clause : q.clauses()) {
|
||||
Query cq = clause.getQuery();
|
||||
cq.setBoost(cq.getBoost() * q.getBoost());
|
||||
if (cq instanceof BooleanQuery && !clause.isRequired() && !clause.isProhibited()) {
|
||||
optimizeBooleanQuery(optimized, (BooleanQuery) cq);
|
||||
} else {
|
||||
optimized.add(clause);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isNegativeQuery(Query q) {
|
||||
if (!(q instanceof BooleanQuery)) {
|
||||
return false;
|
||||
|
|
Loading…
Reference in New Issue