Remove support for empty queries (#22092)

Our query DSL supports empty queries (`{}`), which have a different meaning depending on the query that holds it, either ignored, match_all or match_none. We deprecated the support for empty queries in 5.0, where we log a deprecation warning wherever they are used.

The way we supported it once we moved query parsing to the coordinating node was having an Optional<QueryBuilder> return type in all of our parse methods (called fromXContent). See #17624. The central place for this was QueryParseContext#parseInnerQueryBuilder. We can now remove all the optional return types and simply throw an exception whenever an empty query is found.
This commit is contained in:
Luca Cavanna 2016-12-12 12:37:12 +01:00 committed by GitHub
parent 9be778c5e5
commit 6d987a9b69
77 changed files with 215 additions and 593 deletions

View File

@ -33,7 +33,6 @@ import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.indices.InvalidAliasNameException; import org.elasticsearch.indices.InvalidAliasNameException;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
/** /**
@ -139,10 +138,8 @@ public class AliasValidator extends AbstractComponent {
private static void validateAliasFilter(XContentParser parser, QueryShardContext queryShardContext) throws IOException { private static void validateAliasFilter(XContentParser parser, QueryShardContext queryShardContext) throws IOException {
QueryParseContext queryParseContext = queryShardContext.newParseContext(parser); QueryParseContext queryParseContext = queryShardContext.newParseContext(parser);
Optional<QueryBuilder> parseInnerQueryBuilder = queryParseContext.parseInnerQueryBuilder(); QueryBuilder parseInnerQueryBuilder = queryParseContext.parseInnerQueryBuilder();
if (parseInnerQueryBuilder.isPresent()) { QueryBuilder queryBuilder = QueryBuilder.rewriteQuery(parseInnerQueryBuilder, queryShardContext);
QueryBuilder queryBuilder = QueryBuilder.rewriteQuery(parseInnerQueryBuilder.get(), queryShardContext);
queryBuilder.toFilter(queryShardContext); queryBuilder.toFilter(queryShardContext);
} }
}
} }

View File

@ -37,7 +37,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer; import java.util.function.Consumer;
import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded; import static org.elasticsearch.common.lucene.search.Queries.fixNegativeQueryIfNeeded;
@ -299,7 +298,7 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
builder.endArray(); builder.endArray();
} }
public static Optional<BoolQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException, ParsingException { public static BoolQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
boolean disableCoord = BoolQueryBuilder.DISABLE_COORD_DEFAULT; boolean disableCoord = BoolQueryBuilder.DISABLE_COORD_DEFAULT;
@ -323,17 +322,17 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
switch (currentFieldName) { switch (currentFieldName) {
case MUST: case MUST:
parseContext.parseInnerQueryBuilder().ifPresent(mustClauses::add); mustClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
case SHOULD: case SHOULD:
parseContext.parseInnerQueryBuilder().ifPresent(shouldClauses::add); shouldClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
case FILTER: case FILTER:
parseContext.parseInnerQueryBuilder().ifPresent(filterClauses::add); filterClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
case MUST_NOT: case MUST_NOT:
case MUSTNOT: case MUSTNOT:
parseContext.parseInnerQueryBuilder().ifPresent(mustNotClauses::add); mustNotClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
default: default:
throw new ParsingException(parser.getTokenLocation(), "[bool] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[bool] query does not support [" + currentFieldName + "]");
@ -342,17 +341,17 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
switch (currentFieldName) { switch (currentFieldName) {
case MUST: case MUST:
parseContext.parseInnerQueryBuilder().ifPresent(mustClauses::add); mustClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
case SHOULD: case SHOULD:
parseContext.parseInnerQueryBuilder().ifPresent(shouldClauses::add); shouldClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
case FILTER: case FILTER:
parseContext.parseInnerQueryBuilder().ifPresent(filterClauses::add); filterClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
case MUST_NOT: case MUST_NOT:
case MUSTNOT: case MUSTNOT:
parseContext.parseInnerQueryBuilder().ifPresent(mustNotClauses::add); mustNotClauses.add(parseContext.parseInnerQueryBuilder());
break; break;
default: default:
throw new ParsingException(parser.getTokenLocation(), "bool query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "bool query does not support [" + currentFieldName + "]");
@ -394,7 +393,7 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
boolQuery.adjustPureNegative(adjustPureNegative); boolQuery.adjustPureNegative(adjustPureNegative);
boolQuery.minimumNumberShouldMatch(minimumShouldMatch); boolQuery.minimumNumberShouldMatch(minimumShouldMatch);
boolQuery.queryName(queryName); boolQuery.queryName(queryName);
return Optional.of(boolQuery); return boolQuery;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* The BoostingQuery class can be used to effectively demote results that match a given query. * The BoostingQuery class can be used to effectively demote results that match a given query.
@ -137,12 +136,12 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
builder.endObject(); builder.endObject();
} }
public static Optional<BoostingQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static BoostingQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Optional<QueryBuilder> positiveQuery = null; QueryBuilder positiveQuery = null;
boolean positiveQueryFound = false; boolean positiveQueryFound = false;
Optional<QueryBuilder> negativeQuery = null; QueryBuilder negativeQuery = null;
boolean negativeQueryFound = false; boolean negativeQueryFound = false;
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
float negativeBoost = -1; float negativeBoost = -1;
@ -186,15 +185,12 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),
"[boosting] query requires 'negative_boost' to be set to be a positive value'"); "[boosting] query requires 'negative_boost' to be set to be a positive value'");
} }
if (positiveQuery.isPresent() == false || negativeQuery.isPresent() == false) {
return Optional.empty();
}
BoostingQueryBuilder boostingQuery = new BoostingQueryBuilder(positiveQuery.get(), negativeQuery.get()); BoostingQueryBuilder boostingQuery = new BoostingQueryBuilder(positiveQuery, negativeQuery);
boostingQuery.negativeBoost(negativeBoost); boostingQuery.negativeBoost(negativeBoost);
boostingQuery.boost(boost); boostingQuery.boost(boost);
boostingQuery.queryName(queryName); boostingQuery.queryName(queryName);
return Optional.of(boostingQuery); return boostingQuery;
} }
@Override @Override

View File

@ -40,7 +40,6 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* CommonTermsQuery query is a query that executes high-frequency terms in a * CommonTermsQuery query is a query that executes high-frequency terms in a
@ -263,7 +262,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
builder.endObject(); builder.endObject();
} }
public static Optional<CommonTermsQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static CommonTermsQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -348,7 +347,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
} }
} }
return Optional.of(new CommonTermsQueryBuilder(fieldName, text) return new CommonTermsQueryBuilder(fieldName, text)
.lowFreqMinimumShouldMatch(lowFreqMinimumShouldMatch) .lowFreqMinimumShouldMatch(lowFreqMinimumShouldMatch)
.highFreqMinimumShouldMatch(highFreqMinimumShouldMatch) .highFreqMinimumShouldMatch(highFreqMinimumShouldMatch)
.analyzer(analyzer) .analyzer(analyzer)
@ -357,7 +356,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
.disableCoord(disableCoord) .disableCoord(disableCoord)
.cutoffFrequency(cutoffFrequency) .cutoffFrequency(cutoffFrequency)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A query that wraps a filter and simply returns a constant score equal to the * A query that wraps a filter and simply returns a constant score equal to the
@ -86,10 +85,10 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
builder.endObject(); builder.endObject();
} }
public static Optional<ConstantScoreQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static ConstantScoreQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Optional<QueryBuilder> query = null; QueryBuilder query = null;
boolean queryFound = false; boolean queryFound = false;
String queryName = null; String queryName = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -130,15 +129,10 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
throw new ParsingException(parser.getTokenLocation(), "[constant_score] requires a 'filter' element"); throw new ParsingException(parser.getTokenLocation(), "[constant_score] requires a 'filter' element");
} }
if (query.isPresent() == false) { ConstantScoreQueryBuilder constantScoreBuilder = new ConstantScoreQueryBuilder(query);
// if inner query is empty, bubble this up to caller so they can decide how to deal with it
return Optional.empty();
}
ConstantScoreQueryBuilder constantScoreBuilder = new ConstantScoreQueryBuilder(query.get());
constantScoreBuilder.boost(boost); constantScoreBuilder.boost(boost);
constantScoreBuilder.queryName(queryName); constantScoreBuilder.queryName(queryName);
return Optional.of(constantScoreBuilder); return constantScoreBuilder;
} }
@Override @Override

View File

@ -34,7 +34,6 @@ import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A query that generates the union of documents produced by its sub-queries, and that scores each document * A query that generates the union of documents produced by its sub-queries, and that scores each document
@ -122,7 +121,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<DisMaxQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static DisMaxQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -140,7 +139,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERIES_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERIES_FIELD)) {
queriesFound = true; queriesFound = true;
parseContext.parseInnerQueryBuilder().ifPresent(queries::add); queries.add(parseContext.parseInnerQueryBuilder());
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]");
} }
@ -148,7 +147,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERIES_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERIES_FIELD)) {
queriesFound = true; queriesFound = true;
while (token != XContentParser.Token.END_ARRAY) { while (token != XContentParser.Token.END_ARRAY) {
parseContext.parseInnerQueryBuilder().ifPresent(queries::add); queries.add(parseContext.parseInnerQueryBuilder());
token = parser.nextToken(); token = parser.nextToken();
} }
} else { } else {
@ -178,7 +177,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
for (QueryBuilder query : queries) { for (QueryBuilder query : queries) {
disMaxQuery.add(query); disMaxQuery.add(query);
} }
return Optional.of(disMaxQuery); return disMaxQuery;
} }
@Override @Override

View File

@ -37,7 +37,6 @@ import java.io.IOException;
import java.util.Collection; import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Constructs a query that only match on documents that the field has a value in them. * Constructs a query that only match on documents that the field has a value in them.
@ -84,7 +83,7 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<ExistsQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static ExistsQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldPattern = null; String fieldPattern = null;
@ -120,7 +119,7 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
ExistsQueryBuilder builder = new ExistsQueryBuilder(fieldPattern); ExistsQueryBuilder builder = new ExistsQueryBuilder(fieldPattern);
builder.queryName(queryName); builder.queryName(queryName);
builder.boost(boost); builder.boost(boost);
return Optional.of(builder); return builder;
} }
@Override @Override

View File

@ -33,7 +33,6 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMaskingSpanQueryBuilder> implements SpanQueryBuilder { public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMaskingSpanQueryBuilder> implements SpanQueryBuilder {
public static final String NAME = "field_masking_span"; public static final String NAME = "field_masking_span";
@ -101,7 +100,7 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
builder.endObject(); builder.endObject();
} }
public static Optional<FieldMaskingSpanQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static FieldMaskingSpanQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -117,11 +116,11 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query must be of type span query");
} }
inner = (SpanQueryBuilder) query.get(); inner = (SpanQueryBuilder) query;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query does not support [" throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query does not support ["
+ currentFieldName + "]"); + currentFieldName + "]");
@ -149,7 +148,7 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
FieldMaskingSpanQueryBuilder queryBuilder = new FieldMaskingSpanQueryBuilder(inner, field); FieldMaskingSpanQueryBuilder queryBuilder = new FieldMaskingSpanQueryBuilder(inner, field);
queryBuilder.boost(boost); queryBuilder.boost(boost);
queryBuilder.queryName(queryName); queryBuilder.queryName(queryName);
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -37,7 +37,6 @@ import org.elasticsearch.index.query.support.QueryParsers;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A Query that does fuzzy matching for a specific value. * A Query that does fuzzy matching for a specific value.
@ -252,7 +251,7 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
builder.endObject(); builder.endObject();
} }
public static Optional<FuzzyQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static FuzzyQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
Object value = null; Object value = null;
@ -307,14 +306,14 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
value = parser.objectBytes(); value = parser.objectBytes();
} }
} }
return Optional.of(new FuzzyQueryBuilder(fieldName, value) return new FuzzyQueryBuilder(fieldName, value)
.fuzziness(fuzziness) .fuzziness(fuzziness)
.prefixLength(prefixLength) .prefixLength(prefixLength)
.maxExpansions(maxExpansions) .maxExpansions(maxExpansions)
.transpositions(transpositions) .transpositions(transpositions)
.rewrite(rewrite) .rewrite(rewrite)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
@Override @Override

View File

@ -40,7 +40,6 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Creates a Lucene query that will filter for all documents that lie within the specified * Creates a Lucene query that will filter for all documents that lie within the specified
@ -374,7 +373,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
builder.endObject(); builder.endObject();
} }
public static Optional<GeoBoundingBoxQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static GeoBoundingBoxQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -485,7 +484,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
} else { } else {
builder.setValidationMethod(GeoValidationMethod.infer(coerce, ignoreMalformed)); builder.setValidationMethod(GeoValidationMethod.infer(coerce, ignoreMalformed));
} }
return Optional.of(builder); return builder;
} }
@Override @Override

View File

@ -40,7 +40,6 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Locale; import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Filter results of a query to include only those within a specific distance to some * Filter results of a query to include only those within a specific distance to some
@ -310,7 +309,7 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
builder.endObject(); builder.endObject();
} }
public static Optional<GeoDistanceQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static GeoDistanceQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
XContentParser.Token token; XContentParser.Token token;
@ -425,7 +424,7 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
qb.boost(boost); qb.boost(boost);
qb.queryName(queryName); qb.queryName(queryName);
qb.ignoreUnmapped(ignoreUnmapped); qb.ignoreUnmapped(ignoreUnmapped);
return Optional.of(qb); return qb;
} }
@Override @Override

View File

@ -40,7 +40,6 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQueryBuilder> { public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQueryBuilder> {
public static final String NAME = "geo_polygon"; public static final String NAME = "geo_polygon";
@ -227,7 +226,7 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
builder.endObject(); builder.endObject();
} }
public static Optional<GeoPolygonQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static GeoPolygonQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -308,7 +307,7 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
builder.boost(boost); builder.boost(boost);
} }
builder.ignoreUnmapped(ignoreUnmapped); builder.ignoreUnmapped(ignoreUnmapped);
return Optional.of(builder); return builder;
} }
@Override @Override

View File

@ -47,7 +47,6 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* {@link QueryBuilder} that builds a GeoShape Query * {@link QueryBuilder} that builds a GeoShape Query
@ -456,7 +455,7 @@ public class GeoShapeQueryBuilder extends AbstractQueryBuilder<GeoShapeQueryBuil
builder.endObject(); builder.endObject();
} }
public static Optional<GeoShapeQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static GeoShapeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -562,7 +561,7 @@ public class GeoShapeQueryBuilder extends AbstractQueryBuilder<GeoShapeQueryBuil
} }
builder.boost(boost); builder.boost(boost);
builder.ignoreUnmapped(ignoreUnmapped); builder.ignoreUnmapped(ignoreUnmapped);
return Optional.of(builder); return builder;
} }
@Override @Override

View File

@ -43,7 +43,6 @@ import java.io.IOException;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A query builder for <tt>has_child</tt> query. * A query builder for <tt>has_child</tt> query.
@ -222,7 +221,7 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
builder.endObject(); builder.endObject();
} }
public static Optional<HasChildQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static HasChildQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String childType = null; String childType = null;
@ -234,7 +233,7 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
InnerHitBuilder innerHitBuilder = null; InnerHitBuilder innerHitBuilder = null;
String currentFieldName = null; String currentFieldName = null;
XContentParser.Token token; XContentParser.Token token;
Optional<QueryBuilder> iqb = Optional.empty(); QueryBuilder iqb = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
@ -268,13 +267,7 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
} }
} }
} }
HasChildQueryBuilder hasChildQueryBuilder = new HasChildQueryBuilder(childType, iqb, scoreMode);
if (iqb.isPresent() == false) {
// if inner query is empty, bubble this up to caller so they can decide how to deal with it
return Optional.empty();
}
HasChildQueryBuilder hasChildQueryBuilder = new HasChildQueryBuilder(childType, iqb.get(), scoreMode);
if (innerHitBuilder != null) { if (innerHitBuilder != null) {
hasChildQueryBuilder.innerHit(innerHitBuilder); hasChildQueryBuilder.innerHit(innerHitBuilder);
} }
@ -282,7 +275,7 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
hasChildQueryBuilder.queryName(queryName); hasChildQueryBuilder.queryName(queryName);
hasChildQueryBuilder.boost(boost); hasChildQueryBuilder.boost(boost);
hasChildQueryBuilder.ignoreUnmapped(ignoreUnmapped); hasChildQueryBuilder.ignoreUnmapped(ignoreUnmapped);
return Optional.of(hasChildQueryBuilder); return hasChildQueryBuilder;
} }
public static ScoreMode parseScoreMode(String scoreModeString) { public static ScoreMode parseScoreMode(String scoreModeString) {

View File

@ -38,7 +38,6 @@ import java.io.IOException;
import java.util.HashSet; import java.util.HashSet;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.Set; import java.util.Set;
/** /**
@ -223,7 +222,7 @@ public class HasParentQueryBuilder extends AbstractQueryBuilder<HasParentQueryBu
builder.endObject(); builder.endObject();
} }
public static Optional<HasParentQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static HasParentQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String parentType = null; String parentType = null;
@ -234,7 +233,7 @@ public class HasParentQueryBuilder extends AbstractQueryBuilder<HasParentQueryBu
String currentFieldName = null; String currentFieldName = null;
XContentParser.Token token; XContentParser.Token token;
Optional<QueryBuilder> iqb = Optional.empty(); QueryBuilder iqb = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
@ -272,18 +271,14 @@ public class HasParentQueryBuilder extends AbstractQueryBuilder<HasParentQueryBu
} }
} }
} }
if (iqb.isPresent() == false) { HasParentQueryBuilder queryBuilder = new HasParentQueryBuilder(parentType, iqb, score)
// if inner query is empty, bubble this up to caller so they can decide how to deal with it
return Optional.empty();
}
HasParentQueryBuilder queryBuilder = new HasParentQueryBuilder(parentType, iqb.get(), score)
.ignoreUnmapped(ignoreUnmapped) .ignoreUnmapped(ignoreUnmapped)
.queryName(queryName) .queryName(queryName)
.boost(boost); .boost(boost);
if (innerHits != null) { if (innerHits != null) {
queryBuilder.innerHit(innerHits); queryBuilder.innerHit(innerHits);
} }
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -39,7 +39,6 @@ import java.util.Collection;
import java.util.Collections; import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import static org.elasticsearch.common.xcontent.ObjectParser.fromList; import static org.elasticsearch.common.xcontent.ObjectParser.fromList;
@ -146,9 +145,9 @@ public class IdsQueryBuilder extends AbstractQueryBuilder<IdsQueryBuilder> {
declareStandardFields(PARSER); declareStandardFields(PARSER);
} }
public static Optional<IdsQueryBuilder> fromXContent(QueryParseContext context) { public static IdsQueryBuilder fromXContent(QueryParseContext context) {
try { try {
return Optional.of(PARSER.apply(context.parser(), context)); return PARSER.apply(context.parser(), context);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ParsingException(context.parser().getTokenLocation(), e.getMessage(), e); throw new ParsingException(context.parser().getTokenLocation(), e.getMessage(), e);
} }

View File

@ -64,9 +64,9 @@ public class MatchAllQueryBuilder extends AbstractQueryBuilder<MatchAllQueryBuil
declareStandardFields(PARSER); declareStandardFields(PARSER);
} }
public static Optional<MatchAllQueryBuilder> fromXContent(QueryParseContext context) { public static MatchAllQueryBuilder fromXContent(QueryParseContext context) {
try { try {
return Optional.of(PARSER.apply(context.parser(), context)); return PARSER.apply(context.parser(), context);
} catch (IllegalArgumentException e) { } catch (IllegalArgumentException e) {
throw new ParsingException(context.parser().getTokenLocation(), e.getMessage(), e); throw new ParsingException(context.parser().getTokenLocation(), e.getMessage(), e);
} }

View File

@ -28,7 +28,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
/** /**
* A query that matches no document. * A query that matches no document.
@ -58,7 +57,7 @@ public class MatchNoneQueryBuilder extends AbstractQueryBuilder<MatchNoneQueryBu
builder.endObject(); builder.endObject();
} }
public static Optional<MatchNoneQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static MatchNoneQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String currentFieldName = null; String currentFieldName = null;
@ -86,7 +85,7 @@ public class MatchNoneQueryBuilder extends AbstractQueryBuilder<MatchNoneQueryBu
MatchNoneQueryBuilder matchNoneQueryBuilder = new MatchNoneQueryBuilder(); MatchNoneQueryBuilder matchNoneQueryBuilder = new MatchNoneQueryBuilder();
matchNoneQueryBuilder.boost(boost); matchNoneQueryBuilder.boost(boost);
matchNoneQueryBuilder.queryName(queryName); matchNoneQueryBuilder.queryName(queryName);
return Optional.of(matchNoneQueryBuilder); return matchNoneQueryBuilder;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.index.search.MatchQuery;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Match query is a query that analyzes the text and constructs a phrase prefix * Match query is a query that analyzes the text and constructs a phrase prefix
@ -190,7 +189,7 @@ public class MatchPhrasePrefixQueryBuilder extends AbstractQueryBuilder<MatchPhr
return Objects.hash(fieldName, value, analyzer, slop, maxExpansions); return Objects.hash(fieldName, value, analyzer, slop, maxExpansions);
} }
public static Optional<MatchPhrasePrefixQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static MatchPhrasePrefixQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
Object value = null; Object value = null;
@ -247,6 +246,6 @@ public class MatchPhrasePrefixQueryBuilder extends AbstractQueryBuilder<MatchPhr
matchQuery.maxExpansions(maxExpansion); matchQuery.maxExpansions(maxExpansion);
matchQuery.queryName(queryName); matchQuery.queryName(queryName);
matchQuery.boost(boost); matchQuery.boost(boost);
return Optional.of(matchQuery); return matchQuery;
} }
} }

View File

@ -31,7 +31,6 @@ import org.elasticsearch.index.search.MatchQuery;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Match query is a query that analyzes the text and constructs a phrase query * Match query is a query that analyzes the text and constructs a phrase query
@ -162,7 +161,7 @@ public class MatchPhraseQueryBuilder extends AbstractQueryBuilder<MatchPhraseQue
return Objects.hash(fieldName, value, analyzer, slop); return Objects.hash(fieldName, value, analyzer, slop);
} }
public static Optional<MatchPhraseQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static MatchPhraseQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
Object value = null; Object value = null;
@ -215,6 +214,6 @@ public class MatchPhraseQueryBuilder extends AbstractQueryBuilder<MatchPhraseQue
matchQuery.slop(slop); matchQuery.slop(slop);
matchQuery.queryName(queryName); matchQuery.queryName(queryName);
matchQuery.boost(boost); matchQuery.boost(boost);
return Optional.of(matchQuery); return matchQuery;
} }
} }

View File

@ -40,7 +40,6 @@ import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Match query is a query that analyzes the text and constructs a query as the * Match query is a query that analyzes the text and constructs a query as the
@ -524,7 +523,7 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
return NAME; return NAME;
} }
public static Optional<MatchQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static MatchQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
MatchQuery.Type type = MatchQuery.Type.BOOLEAN; MatchQuery.Type type = MatchQuery.Type.BOOLEAN;
@ -646,7 +645,7 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
matchQuery.zeroTermsQuery(zeroTermsQuery); matchQuery.zeroTermsQuery(zeroTermsQuery);
matchQuery.queryName(queryName); matchQuery.queryName(queryName);
matchQuery.boost(boost); matchQuery.boost(boost);
return Optional.of(matchQuery); return matchQuery;
} }
} }

View File

@ -802,7 +802,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
builder.endObject(); builder.endObject();
} }
public static Optional<MoreLikeThisQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static MoreLikeThisQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
// document inputs // document inputs
@ -952,7 +952,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
if (stopWords != null) { if (stopWords != null) {
moreLikeThisQueryBuilder.stopWords(stopWords); moreLikeThisQueryBuilder.stopWords(stopWords);
} }
return Optional.of(moreLikeThisQueryBuilder); return moreLikeThisQueryBuilder;
} }
private static void parseLikeField(QueryParseContext parseContext, List<String> texts, List<Item> items) throws IOException { private static void parseLikeField(QueryParseContext parseContext, List<String> texts, List<Item> items) throws IOException {

View File

@ -556,7 +556,7 @@ public class MultiMatchQueryBuilder extends AbstractQueryBuilder<MultiMatchQuery
builder.endObject(); builder.endObject();
} }
public static Optional<MultiMatchQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static MultiMatchQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Object value = null; Object value = null;
@ -660,7 +660,7 @@ public class MultiMatchQueryBuilder extends AbstractQueryBuilder<MultiMatchQuery
"Fuziness not allowed for type [" + type.parseField.getPreferredName() + "]"); "Fuziness not allowed for type [" + type.parseField.getPreferredName() + "]");
} }
return Optional.of(new MultiMatchQueryBuilder(value) return new MultiMatchQueryBuilder(value)
.fields(fieldsBoosts) .fields(fieldsBoosts)
.type(type) .type(type)
.analyzer(analyzer) .analyzer(analyzer)
@ -677,7 +677,7 @@ public class MultiMatchQueryBuilder extends AbstractQueryBuilder<MultiMatchQuery
.tieBreaker(tieBreaker) .tieBreaker(tieBreaker)
.zeroTermsQuery(zeroTermsQuery) .zeroTermsQuery(zeroTermsQuery)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
private static void parseFieldAndBoost(XContentParser parser, Map<String, Float> fieldsBoosts) throws IOException { private static void parseFieldAndBoost(XContentParser parser, Map<String, Float> fieldsBoosts) throws IOException {

View File

@ -36,7 +36,6 @@ import org.elasticsearch.index.mapper.ObjectMapper;
import java.io.IOException; import java.io.IOException;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder> { public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder> {
public static final String NAME = "nested"; public static final String NAME = "nested";
@ -152,12 +151,12 @@ public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<NestedQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static NestedQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
ScoreMode scoreMode = ScoreMode.Avg; ScoreMode scoreMode = ScoreMode.Avg;
String queryName = null; String queryName = null;
Optional<QueryBuilder> query = Optional.empty(); QueryBuilder query = null;
String path = null; String path = null;
String currentFieldName = null; String currentFieldName = null;
InnerHitBuilder innerHitBuilder = null; InnerHitBuilder innerHitBuilder = null;
@ -190,19 +189,14 @@ public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder>
} }
} }
} }
NestedQueryBuilder queryBuilder = new NestedQueryBuilder(path, query, scoreMode)
if (query.isPresent() == false) {
// if inner query is empty, bubble this up to caller so they can decide how to deal with it
return Optional.empty();
}
NestedQueryBuilder queryBuilder = new NestedQueryBuilder(path, query.get(), scoreMode)
.ignoreUnmapped(ignoreUnmapped) .ignoreUnmapped(ignoreUnmapped)
.queryName(queryName) .queryName(queryName)
.boost(boost); .boost(boost);
if (innerHitBuilder != null) { if (innerHitBuilder != null) {
queryBuilder.innerHit(innerHitBuilder); queryBuilder.innerHit(innerHitBuilder);
} }
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -38,7 +38,6 @@ import org.elasticsearch.index.mapper.TypeFieldMapper;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public final class ParentIdQueryBuilder extends AbstractQueryBuilder<ParentIdQueryBuilder> { public final class ParentIdQueryBuilder extends AbstractQueryBuilder<ParentIdQueryBuilder> {
public static final String NAME = "parent_id"; public static final String NAME = "parent_id";
@ -116,7 +115,7 @@ public final class ParentIdQueryBuilder extends AbstractQueryBuilder<ParentIdQue
builder.endObject(); builder.endObject();
} }
public static Optional<ParentIdQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static ParentIdQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String type = null; String type = null;
@ -150,7 +149,7 @@ public final class ParentIdQueryBuilder extends AbstractQueryBuilder<ParentIdQue
queryBuilder.queryName(queryName); queryBuilder.queryName(queryName);
queryBuilder.boost(boost); queryBuilder.boost(boost);
queryBuilder.ignoreUnmapped(ignoreUnmapped); queryBuilder.ignoreUnmapped(ignoreUnmapped);
return Optional.of(queryBuilder); return queryBuilder;
} }

View File

@ -36,7 +36,6 @@ import org.elasticsearch.index.query.support.QueryParsers;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A Query that matches documents containing terms with a specified prefix. * A Query that matches documents containing terms with a specified prefix.
@ -117,7 +116,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<PrefixQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static PrefixQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -161,10 +160,10 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
} }
} }
return Optional.of(new PrefixQueryBuilder(fieldName, value) return new PrefixQueryBuilder(fieldName, value)
.rewrite(rewrite) .rewrite(rewrite)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
@Override @Override

View File

@ -23,20 +23,15 @@ import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParseFieldMatcherSupplier; import org.elasticsearch.common.ParseFieldMatcherSupplier;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.logging.DeprecationLogger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.indices.query.IndicesQueriesRegistry; import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.script.Script; import org.elasticsearch.script.Script;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class QueryParseContext implements ParseFieldMatcherSupplier { public class QueryParseContext implements ParseFieldMatcherSupplier {
private static final DeprecationLogger DEPRECATION_LOGGER = new DeprecationLogger(Loggers.getLogger(QueryParseContext.class));
private static final ParseField CACHE = new ParseField("_cache").withAllDeprecated("Elasticsearch makes its own caching decisions"); private static final ParseField CACHE = new ParseField("_cache").withAllDeprecated("Elasticsearch makes its own caching decisions");
private static final ParseField CACHE_KEY = new ParseField("_cache_key").withAllDeprecated("Filters are always used as cache keys"); private static final ParseField CACHE_KEY = new ParseField("_cache_key").withAllDeprecated("Filters are always used as cache keys");
@ -75,7 +70,7 @@ public class QueryParseContext implements ParseFieldMatcherSupplier {
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
String fieldName = parser.currentName(); String fieldName = parser.currentName();
if ("query".equals(fieldName)) { if ("query".equals(fieldName)) {
queryBuilder = parseInnerQueryBuilder().orElse(null); queryBuilder = parseInnerQueryBuilder();
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "request does not support [" + parser.currentName() + "]"); throw new ParsingException(parser.getTokenLocation(), "request does not support [" + parser.currentName() + "]");
} }
@ -92,20 +87,15 @@ public class QueryParseContext implements ParseFieldMatcherSupplier {
/** /**
* Parses a query excluding the query element that wraps it * Parses a query excluding the query element that wraps it
*/ */
public Optional<QueryBuilder> parseInnerQueryBuilder() throws IOException { public QueryBuilder parseInnerQueryBuilder() throws IOException {
if (parser.currentToken() != XContentParser.Token.START_OBJECT) { if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) { if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, must start with start_object"); throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, must start with start_object");
} }
} }
if (parser.nextToken() == XContentParser.Token.END_OBJECT) { if (parser.nextToken() == XContentParser.Token.END_OBJECT) {
// we encountered '{}' for a query clause // we encountered '{}' for a query clause, it used to be supported, deprecated in 5.0 and removed in 6.0
String msg = "query malformed, empty clause found at [" + parser.getTokenLocation() +"]"; throw new IllegalArgumentException("query malformed, empty clause found at [" + parser.getTokenLocation() +"]");
DEPRECATION_LOGGER.deprecated(msg);
if (parseFieldMatcher.isStrict()) {
throw new IllegalArgumentException(msg);
}
return Optional.empty();
} }
if (parser.currentToken() != XContentParser.Token.FIELD_NAME) { if (parser.currentToken() != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object"); throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
@ -115,9 +105,7 @@ public class QueryParseContext implements ParseFieldMatcherSupplier {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) { if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[" + queryName + "] query malformed, no start_object after query name"); throw new ParsingException(parser.getTokenLocation(), "[" + queryName + "] query malformed, no start_object after query name");
} }
@SuppressWarnings("unchecked") QueryBuilder result = indicesQueriesRegistry.lookup(queryName, parseFieldMatcher, parser.getTokenLocation()).fromXContent(this);
Optional<QueryBuilder> result = (Optional<QueryBuilder>) indicesQueriesRegistry.lookup(queryName, parseFieldMatcher,
parser.getTokenLocation()).fromXContent(this);
//end_object of the specific query (e.g. match, multi_match etc.) element //end_object of the specific query (e.g. match, multi_match etc.) element
if (parser.currentToken() != XContentParser.Token.END_OBJECT) { if (parser.currentToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),

View File

@ -20,7 +20,6 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
/** /**
* Defines a query parser that is able to parse {@link QueryBuilder}s from {@link org.elasticsearch.common.xcontent.XContent}. * Defines a query parser that is able to parse {@link QueryBuilder}s from {@link org.elasticsearch.common.xcontent.XContent}.
@ -37,5 +36,5 @@ public interface QueryParser<QB extends QueryBuilder> {
* call * call
* @return the new QueryBuilder * @return the new QueryBuilder
*/ */
Optional<QB> fromXContent(QueryParseContext parseContext) throws IOException; QB fromXContent(QueryParseContext parseContext) throws IOException;
} }

View File

@ -57,7 +57,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.TreeMap; import java.util.TreeMap;
@ -685,7 +684,7 @@ public class QueryStringQueryBuilder extends AbstractQueryBuilder<QueryStringQue
builder.endObject(); builder.endObject();
} }
public static Optional<QueryStringQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static QueryStringQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String currentFieldName = null; String currentFieldName = null;
XContentParser.Token token; XContentParser.Token token;
@ -855,7 +854,7 @@ public class QueryStringQueryBuilder extends AbstractQueryBuilder<QueryStringQue
queryStringQuery.queryName(queryName); queryStringQuery.queryName(queryName);
queryStringQuery.splitOnWhitespace(splitOnWhitespace); queryStringQuery.splitOnWhitespace(splitOnWhitespace);
queryStringQuery.useAllFields(useAllFields); queryStringQuery.useAllFields(useAllFields);
return Optional.of(queryStringQuery); return queryStringQuery;
} }
@Override @Override

View File

@ -44,7 +44,6 @@ import org.joda.time.DateTimeZone;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A Query that matches documents within an range of terms. * A Query that matches documents within an range of terms.
@ -344,7 +343,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
builder.endObject(); builder.endObject();
} }
public static Optional<RangeQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static RangeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -435,7 +434,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
if (relation != null) { if (relation != null) {
rangeQuery.relation(relation); rangeQuery.relation(relation);
} }
return Optional.of(rangeQuery); return rangeQuery;
} }
@Override @Override

View File

@ -37,7 +37,6 @@ import org.elasticsearch.index.query.support.QueryParsers;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A Query that does fuzzy matching for a specific value. * A Query that does fuzzy matching for a specific value.
@ -178,7 +177,7 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<RegexpQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static RegexpQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
String rewrite = null; String rewrite = null;
@ -233,12 +232,12 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} }
} }
return Optional.of(new RegexpQueryBuilder(fieldName, value) return new RegexpQueryBuilder(fieldName, value)
.flags(flagsValue) .flags(flagsValue)
.maxDeterminizedStates(maxDeterminizedStates) .maxDeterminizedStates(maxDeterminizedStates)
.rewrite(rewrite) .rewrite(rewrite)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
@Override @Override

View File

@ -38,7 +38,6 @@ import org.elasticsearch.script.SearchScript;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder> { public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder> {
public static final String NAME = "script"; public static final String NAME = "script";
@ -84,7 +83,7 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<ScriptQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static ScriptQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
// also, when caching, since its isCacheable is false, will result in loading all bit set... // also, when caching, since its isCacheable is false, will result in loading all bit set...
Script script = null; Script script = null;
@ -122,9 +121,9 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
throw new ParsingException(parser.getTokenLocation(), "script must be provided with a [script] filter"); throw new ParsingException(parser.getTokenLocation(), "script must be provided with a [script] filter");
} }
return Optional.of(new ScriptQueryBuilder(script) return new ScriptQueryBuilder(script)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
@Override @Override

View File

@ -40,7 +40,6 @@ import java.util.HashMap;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.TreeMap; import java.util.TreeMap;
/** /**
@ -471,7 +470,7 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
builder.endObject(); builder.endObject();
} }
public static Optional<SimpleQueryStringBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SimpleQueryStringBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String currentFieldName = null; String currentFieldName = null;
@ -580,7 +579,7 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
} }
qb.analyzeWildcard(analyzeWildcard).boost(boost).quoteFieldSuffix(quoteFieldSuffix); qb.analyzeWildcard(analyzeWildcard).boost(boost).quoteFieldSuffix(quoteFieldSuffix);
qb.useAllFields(useAllFields); qb.useAllFields(useAllFields);
return Optional.of(qb); return qb;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Builder for {@link org.apache.lucene.search.spans.SpanContainingQuery}. * Builder for {@link org.apache.lucene.search.spans.SpanContainingQuery}.
@ -100,7 +99,7 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
builder.endObject(); builder.endObject();
} }
public static Optional<SpanContainingQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanContainingQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null; String queryName = null;
@ -114,17 +113,17 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, BIG_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, BIG_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_containing [big] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "span_containing [big] must be of type span query");
} }
big = (SpanQueryBuilder) query.get(); big = (SpanQueryBuilder) query;
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, LITTLE_FIELD)) { } else if (parseContext.getParseFieldMatcher().match(currentFieldName, LITTLE_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_containing [little] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "span_containing [little] must be of type span query");
} }
little = (SpanQueryBuilder) query.get(); little = (SpanQueryBuilder) query;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),
"[span_containing] query does not support [" + currentFieldName + "]"); "[span_containing] query does not support [" + currentFieldName + "]");
@ -141,7 +140,7 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
SpanContainingQueryBuilder query = new SpanContainingQueryBuilder(big, little); SpanContainingQueryBuilder query = new SpanContainingQueryBuilder(big, little);
query.boost(boost).queryName(queryName); query.boost(boost).queryName(queryName);
return Optional.of(query); return query;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBuilder> implements SpanQueryBuilder { public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBuilder> implements SpanQueryBuilder {
public static final String NAME = "span_first"; public static final String NAME = "span_first";
@ -100,7 +99,7 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
builder.endObject(); builder.endObject();
} }
public static Optional<SpanFirstQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanFirstQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -116,11 +115,11 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MATCH_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, MATCH_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanFirst [match] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "spanFirst [match] must be of type span query");
} }
match = (SpanQueryBuilder) query.get(); match = (SpanQueryBuilder) query;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_first] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_first] query does not support [" + currentFieldName + "]");
} }
@ -144,7 +143,7 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
} }
SpanFirstQueryBuilder queryBuilder = new SpanFirstQueryBuilder(match, end); SpanFirstQueryBuilder queryBuilder = new SpanFirstQueryBuilder(match, end);
queryBuilder.boost(boost).queryName(queryName); queryBuilder.boost(boost).queryName(queryName);
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -33,7 +33,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Query that allows wraping a {@link MultiTermQueryBuilder} (one of wildcard, fuzzy, prefix, term, range or regexp query) * Query that allows wraping a {@link MultiTermQueryBuilder} (one of wildcard, fuzzy, prefix, term, range or regexp query)
@ -82,7 +81,7 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
builder.endObject(); builder.endObject();
} }
public static Optional<SpanMultiTermQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanMultiTermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String currentFieldName = null; String currentFieldName = null;
MultiTermQueryBuilder subQuery = null; MultiTermQueryBuilder subQuery = null;
@ -94,12 +93,12 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MATCH_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, MATCH_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof MultiTermQueryBuilder == false) { if (query instanceof MultiTermQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),
"[span_multi] [" + MATCH_FIELD.getPreferredName() + "] must be of type multi term query"); "[span_multi] [" + MATCH_FIELD.getPreferredName() + "] must be of type multi term query");
} }
subQuery = (MultiTermQueryBuilder) query.get(); subQuery = (MultiTermQueryBuilder) query;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_multi] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_multi] query does not support [" + currentFieldName + "]");
} }
@ -119,7 +118,7 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
"[span_multi] must have [" + MATCH_FIELD.getPreferredName() + "] multi term query clause"); "[span_multi] must have [" + MATCH_FIELD.getPreferredName() + "] multi term query clause");
} }
return Optional.of(new SpanMultiTermQueryBuilder(subQuery).queryName(queryName).boost(boost)); return new SpanMultiTermQueryBuilder(subQuery).queryName(queryName).boost(boost);
} }
@Override @Override

View File

@ -34,7 +34,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Matches spans which are near one another. One can specify slop, the maximum number * Matches spans which are near one another. One can specify slop, the maximum number
@ -144,7 +143,7 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
builder.endObject(); builder.endObject();
} }
public static Optional<SpanNearQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanNearQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -162,11 +161,11 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, CLAUSES_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, CLAUSES_FIELD)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanNear [clauses] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "spanNear [clauses] must be of type span query");
} }
clauses.add((SpanQueryBuilder) query.get()); clauses.add((SpanQueryBuilder) query);
} }
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_near] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_near] query does not support [" + currentFieldName + "]");
@ -203,7 +202,7 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
queryBuilder.inOrder(inOrder); queryBuilder.inOrder(inOrder);
queryBuilder.boost(boost); queryBuilder.boost(boost);
queryBuilder.queryName(queryName); queryBuilder.queryName(queryName);
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilder> implements SpanQueryBuilder { public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilder> implements SpanQueryBuilder {
public static final String NAME = "span_not"; public static final String NAME = "span_not";
@ -161,7 +160,7 @@ public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilde
builder.endObject(); builder.endObject();
} }
public static Optional<SpanNotQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanNotQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -182,17 +181,17 @@ public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilde
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, INCLUDE_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, INCLUDE_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanNot [include] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "spanNot [include] must be of type span query");
} }
include = (SpanQueryBuilder) query.get(); include = (SpanQueryBuilder) query;
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, EXCLUDE_FIELD)) { } else if (parseContext.getParseFieldMatcher().match(currentFieldName, EXCLUDE_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanNot [exclude] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "spanNot [exclude] must be of type span query");
} }
exclude = (SpanQueryBuilder) query.get(); exclude = (SpanQueryBuilder) query;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_not] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_not] query does not support [" + currentFieldName + "]");
} }
@ -234,7 +233,7 @@ public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilde
} }
spanNotQuery.boost(boost); spanNotQuery.boost(boost);
spanNotQuery.queryName(queryName); spanNotQuery.queryName(queryName);
return Optional.of(spanNotQuery); return spanNotQuery;
} }
@Override @Override

View File

@ -34,7 +34,6 @@ import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Span query that matches the union of its clauses. Maps to {@link SpanOrQuery}. * Span query that matches the union of its clauses. Maps to {@link SpanOrQuery}.
@ -98,7 +97,7 @@ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder>
builder.endObject(); builder.endObject();
} }
public static Optional<SpanOrQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanOrQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -114,11 +113,11 @@ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder>
} else if (token == XContentParser.Token.START_ARRAY) { } else if (token == XContentParser.Token.START_ARRAY) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, CLAUSES_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, CLAUSES_FIELD)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanOr [clauses] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "spanOr [clauses] must be of type span query");
} }
clauses.add((SpanQueryBuilder) query.get()); clauses.add((SpanQueryBuilder) query);
} }
} else { } else {
throw new ParsingException(parser.getTokenLocation(), "[span_or] query does not support [" + currentFieldName + "]"); throw new ParsingException(parser.getTokenLocation(), "[span_or] query does not support [" + currentFieldName + "]");
@ -144,7 +143,7 @@ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder>
} }
queryBuilder.boost(boost); queryBuilder.boost(boost);
queryBuilder.queryName(queryName); queryBuilder.queryName(queryName);
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
/** /**
* A Span Query that matches documents containing a term. * A Span Query that matches documents containing a term.
@ -92,7 +91,7 @@ public class SpanTermQueryBuilder extends BaseTermQueryBuilder<SpanTermQueryBuil
return new SpanTermQuery(term); return new SpanTermQuery(term);
} }
public static Optional<SpanTermQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException, ParsingException { public static SpanTermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
Object value = null; Object value = null;
@ -133,7 +132,7 @@ public class SpanTermQueryBuilder extends BaseTermQueryBuilder<SpanTermQueryBuil
SpanTermQueryBuilder result = new SpanTermQueryBuilder(fieldName, value); SpanTermQueryBuilder result = new SpanTermQueryBuilder(fieldName, value);
result.boost(boost).queryName(queryName); result.boost(boost).queryName(queryName);
return Optional.of(result); return result;
} }
@Override @Override

View File

@ -31,7 +31,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Builder for {@link org.apache.lucene.search.spans.SpanWithinQuery}. * Builder for {@link org.apache.lucene.search.spans.SpanWithinQuery}.
@ -105,7 +104,7 @@ public class SpanWithinQueryBuilder extends AbstractQueryBuilder<SpanWithinQuery
builder.endObject(); builder.endObject();
} }
public static Optional<SpanWithinQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static SpanWithinQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -120,17 +119,17 @@ public class SpanWithinQueryBuilder extends AbstractQueryBuilder<SpanWithinQuery
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, BIG_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, BIG_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_within [big] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "span_within [big] must be of type span query");
} }
big = (SpanQueryBuilder) query.get(); big = (SpanQueryBuilder) query;
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, LITTLE_FIELD)) { } else if (parseContext.getParseFieldMatcher().match(currentFieldName, LITTLE_FIELD)) {
Optional<QueryBuilder> query = parseContext.parseInnerQueryBuilder(); QueryBuilder query = parseContext.parseInnerQueryBuilder();
if (query.isPresent() == false || query.get() instanceof SpanQueryBuilder == false) { if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_within [little] must be of type span query"); throw new ParsingException(parser.getTokenLocation(), "span_within [little] must be of type span query");
} }
little = (SpanQueryBuilder) query.get(); little = (SpanQueryBuilder) query;
} else { } else {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),
"[span_within] query does not support [" + currentFieldName + "]"); "[span_within] query does not support [" + currentFieldName + "]");
@ -153,7 +152,7 @@ public class SpanWithinQueryBuilder extends AbstractQueryBuilder<SpanWithinQuery
SpanWithinQueryBuilder query = new SpanWithinQueryBuilder(big, little); SpanWithinQueryBuilder query = new SpanWithinQueryBuilder(big, little);
query.boost(boost).queryName(queryName); query.boost(boost).queryName(queryName);
return Optional.of(query); return query;
} }
@Override @Override

View File

@ -30,7 +30,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MappedFieldType; import org.elasticsearch.index.mapper.MappedFieldType;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
/** /**
* A Query that matches documents containing a term. * A Query that matches documents containing a term.
@ -83,7 +82,7 @@ public class TermQueryBuilder extends BaseTermQueryBuilder<TermQueryBuilder> {
super(in); super(in);
} }
public static Optional<TermQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static TermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String queryName = null; String queryName = null;
@ -132,7 +131,7 @@ public class TermQueryBuilder extends BaseTermQueryBuilder<TermQueryBuilder> {
if (queryName != null) { if (queryName != null) {
termQuery.queryName(queryName); termQuery.queryName(queryName);
} }
return Optional.of(termQuery); return termQuery;
} }
@Override @Override

View File

@ -48,7 +48,6 @@ import java.util.Collections;
import java.util.HashSet; import java.util.HashSet;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import java.util.Set; import java.util.Set;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.IntStream; import java.util.stream.IntStream;
@ -321,7 +320,7 @@ public class TermsQueryBuilder extends AbstractQueryBuilder<TermsQueryBuilder> {
builder.endObject(); builder.endObject();
} }
public static Optional<TermsQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static TermsQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
@ -372,9 +371,9 @@ public class TermsQueryBuilder extends AbstractQueryBuilder<TermsQueryBuilder> {
throw new ParsingException(parser.getTokenLocation(), "[" + TermsQueryBuilder.NAME + "] query requires a field name, " + throw new ParsingException(parser.getTokenLocation(), "[" + TermsQueryBuilder.NAME + "] query requires a field name, " +
"followed by array of terms or a document lookup specification"); "followed by array of terms or a document lookup specification");
} }
return Optional.of(new TermsQueryBuilder(fieldName, values, termsLookup) return new TermsQueryBuilder(fieldName, values, termsLookup)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
private static List<Object> parseValues(XContentParser parser) throws IOException { private static List<Object> parseValues(XContentParser parser) throws IOException {

View File

@ -33,7 +33,6 @@ import org.elasticsearch.index.mapper.DocumentMapper;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> { public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> {
public static final String NAME = "type"; public static final String NAME = "type";
@ -81,7 +80,7 @@ public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> {
builder.endObject(); builder.endObject();
} }
public static Optional<TypeQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static TypeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
BytesRef type = null; BytesRef type = null;
@ -114,9 +113,9 @@ public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),
"[" + TypeQueryBuilder.NAME + "] filter needs to be provided with a value for the type"); "[" + TypeQueryBuilder.NAME + "] filter needs to be provided with a value for the type");
} }
return Optional.of(new TypeQueryBuilder(type) return new TypeQueryBuilder(type)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }

View File

@ -36,7 +36,6 @@ import org.elasticsearch.index.query.support.QueryParsers;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Implements the wildcard search query. Supported wildcards are <tt>*</tt>, which * Implements the wildcard search query. Supported wildcards are <tt>*</tt>, which
@ -133,7 +132,7 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
builder.endObject(); builder.endObject();
} }
public static Optional<WildcardQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static WildcardQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
String fieldName = null; String fieldName = null;
String rewrite = null; String rewrite = null;
@ -177,10 +176,10 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
} }
} }
return Optional.of(new WildcardQueryBuilder(fieldName, value) return new WildcardQueryBuilder(fieldName, value)
.rewrite(rewrite) .rewrite(rewrite)
.boost(boost) .boost(boost)
.queryName(queryName)); .queryName(queryName);
} }
@Override @Override

View File

@ -34,7 +34,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException; import java.io.IOException;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.util.Arrays; import java.util.Arrays;
import java.util.Optional;
/** /**
* A Query builder which allows building a query given JSON string or binary data provided as input. This is useful when you want * A Query builder which allows building a query given JSON string or binary data provided as input. This is useful when you want
@ -116,7 +115,7 @@ public class WrapperQueryBuilder extends AbstractQueryBuilder<WrapperQueryBuilde
builder.endObject(); builder.endObject();
} }
public static Optional<WrapperQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static WrapperQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken(); XContentParser.Token token = parser.nextToken();
@ -136,7 +135,7 @@ public class WrapperQueryBuilder extends AbstractQueryBuilder<WrapperQueryBuilde
if (source == null) { if (source == null) {
throw new ParsingException(parser.getTokenLocation(), "wrapper query has no [query] specified"); throw new ParsingException(parser.getTokenLocation(), "wrapper query has no [query] specified");
} }
return Optional.of(new WrapperQueryBuilder(source)); return new WrapperQueryBuilder(source);
} }
@Override @Override
@ -164,8 +163,7 @@ public class WrapperQueryBuilder extends AbstractQueryBuilder<WrapperQueryBuilde
try (XContentParser qSourceParser = XContentFactory.xContent(source).createParser(source)) { try (XContentParser qSourceParser = XContentFactory.xContent(source).createParser(source)) {
QueryParseContext parseContext = context.newParseContext(qSourceParser); QueryParseContext parseContext = context.newParseContext(qSourceParser);
final QueryBuilder queryBuilder = parseContext.parseInnerQueryBuilder().orElseThrow( final QueryBuilder queryBuilder = parseContext.parseInnerQueryBuilder();
() -> new ParsingException(qSourceParser.getTokenLocation(), "inner query cannot be empty"));
if (boost() != DEFAULT_BOOST || queryName() != null) { if (boost() != DEFAULT_BOOST || queryName() != null) {
final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
boolQueryBuilder.must(queryBuilder); boolQueryBuilder.must(queryBuilder);

View File

@ -40,7 +40,6 @@ import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.InnerHitBuilder; import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder; import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryRewriteContext; import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.query.QueryShardContext;
@ -52,7 +51,6 @@ import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A query that uses a filters with a script associated with them to compute the * A query that uses a filters with a script associated with them to compute the
@ -437,7 +435,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
InnerHitBuilder.extractInnerHits(query(), innerHits); InnerHitBuilder.extractInnerHits(query(), innerHits);
} }
public static Optional<FunctionScoreQueryBuilder> fromXContent(ParseFieldRegistry<ScoreFunctionParser<?>> scoreFunctionsRegistry, public static FunctionScoreQueryBuilder fromXContent(ParseFieldRegistry<ScoreFunctionParser<?>> scoreFunctionsRegistry,
QueryParseContext parseContext) throws IOException { QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
@ -467,7 +465,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. [query] is already defined.", throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. [query] is already defined.",
NAME); NAME);
} }
query = parseContext.parseInnerQueryBuilder().orElse(QueryBuilders.matchAllQuery()); query = parseContext.parseInnerQueryBuilder();
} else { } else {
if (singleFunctionFound) { if (singleFunctionFound) {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),
@ -555,7 +553,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
} }
functionScoreQueryBuilder.boost(boost); functionScoreQueryBuilder.boost(boost);
functionScoreQueryBuilder.queryName(queryName); functionScoreQueryBuilder.queryName(queryName);
return Optional.of(functionScoreQueryBuilder); return functionScoreQueryBuilder;
} }
private static void handleMisplacedFunctionsDeclaration(XContentLocation contentLocation, String errorString) { private static void handleMisplacedFunctionsDeclaration(XContentLocation contentLocation, String errorString) {
@ -583,7 +581,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
currentFieldName = parser.currentName(); currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, FILTER_FIELD)) { if (parseContext.getParseFieldMatcher().match(currentFieldName, FILTER_FIELD)) {
filter = parseContext.parseInnerQueryBuilder().orElse(QueryBuilders.matchAllQuery()); filter = parseContext.parseInnerQueryBuilder();
} else { } else {
if (scoreFunction != null) { if (scoreFunction != null) {
throw new ParsingException(parser.getTokenLocation(), throw new ParsingException(parser.getTokenLocation(),

View File

@ -22,7 +22,6 @@ package org.elasticsearch.search.aggregations.bucket.filter;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
@ -86,7 +85,7 @@ public class FilterAggregationBuilder extends AbstractAggregationBuilder<FilterA
} }
public static FilterAggregationBuilder parse(String aggregationName, QueryParseContext context) throws IOException { public static FilterAggregationBuilder parse(String aggregationName, QueryParseContext context) throws IOException {
QueryBuilder filter = context.parseInnerQueryBuilder().orElse(new MatchAllQueryBuilder()); QueryBuilder filter = context.parseInnerQueryBuilder();
return new FilterAggregationBuilder(aggregationName, filter); return new FilterAggregationBuilder(aggregationName, filter);
} }

View File

@ -29,8 +29,8 @@ import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder; import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregatorFactories.Builder; import org.elasticsearch.search.aggregations.AggregatorFactories.Builder;
import org.elasticsearch.search.aggregations.InternalAggregation.Type;
import org.elasticsearch.search.aggregations.AggregatorFactory; import org.elasticsearch.search.aggregations.AggregatorFactory;
import org.elasticsearch.search.aggregations.InternalAggregation.Type;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator.KeyedFilter; import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator.KeyedFilter;
import org.elasticsearch.search.aggregations.support.AggregationContext; import org.elasticsearch.search.aggregations.support.AggregationContext;
@ -41,8 +41,6 @@ import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
public class FiltersAggregationBuilder extends AbstractAggregationBuilder<FiltersAggregationBuilder> { public class FiltersAggregationBuilder extends AbstractAggregationBuilder<FiltersAggregationBuilder> {
public static final String NAME = "filters"; public static final String NAME = "filters";
private static final Type TYPE = new Type(NAME); private static final Type TYPE = new Type(NAME);
@ -240,7 +238,7 @@ public class FiltersAggregationBuilder extends AbstractAggregationBuilder<Filter
if (token == XContentParser.Token.FIELD_NAME) { if (token == XContentParser.Token.FIELD_NAME) {
key = parser.currentName(); key = parser.currentName();
} else { } else {
QueryBuilder filter = context.parseInnerQueryBuilder().orElse(matchAllQuery()); QueryBuilder filter = context.parseInnerQueryBuilder();
keyedFilters.add(new FiltersAggregator.KeyedFilter(key, filter)); keyedFilters.add(new FiltersAggregator.KeyedFilter(key, filter));
} }
} }
@ -252,7 +250,7 @@ public class FiltersAggregationBuilder extends AbstractAggregationBuilder<Filter
if (context.getParseFieldMatcher().match(currentFieldName, FILTERS_FIELD)) { if (context.getParseFieldMatcher().match(currentFieldName, FILTERS_FIELD)) {
nonKeyedFilters = new ArrayList<>(); nonKeyedFilters = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) { while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
QueryBuilder filter = context.parseInnerQueryBuilder().orElse(matchAllQuery()); QueryBuilder filter = context.parseInnerQueryBuilder();
nonKeyedFilters.add(filter); nonKeyedFilters.add(filter);
} }
} else { } else {

View File

@ -77,7 +77,7 @@ public class SignificantTermsAggregationBuilder extends ValuesSourceAggregationB
parser.declareString(SignificantTermsAggregationBuilder::executionHint, TermsAggregationBuilder.EXECUTION_HINT_FIELD_NAME); parser.declareString(SignificantTermsAggregationBuilder::executionHint, TermsAggregationBuilder.EXECUTION_HINT_FIELD_NAME);
parser.declareObject((b, v) -> { if (v.isPresent()) b.backgroundFilter(v.get()); }, parser.declareObject(SignificantTermsAggregationBuilder::backgroundFilter,
(p, context) -> context.parseInnerQueryBuilder(), (p, context) -> context.parseInnerQueryBuilder(),
SignificantTermsAggregationBuilder.BACKGROUND_FILTER); SignificantTermsAggregationBuilder.BACKGROUND_FILTER);

View File

@ -991,9 +991,9 @@ public final class SearchSourceBuilder extends ToXContentToBytes implements Writ
} }
} else if (token == XContentParser.Token.START_OBJECT) { } else if (token == XContentParser.Token.START_OBJECT) {
if (context.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) { if (context.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
queryBuilder = context.parseInnerQueryBuilder().orElse(null); queryBuilder = context.parseInnerQueryBuilder();
} else if (context.getParseFieldMatcher().match(currentFieldName, POST_FILTER_FIELD)) { } else if (context.getParseFieldMatcher().match(currentFieldName, POST_FILTER_FIELD)) {
postQueryBuilder = context.parseInnerQueryBuilder().orElse(null); postQueryBuilder = context.parseInnerQueryBuilder();
} else if (context.getParseFieldMatcher().match(currentFieldName, _SOURCE_FIELD)) { } else if (context.getParseFieldMatcher().match(currentFieldName, _SOURCE_FIELD)) {
fetchSourceContext = FetchSourceContext.parse(context.parser()); fetchSourceContext = FetchSourceContext.parse(context.parser());
} else if (context.getParseFieldMatcher().match(currentFieldName, SCRIPT_FIELDS_FIELD)) { } else if (context.getParseFieldMatcher().match(currentFieldName, SCRIPT_FIELDS_FIELD)) {

View File

@ -539,7 +539,7 @@ public abstract class AbstractHighlighterBuilder<HB extends AbstractHighlighterB
}, OPTIONS_FIELD); }, OPTIONS_FIELD);
parser.declareObject(HB::highlightQuery, (XContentParser p, QueryParseContext c) -> { parser.declareObject(HB::highlightQuery, (XContentParser p, QueryParseContext c) -> {
try { try {
return c.parseInnerQueryBuilder().orElse(null); return c.parseInnerQueryBuilder();
} catch (IOException e) { } catch (IOException e) {
throw new RuntimeException("Error parsing query", e); throw new RuntimeException("Error parsing query", e);
} }

View File

@ -38,7 +38,6 @@ import org.elasticsearch.search.Scroll;
import org.elasticsearch.search.builder.SearchSourceBuilder; import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
/** /**
@ -110,11 +109,7 @@ public interface ShardSearchRequest {
try { try {
byte[] filterSource = alias.filter().uncompressed(); byte[] filterSource = alias.filter().uncompressed();
try (XContentParser parser = XContentFactory.xContent(filterSource).createParser(filterSource)) { try (XContentParser parser = XContentFactory.xContent(filterSource).createParser(filterSource)) {
Optional<QueryBuilder> innerQueryBuilder = contextFactory.apply(parser).parseInnerQueryBuilder(); return contextFactory.apply(parser).parseInnerQueryBuilder();
if (innerQueryBuilder.isPresent()) {
return innerQueryBuilder.get();
}
return null;
} }
} catch (IOException ex) { } catch (IOException ex) {
throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex); throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex);

View File

@ -26,7 +26,6 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser; import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.rescore.QueryRescorer.QueryRescoreContext; import org.elasticsearch.search.rescore.QueryRescorer.QueryRescoreContext;
@ -57,7 +56,7 @@ public class QueryRescorerBuilder extends RescoreBuilder<QueryRescorerBuilder> {
static { static {
QUERY_RESCORE_PARSER.declareObject(InnerBuilder::setQueryBuilder, (p, c) -> { QUERY_RESCORE_PARSER.declareObject(InnerBuilder::setQueryBuilder, (p, c) -> {
try { try {
return c.parseInnerQueryBuilder().orElse(QueryBuilders.matchAllQuery()); return c.parseInnerQueryBuilder();
} catch (IOException e) { } catch (IOException e) {
throw new ParsingException(p.getTokenLocation(), "Could not parse inner query", e); throw new ParsingException(p.getTokenLocation(), "Could not parse inner query", e);
} }

View File

@ -62,7 +62,6 @@ import java.util.Arrays;
import java.util.List; import java.util.List;
import java.util.Locale; import java.util.Locale;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* A geo distance based sorting on a geo point like field. * A geo distance based sorting on a geo point like field.
@ -408,7 +407,7 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
GeoDistance geoDistance = GeoDistance.DEFAULT; GeoDistance geoDistance = GeoDistance.DEFAULT;
SortOrder order = SortOrder.ASC; SortOrder order = SortOrder.ASC;
SortMode sortMode = null; SortMode sortMode = null;
Optional<QueryBuilder> nestedFilter = Optional.empty(); QueryBuilder nestedFilter = null;
String nestedPath = null; String nestedPath = null;
boolean coerce = GeoValidationMethod.DEFAULT_LENIENT_PARSING; boolean coerce = GeoValidationMethod.DEFAULT_LENIENT_PARSING;
@ -493,7 +492,9 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
if (sortMode != null) { if (sortMode != null) {
result.sortMode(sortMode); result.sortMode(sortMode);
} }
nestedFilter.ifPresent(result::setNestedFilter); if (nestedFilter != null) {
result.setNestedFilter(nestedFilter);
}
result.setNestedPath(nestedPath); result.setNestedPath(nestedPath);
if (validation == null) { if (validation == null) {
// looks like either validation was left unset or we are parsing old validation json // looks like either validation was left unset or we are parsing old validation json

View File

@ -203,9 +203,7 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
protected static QueryBuilder parseNestedFilter(XContentParser parser, QueryParseContext context) { protected static QueryBuilder parseNestedFilter(XContentParser parser, QueryParseContext context) {
try { try {
QueryBuilder builder = context.parseInnerQueryBuilder().orElseThrow(() -> new ParsingException(parser.getTokenLocation(), return context.parseInnerQueryBuilder();
"Expected " + NESTED_FILTER_FIELD.getPreferredName() + " element."));
return builder;
} catch (Exception e) { } catch (Exception e) {
throw new ParsingException(parser.getTokenLocation(), "Expected " + NESTED_FILTER_FIELD.getPreferredName() + " element.", e); throw new ParsingException(parser.getTokenLocation(), "Expected " + NESTED_FILTER_FIELD.getPreferredName() + " element.", e);
} }

View File

@ -34,14 +34,11 @@ import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.text.Text; import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.MatchNoneQueryBuilder;
import org.elasticsearch.index.query.ParsedQuery; import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.script.CompiledScript;
import org.elasticsearch.script.ExecutableScript; import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.ScriptService;
import org.elasticsearch.search.suggest.Suggest.Suggestion; import org.elasticsearch.search.suggest.Suggest.Suggestion;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry; import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option; import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry.Option;
@ -54,7 +51,6 @@ import java.io.IOException;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import java.util.function.Function; import java.util.function.Function;
public final class PhraseSuggester extends Suggester<PhraseSuggestionContext> { public final class PhraseSuggester extends Suggester<PhraseSuggestionContext> {
@ -125,8 +121,8 @@ public final class PhraseSuggester extends Suggester<PhraseSuggestionContext> {
final ExecutableScript executable = collateScript.apply(vars); final ExecutableScript executable = collateScript.apply(vars);
final BytesReference querySource = (BytesReference) executable.run(); final BytesReference querySource = (BytesReference) executable.run();
try (XContentParser parser = XContentFactory.xContent(querySource).createParser(querySource)) { try (XContentParser parser = XContentFactory.xContent(querySource).createParser(querySource)) {
Optional<QueryBuilder> innerQueryBuilder = shardContext.newParseContext(parser).parseInnerQueryBuilder(); QueryBuilder innerQueryBuilder = shardContext.newParseContext(parser).parseInnerQueryBuilder();
final ParsedQuery parsedQuery = shardContext.toQuery(innerQueryBuilder.orElse(new MatchNoneQueryBuilder())); final ParsedQuery parsedQuery = shardContext.toQuery(innerQueryBuilder);
collateMatch = Lucene.exists(searcher, parsedQuery.query()); collateMatch = Lucene.exists(searcher, parsedQuery.query());
} }
} }

View File

@ -145,7 +145,9 @@ public class IndexAliasesIT extends ESIntegTestCase {
ensureGreen(); ensureGreen();
logger.info("--> aliasing index [test] with [alias1] and empty filter"); logger.info("--> aliasing index [test] with [alias1] and empty filter");
assertAcked(admin().indices().prepareAliases().addAlias("test", "alias1", "{}")); IllegalArgumentException iae = expectThrows(IllegalArgumentException.class,
() -> admin().indices().prepareAliases().addAlias("test", "alias1", "{}").get());
assertEquals("failed to parse filter for alias [alias1]", iae.getMessage());
} }
public void testSearchingFilteringAliasesSingleIndex() throws Exception { public void testSearchingFilteringAliasesSingleIndex() throws Exception {

View File

@ -46,7 +46,6 @@ import static org.elasticsearch.index.query.QueryBuilders.constantScoreQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.startsWith;
public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilder> { public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilder> {
@Override @Override
@ -330,34 +329,6 @@ public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilde
assertEquals(query, "kimchy", ((TermQueryBuilder)queryBuilder.must().get(0)).value()); assertEquals(query, "kimchy", ((TermQueryBuilder)queryBuilder.must().get(0)).value());
} }
/**
* we ignore empty query bodies if we are not in strict mode
*/
public void testFromJsonEmptyQueryBody() throws IOException {
String query =
"{" +
"\"bool\" : {" +
" \"must\" : [ { } ]," +
" \"filter\" : { }," +
" \"must_not\" : [ { \"constant_score\" : {\"filter\" : { } } } ]" +
"}" +
"}";
BoolQueryBuilder queryBuilder = (BoolQueryBuilder) parseQuery(query, ParseFieldMatcher.EMPTY);
assertEquals(query, 0, queryBuilder.must().size());
assertEquals(query, 0, queryBuilder.filter().size());
assertEquals(query, 0, queryBuilder.mustNot().size());
assertEquals(query, 0, queryBuilder.should().size());
// we should have deprecation warning headers regardless of throwing an exception
checkWarningHeaders("query malformed, empty clause found at [1:27]",
"query malformed, empty clause found at [1:46]",
"query malformed, empty clause found at [1:100]");
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> parseQuery(query, ParseFieldMatcher.STRICT));
assertThat(ex.getMessage(), startsWith("query malformed, empty clause found at"));
checkWarningHeaders("query malformed, empty clause found at [1:27]");
}
/** /**
* test that unknown query names in the clauses throw an error * test that unknown query names in the clauses throw an error
*/ */

View File

@ -21,18 +21,13 @@ package org.elasticsearch.index.query;
import org.apache.lucene.queries.BoostingQuery; import org.apache.lucene.queries.BoostingQuery;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase; import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue;; import static org.hamcrest.CoreMatchers.nullValue;
public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQueryBuilder> { public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQueryBuilder> {
@ -94,45 +89,6 @@ public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQue
assertEquals(query, 5, queryBuilder.positiveQuery().boost(), 0.00001); assertEquals(query, 5, queryBuilder.positiveQuery().boost(), 0.00001);
} }
/**
* we bubble up empty inner clauses as an empty optional
*/
public void testFromJsonEmptyQueryBody() throws IOException {
String query =
"{ \"boosting\" : {" +
" \"positive\" : { }, " +
" \"negative\" : { \"match_all\" : {} }, " +
" \"negative_boost\" : 23.0" +
" }" +
"}";
XContentParser parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext context = createParseContext(parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [1:36]");
query =
"{ \"boosting\" : {\n" +
" \"positive\" : { \"match_all\" : {} },\n" +
" \"negative\" : { },\n" +
" \"negative_boost\" : 23.0\n" +
" }\n" +
"}";
parser = XContentFactory.xContent(query).createParser(query);
context = createParseContext(parser, ParseFieldMatcher.EMPTY);
innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [3:20]");
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [3:20]"));
checkWarningHeaders("query malformed, empty clause found at [3:20]");
}
public void testRewrite() throws IOException { public void testRewrite() throws IOException {
QueryBuilder positive = randomBoolean() ? new MatchAllQueryBuilder() : new WrapperQueryBuilder(new TermQueryBuilder("pos", "bar").toString()); QueryBuilder positive = randomBoolean() ? new MatchAllQueryBuilder() : new WrapperQueryBuilder(new TermQueryBuilder("pos", "bar").toString());
QueryBuilder negative = randomBoolean() ? new MatchAllQueryBuilder() : new WrapperQueryBuilder(new TermQueryBuilder("neg", "bar").toString()); QueryBuilder negative = randomBoolean() ? new MatchAllQueryBuilder() : new WrapperQueryBuilder(new TermQueryBuilder("neg", "bar").toString());

View File

@ -21,17 +21,12 @@ package org.elasticsearch.index.query;
import org.apache.lucene.search.ConstantScoreQuery; import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase; import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.CoreMatchers.nullValue;
import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.containsString;
@ -119,27 +114,4 @@ public class ConstantScoreQueryBuilderTests extends AbstractQueryTestCase<Consta
assertEquals(json, 23.0, parsed.boost(), 0.0001); assertEquals(json, 23.0, parsed.boost(), 0.0001);
assertEquals(json, 42.0, parsed.innerQuery().boost(), 0.0001); assertEquals(json, 42.0, parsed.innerQuery().boost(), 0.0001);
} }
/**
* we bubble up empty query bodies as an empty optional
*/
public void testFromJsonEmptyQueryBody() throws IOException {
String query =
"{ \"constant_score\" : {" +
" \"filter\" : { }" +
" }" +
"}";
XContentParser parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext context = createParseContext(parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [1:40]");
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [1:40]"));
checkWarningHeaders("query malformed, empty clause found at [1:40]");
}
} }

View File

@ -22,10 +22,8 @@ package org.elasticsearch.index.query;
import org.apache.lucene.index.Term; import org.apache.lucene.index.Term;
import org.apache.lucene.search.BoostQuery; import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.DisjunctionMaxQuery; import org.apache.lucene.search.DisjunctionMaxQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.PrefixQuery; import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
import org.elasticsearch.test.AbstractQueryTestCase; import org.elasticsearch.test.AbstractQueryTestCase;
@ -85,23 +83,6 @@ public class DisMaxQueryBuilderTests extends AbstractQueryTestCase<DisMaxQueryBu
return alternateVersions; return alternateVersions;
} }
/**
* Test with empty inner query body, this should be converted to a {@link MatchNoDocsQuery}.
* To test this, we use inner {@link ConstantScoreQueryBuilder} with empty inner filter.
*/
public void testInnerQueryEmptyException() throws IOException {
String queryString = "{ \"" + DisMaxQueryBuilder.NAME + "\" :"
+ " { \"queries\" : [ {\"" + ConstantScoreQueryBuilder.NAME + "\" : { \"filter\" : { } } } ] "
+ " }"
+ " }";
QueryBuilder queryBuilder = parseQuery(queryString, ParseFieldMatcher.EMPTY);
QueryShardContext context = createShardContext();
Query luceneQuery = queryBuilder.toQuery(context);
assertThat(luceneQuery, instanceOf(MatchNoDocsQuery.class));
assertThat(luceneQuery.toString(), equalTo("MatchNoDocsQuery(\"no clauses for dismax query.\")"));
checkWarningHeaders("query malformed, empty clause found at [1:78]");
}
public void testIllegalArguments() { public void testIllegalArguments() {
DisMaxQueryBuilder disMaxQuery = new DisMaxQueryBuilder(); DisMaxQueryBuilder disMaxQuery = new DisMaxQueryBuilder();
expectThrows(IllegalArgumentException.class, () -> disMaxQuery.add(null)); expectThrows(IllegalArgumentException.class, () -> disMaxQuery.add(null));

View File

@ -20,7 +20,6 @@
package org.elasticsearch.index.query; package org.elasticsearch.index.query;
import com.carrotsearch.randomizedtesting.generators.RandomPicks; import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import org.apache.lucene.queries.TermsQuery; import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.search.BooleanClause; import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery; import org.apache.lucene.search.BooleanQuery;
@ -33,11 +32,8 @@ import org.apache.lucene.search.similarities.PerFieldSimilarityWrapper;
import org.apache.lucene.search.similarities.Similarity; import org.apache.lucene.search.similarities.Similarity;
import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.BytesRef;
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.TypeFieldMapper; import org.elasticsearch.index.mapper.TypeFieldMapper;
import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.Uid;
@ -53,7 +49,6 @@ import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
@ -223,28 +218,6 @@ public class HasChildQueryBuilderTests extends AbstractQueryTestCase<HasChildQue
assertEquals(query, queryBuilder.innerHit(), expected); assertEquals(query, queryBuilder.innerHit(), expected);
} }
/**
* we resolve empty inner clauses by representing this whole query as empty optional upstream
*/
public void testFromJsonEmptyQueryBody() throws IOException {
String query = "{\n" +
" \"has_child\" : {\n" +
" \"query\" : { },\n" +
" \"type\" : \"child\"" +
" }" +
"}";
XContentParser parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext context = createParseContext(parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [3:17]"));
checkWarningHeaders("query malformed, empty clause found at [3:17]");
}
public void testToQueryInnerQueryType() throws IOException { public void testToQueryInnerQueryType() throws IOException {
String[] searchTypes = new String[]{PARENT_TYPE}; String[] searchTypes = new String[]{PARENT_TYPE};
QueryShardContext shardContext = createShardContext(); QueryShardContext shardContext = createShardContext();

View File

@ -28,7 +28,6 @@ import org.elasticsearch.common.compress.CompressedXContent;
import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.search.fetch.subphase.InnerHitsContext; import org.elasticsearch.search.fetch.subphase.InnerHitsContext;
import org.elasticsearch.search.internal.SearchContext; import org.elasticsearch.search.internal.SearchContext;
@ -39,7 +38,6 @@ import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException; import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.Optional;
import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.equalTo;
@ -206,30 +204,6 @@ public class HasParentQueryBuilderTests extends AbstractQueryTestCase<HasParentQ
assertEquals(json, "something", ((TermQueryBuilder) parsed.query()).value()); assertEquals(json, "something", ((TermQueryBuilder) parsed.query()).value());
} }
/**
* we resolve empty inner clauses by representing this whole query as empty optional upstream
*/
public void testFromJsonEmptyQueryBody() throws IOException {
String query = "{\n" +
" \"has_parent\" : {\n" +
" \"query\" : { },\n" +
" \"parent_type\" : \"blog\"" +
" }" +
"}";
XContentParser parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext context = createParseContext(parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> innerQueryBuilder = context.parseInnerQueryBuilder();
assertTrue(innerQueryBuilder.isPresent() == false);
checkWarningHeaders("query malformed, empty clause found at [3:17]");
parser = XContentFactory.xContent(query).createParser(query);
QueryParseContext otherContext = createParseContext(parser, ParseFieldMatcher.STRICT);
IllegalArgumentException ex = expectThrows(IllegalArgumentException.class, () -> otherContext.parseInnerQueryBuilder());
assertThat(ex.getMessage(), equalTo("query malformed, empty clause found at [3:17]"));
checkWarningHeaders("query malformed, empty clause found at [3:17]");
}
public void testIgnoreUnmapped() throws IOException { public void testIgnoreUnmapped() throws IOException {
final HasParentQueryBuilder queryBuilder = new HasParentQueryBuilder("unmapped", new MatchAllQueryBuilder(), false); final HasParentQueryBuilder queryBuilder = new HasParentQueryBuilder("unmapped", new MatchAllQueryBuilder(), false);
queryBuilder.ignoreUnmapped(true); queryBuilder.ignoreUnmapped(true);

View File

@ -35,13 +35,8 @@ import org.junit.Before;
import org.junit.BeforeClass; import org.junit.BeforeClass;
import java.io.IOException; import java.io.IOException;
import java.util.List;
import java.util.Optional;
import static java.util.Collections.emptyList; import static java.util.Collections.emptyList;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasSize;
public class QueryParseContextTests extends ESTestCase { public class QueryParseContextTests extends ESTestCase {
@ -99,20 +94,8 @@ public class QueryParseContextTests extends ESTestCase {
String source = query.toString(); String source = query.toString();
try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) { try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) {
QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.STRICT); QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.STRICT);
Optional<QueryBuilder> actual = context.parseInnerQueryBuilder(); QueryBuilder actual = context.parseInnerQueryBuilder();
assertEquals(query, actual.get()); assertEquals(query, actual);
}
}
public void testParseInnerQueryBuilderEmptyBody() throws IOException {
String source = "{}";
try (XContentParser parser = XContentFactory.xContent(source).createParser(source)) {
QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.EMPTY);
Optional<QueryBuilder> emptyQuery = context.parseInnerQueryBuilder();
assertFalse(emptyQuery.isPresent());
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(1));
assertThat(warnings, hasItem(equalTo("query malformed, empty clause found at [1:2]")));
} }
} }
@ -128,12 +111,9 @@ public class QueryParseContextTests extends ESTestCase {
source = "{}"; source = "{}";
try (XContentParser parser = JsonXContent.jsonXContent.createParser(source)) { try (XContentParser parser = JsonXContent.jsonXContent.createParser(source)) {
QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.STRICT); QueryParseContext context = new QueryParseContext(indicesQueriesRegistry, parser, ParseFieldMatcher.EMPTY);
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> context.parseInnerQueryBuilder()); IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> context.parseInnerQueryBuilder());
assertEquals("query malformed, empty clause found at [1:2]", exception.getMessage()); assertEquals("query malformed, empty clause found at [1:2]", exception.getMessage());
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(1));
assertThat(warnings, hasItem(equalTo("query malformed, empty clause found at [1:2]")));
} }
source = "{ \"foo\" : \"bar\" }"; source = "{ \"foo\" : \"bar\" }";
@ -149,9 +129,5 @@ public class QueryParseContextTests extends ESTestCase {
ParsingException exception = expectThrows(ParsingException.class, () -> context.parseInnerQueryBuilder()); ParsingException exception = expectThrows(ParsingException.class, () -> context.parseInnerQueryBuilder());
assertEquals("no [query] registered for [foo]", exception.getMessage()); assertEquals("no [query] registered for [foo]", exception.getMessage());
} }
final List<String> warnings = threadContext.getResponseHeaders().get(DeprecationLogger.DEPRECATION_HEADER);
assertThat(warnings, hasSize(1));
assertThat(warnings, hasItem(equalTo("query malformed, empty clause found at [1:2]")));
} }
} }

View File

@ -30,7 +30,6 @@ import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.plugin.DummyQueryParserPlugin.DummyQuery; import org.elasticsearch.index.query.plugin.DummyQueryParserPlugin.DummyQuery;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
public class DummyQueryBuilder extends AbstractQueryBuilder<DummyQueryBuilder> { public class DummyQueryBuilder extends AbstractQueryBuilder<DummyQueryBuilder> {
public static final String NAME = "dummy"; public static final String NAME = "dummy";
@ -52,10 +51,10 @@ public class DummyQueryBuilder extends AbstractQueryBuilder<DummyQueryBuilder> {
builder.startObject(NAME).endObject(); builder.startObject(NAME).endObject();
} }
public static Optional<DummyQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static DummyQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser.Token token = parseContext.parser().nextToken(); XContentParser.Token token = parseContext.parser().nextToken();
assert token == XContentParser.Token.END_OBJECT; assert token == XContentParser.Token.END_OBJECT;
return Optional.of(new DummyQueryBuilder()); return new DummyQueryBuilder();
} }
@Override @Override

View File

@ -21,17 +21,10 @@ package org.elasticsearch.search.aggregations.bucket;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filter.Filter; import org.elasticsearch.search.aggregations.bucket.filter.Filter;
import org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.ESIntegTestCase;
@ -122,24 +115,6 @@ public class FilterIT extends ESIntegTestCase {
assertThat(filter.getDocCount(), equalTo((long) numDocs)); assertThat(filter.getDocCount(), equalTo((long) numDocs));
} }
/**
* test that "{ "filter" : {} }" is regarded as match_all when not parsing strict
*/
public void testEmptyFilter() throws Exception {
String emtpyFilterBody = "{ }";
XContentParser parser = XContentFactory.xContent(emtpyFilterBody).createParser(emtpyFilterBody);
QueryParseContext parseContext = new QueryParseContext(new IndicesQueriesRegistry(), parser, ParseFieldMatcher.EMPTY);
AggregationBuilder filterAgg = FilterAggregationBuilder.parse("tag1", parseContext);
SearchResponse response = client().prepareSearch("idx").addAggregation(filterAgg).execute().actionGet();
assertSearchResponse(response);
Filter filter = response.getAggregations().get("tag1");
assertThat(filter, notNullValue());
assertThat(filter.getDocCount(), equalTo((long) numDocs));
}
public void testWithSubAggregation() throws Exception { public void testWithSubAggregation() throws Exception {
SearchResponse response = client().prepareSearch("idx") SearchResponse response = client().prepareSearch("idx")
.addAggregation(filter("tag1", termQuery("tag", "tag1")) .addAggregation(filter("tag1", termQuery("tag", "tag1"))

View File

@ -22,17 +22,10 @@ package org.elasticsearch.search.aggregations.bucket;
import org.elasticsearch.ElasticsearchException; import org.elasticsearch.ElasticsearchException;
import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.index.IndexRequestBuilder;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.indices.query.IndicesQueriesRegistry;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filters.Filters; import org.elasticsearch.search.aggregations.bucket.filters.Filters;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator.KeyedFilter; import org.elasticsearch.search.aggregations.bucket.filters.FiltersAggregator.KeyedFilter;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram; import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.aggregations.metrics.avg.Avg; import org.elasticsearch.search.aggregations.metrics.avg.Avg;
@ -205,45 +198,9 @@ public class FiltersIT extends ESIntegTestCase {
assertThat(avgValue, notNullValue()); assertThat(avgValue, notNullValue());
assertThat(avgValue.getName(), equalTo("avg_value")); assertThat(avgValue.getName(), equalTo("avg_value"));
assertThat(avgValue.getValue(), equalTo((double) sum / numTag2Docs)); assertThat(avgValue.getValue(), equalTo((double) sum / numTag2Docs));
assertThat((String) propertiesKeys[1], equalTo("tag2")); assertThat(propertiesKeys[1], equalTo("tag2"));
assertThat((long) propertiesDocCounts[1], equalTo((long) numTag2Docs)); assertThat(propertiesDocCounts[1], equalTo((long) numTag2Docs));
assertThat((double) propertiesCounts[1], equalTo((double) sum / numTag2Docs)); assertThat(propertiesCounts[1], equalTo((double) sum / numTag2Docs));
}
public void testEmptyFilter() throws Exception {
String emtpyFilterBody = "{ \"filters\" : [ {} ] }";
XContentParser parser = XContentFactory.xContent(emtpyFilterBody).createParser(emtpyFilterBody);
parser.nextToken();
QueryParseContext parseContext = new QueryParseContext(new IndicesQueriesRegistry(), parser, ParseFieldMatcher.EMPTY);
AggregationBuilder filtersAgg = FiltersAggregationBuilder.parse("tag1", parseContext);
SearchResponse response = client().prepareSearch("idx").addAggregation(filtersAgg).execute().actionGet();
assertSearchResponse(response);
Filters filter = response.getAggregations().get("tag1");
assertThat(filter, notNullValue());
assertThat(filter.getBuckets().size(), equalTo(1));
assertThat(filter.getBuckets().get(0).getDocCount(), equalTo((long) numDocs));
}
public void testEmptyKeyedFilter() throws Exception {
String emtpyFilterBody = "{ \"filters\" : {\"foo\" : {} } }";
XContentParser parser = XContentFactory.xContent(emtpyFilterBody).createParser(emtpyFilterBody);
parser.nextToken();
QueryParseContext parseContext = new QueryParseContext(new IndicesQueriesRegistry(), parser, ParseFieldMatcher.EMPTY);
AggregationBuilder filtersAgg = FiltersAggregationBuilder.parse("tag1", parseContext);
SearchResponse response = client().prepareSearch("idx").addAggregation(filtersAgg)
.execute().actionGet();
assertSearchResponse(response);
Filters filter = response.getAggregations().get("tag1");
assertThat(filter, notNullValue());
assertThat(filter.getBuckets().size(), equalTo(1));
assertThat(filter.getBuckets().get(0).getKey(), equalTo("foo"));
assertThat(filter.getBuckets().get(0).getDocCount(), equalTo((long) numDocs));
} }
public void testAsSubAggregation() { public void testAsSubAggregation() {
@ -444,9 +401,9 @@ public class FiltersIT extends ESIntegTestCase {
assertThat(avgValue, notNullValue()); assertThat(avgValue, notNullValue());
assertThat(avgValue.getName(), equalTo("avg_value")); assertThat(avgValue.getName(), equalTo("avg_value"));
assertThat(avgValue.getValue(), equalTo((double) sum / numTag1Docs)); assertThat(avgValue.getValue(), equalTo((double) sum / numTag1Docs));
assertThat((String) propertiesKeys[0], equalTo("tag1")); assertThat(propertiesKeys[0], equalTo("tag1"));
assertThat((long) propertiesDocCounts[0], equalTo((long) numTag1Docs)); assertThat(propertiesDocCounts[0], equalTo((long) numTag1Docs));
assertThat((double) propertiesCounts[0], equalTo((double) sum / numTag1Docs)); assertThat(propertiesCounts[0], equalTo((double) sum / numTag1Docs));
bucket = filters.getBucketByKey("tag2"); bucket = filters.getBucketByKey("tag2");
assertThat(bucket, Matchers.notNullValue()); assertThat(bucket, Matchers.notNullValue());
@ -460,9 +417,9 @@ public class FiltersIT extends ESIntegTestCase {
assertThat(avgValue, notNullValue()); assertThat(avgValue, notNullValue());
assertThat(avgValue.getName(), equalTo("avg_value")); assertThat(avgValue.getName(), equalTo("avg_value"));
assertThat(avgValue.getValue(), equalTo((double) sum / numTag2Docs)); assertThat(avgValue.getValue(), equalTo((double) sum / numTag2Docs));
assertThat((String) propertiesKeys[1], equalTo("tag2")); assertThat(propertiesKeys[1], equalTo("tag2"));
assertThat((long) propertiesDocCounts[1], equalTo((long) numTag2Docs)); assertThat(propertiesDocCounts[1], equalTo((long) numTag2Docs));
assertThat((double) propertiesCounts[1], equalTo((double) sum / numTag2Docs)); assertThat(propertiesCounts[1], equalTo((double) sum / numTag2Docs));
bucket = filters.getBucketByKey("_other_"); bucket = filters.getBucketByKey("_other_");
assertThat(bucket, Matchers.notNullValue()); assertThat(bucket, Matchers.notNullValue());
@ -476,9 +433,9 @@ public class FiltersIT extends ESIntegTestCase {
assertThat(avgValue, notNullValue()); assertThat(avgValue, notNullValue());
assertThat(avgValue.getName(), equalTo("avg_value")); assertThat(avgValue.getName(), equalTo("avg_value"));
assertThat(avgValue.getValue(), equalTo((double) sum / numOtherDocs)); assertThat(avgValue.getValue(), equalTo((double) sum / numOtherDocs));
assertThat((String) propertiesKeys[2], equalTo("_other_")); assertThat(propertiesKeys[2], equalTo("_other_"));
assertThat((long) propertiesDocCounts[2], equalTo((long) numOtherDocs)); assertThat(propertiesDocCounts[2], equalTo((long) numOtherDocs));
assertThat((double) propertiesCounts[2], equalTo((double) sum / numOtherDocs)); assertThat(propertiesCounts[2], equalTo((double) sum / numOtherDocs));
} }
public void testEmptyAggregationWithOtherBucket() throws Exception { public void testEmptyAggregationWithOtherBucket() throws Exception {

View File

@ -22,7 +22,6 @@ package org.elasticsearch.search.builder;
import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException; import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.bytes.BytesArray;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.BytesStreamOutput;
import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput; import org.elasticsearch.common.io.stream.NamedWriteableAwareStreamInput;
@ -315,16 +314,4 @@ public class SearchSourceBuilderTests extends AbstractSearchTestCase {
assertEquals("query", sourceAsMap.keySet().iterator().next()); assertEquals("query", sourceAsMap.keySet().iterator().next());
} }
} }
public void testEmptyPostFilter() throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
String query = "{ \"post_filter\": {} }";
assertParseSearchSource(builder, new BytesArray(query), ParseFieldMatcher.EMPTY);
}
public void testEmptyQuery() throws IOException {
SearchSourceBuilder builder = new SearchSourceBuilder();
String query = "{ \"query\": {} }";
assertParseSearchSource(builder, new BytesArray(query), ParseFieldMatcher.EMPTY);
}
} }

View File

@ -23,6 +23,9 @@
* The deprecated `indices` query has been removed. * The deprecated `indices` query has been removed.
* Support for empty query objects (`{ }`) has been removed from the query DSL.
An error is thrown whenever an empty query object is provided.
==== Search shards API ==== Search shards API
The search shards API no longer accepts the `type` url parameter, which didn't The search shards API no longer accepts the `type` url parameter, which didn't

View File

@ -19,7 +19,6 @@
package org.elasticsearch.script.mustache; package org.elasticsearch.script.mustache;
import org.apache.lucene.search.Query; import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.StreamOutput;
@ -42,7 +41,6 @@ import java.io.IOException;
import java.util.Collections; import java.util.Collections;
import java.util.Map; import java.util.Map;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
/** /**
* Facilitates creating template query requests. * Facilitates creating template query requests.
@ -122,8 +120,7 @@ public class TemplateQueryBuilder extends AbstractQueryBuilder<TemplateQueryBuil
BytesReference querySource = queryRewriteContext.getTemplateBytes(template); BytesReference querySource = queryRewriteContext.getTemplateBytes(template);
try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) { try (XContentParser qSourceParser = XContentFactory.xContent(querySource).createParser(querySource)) {
final QueryParseContext queryParseContext = queryRewriteContext.newParseContext(qSourceParser); final QueryParseContext queryParseContext = queryRewriteContext.newParseContext(qSourceParser);
final QueryBuilder queryBuilder = queryParseContext.parseInnerQueryBuilder().orElseThrow( final QueryBuilder queryBuilder = queryParseContext.parseInnerQueryBuilder();
() -> new ParsingException(qSourceParser.getTokenLocation(), "inner query in [" + NAME + "] cannot be empty"));
if (boost() != DEFAULT_BOOST || queryName() != null) { if (boost() != DEFAULT_BOOST || queryName() != null) {
final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder(); final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
boolQueryBuilder.must(queryBuilder); boolQueryBuilder.must(queryBuilder);
@ -137,9 +134,9 @@ public class TemplateQueryBuilder extends AbstractQueryBuilder<TemplateQueryBuil
* In the simplest case, parse template string and variables from the request, * In the simplest case, parse template string and variables from the request,
* compile the template and execute the template against the given variables. * compile the template and execute the template against the given variables.
*/ */
public static Optional<TemplateQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static TemplateQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
Script template = Script.parse(parser, parseContext.getParseFieldMatcher(), "mustache"); Script template = Script.parse(parser, parseContext.getParseFieldMatcher(), "mustache");
return Optional.of(new TemplateQueryBuilder(template)); return new TemplateQueryBuilder(template);
} }
} }

View File

@ -75,7 +75,6 @@ import org.elasticsearch.index.query.QueryShardException;
import java.io.IOException; import java.io.IOException;
import java.util.Objects; import java.util.Objects;
import java.util.Optional;
import static org.elasticsearch.index.mapper.SourceToParse.source; import static org.elasticsearch.index.mapper.SourceToParse.source;
import static org.elasticsearch.percolator.PercolatorFieldMapper.parseQuery; import static org.elasticsearch.percolator.PercolatorFieldMapper.parseQuery;
@ -233,7 +232,7 @@ public class PercolateQueryBuilder extends AbstractQueryBuilder<PercolateQueryBu
builder.endObject(); builder.endObject();
} }
public static Optional<PercolateQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException { public static PercolateQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
float boost = AbstractQueryBuilder.DEFAULT_BOOST; float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -314,7 +313,7 @@ public class PercolateQueryBuilder extends AbstractQueryBuilder<PercolateQueryBu
} }
queryBuilder.queryName(queryName); queryBuilder.queryName(queryName);
queryBuilder.boost(boost); queryBuilder.boost(boost);
return Optional.of(queryBuilder); return queryBuilder;
} }
@Override @Override

View File

@ -345,8 +345,7 @@ public class PercolatorFieldMapper extends FieldMapper {
private static QueryBuilder parseQueryBuilder(QueryParseContext context, XContentLocation location) { private static QueryBuilder parseQueryBuilder(QueryParseContext context, XContentLocation location) {
try { try {
return context.parseInnerQueryBuilder() return context.parseInnerQueryBuilder();
.orElseThrow(() -> new ParsingException(location, "Failed to parse inner query, was empty"));
} catch (IOException e) { } catch (IOException e) {
throw new ParsingException(location, "Failed to parse", e); throw new ParsingException(location, "Failed to parse", e);
} }

View File

@ -209,7 +209,7 @@ public class TransportPercolateAction extends HandledTransportAction<PercolateRe
try (XContentParser parser = XContentHelper.createParser(querySource)) { try (XContentParser parser = XContentHelper.createParser(querySource)) {
QueryParseContext queryParseContext = new QueryParseContext(queryRegistry, parser, parseFieldMatcher); QueryParseContext queryParseContext = new QueryParseContext(queryRegistry, parser, parseFieldMatcher);
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery(); BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
queryParseContext.parseInnerQueryBuilder().ifPresent(boolQueryBuilder::must); boolQueryBuilder.must(queryParseContext.parseInnerQueryBuilder());
boolQueryBuilder.filter(percolateQueryBuilder); boolQueryBuilder.filter(percolateQueryBuilder);
searchSource.field("query", boolQueryBuilder); searchSource.field("query", boolQueryBuilder);
} }

View File

@ -480,10 +480,9 @@ public class PercolatorFieldMapperTests extends ESSingleNodeTestCase {
QueryParseContext qsc = indexService.newQueryShardContext( QueryParseContext qsc = indexService.newQueryShardContext(
randomInt(20), null, () -> { throw new UnsupportedOperationException(); }) randomInt(20), null, () -> { throw new UnsupportedOperationException(); })
.newParseContext(sourceParser); .newParseContext(sourceParser);
assertThat(qsc.parseInnerQueryBuilder().get(), equalTo(expected)); assertThat(qsc.parseInnerQueryBuilder(), equalTo(expected));
} }
public void testEmptyName() throws Exception { public void testEmptyName() throws Exception {
// after 5.x // after 5.x
String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1")

View File

@ -33,7 +33,6 @@ import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext; import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException; import java.io.IOException;
import java.util.Optional;
/** /**
* A query that performs a <code>match_all</code> query, but with each <em>index</em> touched getting a unique deprecation warning. * A query that performs a <code>match_all</code> query, but with each <em>index</em> touched getting a unique deprecation warning.
@ -66,14 +65,14 @@ public class TestDeprecatedQueryBuilder extends AbstractQueryBuilder<TestDepreca
builder.startObject(NAME).endObject(); builder.startObject(NAME).endObject();
} }
public static Optional<TestDeprecatedQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException, ParsingException { public static TestDeprecatedQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser(); XContentParser parser = parseContext.parser();
if (parser.nextToken() != XContentParser.Token.END_OBJECT) { if (parser.nextToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[{}] query does not have any fields", NAME); throw new ParsingException(parser.getTokenLocation(), "[{}] query does not have any fields", NAME);
} }
return Optional.of(new TestDeprecatedQueryBuilder()); return new TestDeprecatedQueryBuilder();
} }
@Override @Override

View File

@ -591,8 +591,7 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
private static QueryBuilder parseQuery(XContentParser parser, ParseFieldMatcher matcher) throws IOException { private static QueryBuilder parseQuery(XContentParser parser, ParseFieldMatcher matcher) throws IOException {
QueryParseContext context = createParseContext(parser, matcher); QueryParseContext context = createParseContext(parser, matcher);
QueryBuilder parseInnerQueryBuilder = context.parseInnerQueryBuilder() QueryBuilder parseInnerQueryBuilder = context.parseInnerQueryBuilder();
.orElseThrow(() -> new IllegalArgumentException("inner query body cannot be empty"));
assertNull(parser.nextToken()); assertNull(parser.nextToken());
return parseInnerQueryBuilder; return parseInnerQueryBuilder;
} }