Remove QueryParseContext from parsing QueryBuilders (#25448)

Currently QueryParseContext is only a thin wrapper around an XContentParser that
adds little functionality of its own. I provides helpers for long deprecated
field names which can be removed and two helper methods that can be made static
and moved to other classes. This is a first step in helping to remove
QueryParseContext entirely.
This commit is contained in:
Christoph Büscher 2017-06-29 17:10:20 +02:00 committed by GitHub
parent 22ff76da0c
commit 927111c91d
97 changed files with 462 additions and 562 deletions

View File

@ -30,13 +30,14 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentHelper;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.indices.InvalidAliasNameException;
import java.io.IOException;
import java.util.function.Function;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
/**
* Validator for an alias, to be used before adding an alias to the index metadata
* and make sure the alias is valid
@ -141,8 +142,7 @@ public class AliasValidator extends AbstractComponent {
}
private static void validateAliasFilter(XContentParser parser, QueryShardContext queryShardContext) throws IOException {
QueryParseContext queryParseContext = queryShardContext.newParseContext(parser);
QueryBuilder parseInnerQueryBuilder = queryParseContext.parseInnerQueryBuilder();
QueryBuilder parseInnerQueryBuilder = parseInnerQueryBuilder(parser);
QueryBuilder queryBuilder = QueryBuilder.rewriteQuery(parseInnerQueryBuilder, queryShardContext);
queryBuilder.toFilter(queryShardContext);
}

View File

@ -31,8 +31,11 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.common.xcontent.AbstractObjectParser;
import org.elasticsearch.common.xcontent.NamedXContentRegistry.UnknownNamedObjectException;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentLocation;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.XContentParser.Token;
import org.elasticsearch.common.xcontent.XContentType;
import java.io.IOException;
@ -286,6 +289,50 @@ public abstract class AbstractQueryBuilder<QB extends AbstractQueryBuilder<QB>>
protected void extractInnerHitBuilders(Map<String, InnerHitContextBuilder> innerHits) {
}
/**
* Parses a query excluding the query element that wraps it
*/
public static QueryBuilder parseInnerQueryBuilder(XContentParser parser) throws IOException {
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, must start with start_object");
}
}
if (parser.nextToken() == XContentParser.Token.END_OBJECT) {
// we encountered '{}' for a query clause, it used to be supported, deprecated in 5.0 and removed in 6.0
throw new IllegalArgumentException("query malformed, empty clause found at [" + parser.getTokenLocation() +"]");
}
if (parser.currentToken() != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
}
String queryName = parser.currentName();
// move to the next START_OBJECT
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[" + queryName + "] query malformed, no start_object after query name");
}
QueryBuilder result;
try {
// TODO what can we pass in here
result = parser.namedObject(QueryBuilder.class, queryName, null);
} catch (UnknownNamedObjectException e) {
// Preserve the error message from 5.0 until we have a compellingly better message so we don't break BWC.
// This intentionally doesn't include the causing exception because that'd change the "root_cause" of any unknown query errors
throw new ParsingException(new XContentLocation(e.getLineNumber(), e.getColumnNumber()),
"no [query] registered for [" + e.getName() + "]");
}
//end_object of the specific query (e.g. match, multi_match etc.) element
if (parser.currentToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(),
"[" + queryName + "] malformed query, expected [END_OBJECT] but found [" + parser.currentToken() + "]");
}
//end_object of the query object
if (parser.nextToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(),
"[" + queryName + "] malformed query, expected [END_OBJECT] but found [" + parser.currentToken() + "]");
}
return result;
}
// Like Objects.requireNotNull(...) but instead throws a IllegalArgumentException
protected static <T> T requireValue(T value, String message) {
if (value == null) {

View File

@ -275,11 +275,9 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
builder.endArray();
}
public static BoolQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
public static BoolQueryBuilder fromXContent(XContentParser parser) throws IOException, ParsingException {
boolean adjustPureNegative = BoolQueryBuilder.ADJUST_PURE_NEGATIVE_DEFAULT;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
float boost = DEFAULT_BOOST;
String minimumShouldMatch = null;
final List<QueryBuilder> mustClauses = new ArrayList<>();
@ -293,22 +291,20 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
switch (currentFieldName) {
case MUST:
mustClauses.add(parseContext.parseInnerQueryBuilder());
mustClauses.add(parseInnerQueryBuilder(parser));
break;
case SHOULD:
shouldClauses.add(parseContext.parseInnerQueryBuilder());
shouldClauses.add(parseInnerQueryBuilder(parser));
break;
case FILTER:
filterClauses.add(parseContext.parseInnerQueryBuilder());
filterClauses.add(parseInnerQueryBuilder(parser));
break;
case MUST_NOT:
case MUSTNOT:
mustNotClauses.add(parseContext.parseInnerQueryBuilder());
mustNotClauses.add(parseInnerQueryBuilder(parser));
break;
default:
throw new ParsingException(parser.getTokenLocation(), "[bool] query does not support [" + currentFieldName + "]");
@ -317,17 +313,17 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
switch (currentFieldName) {
case MUST:
mustClauses.add(parseContext.parseInnerQueryBuilder());
mustClauses.add(parseInnerQueryBuilder(parser));
break;
case SHOULD:
shouldClauses.add(parseContext.parseInnerQueryBuilder());
shouldClauses.add(parseInnerQueryBuilder(parser));
break;
case FILTER:
filterClauses.add(parseContext.parseInnerQueryBuilder());
filterClauses.add(parseInnerQueryBuilder(parser));
break;
case MUST_NOT:
case MUSTNOT:
mustNotClauses.add(parseContext.parseInnerQueryBuilder());
mustNotClauses.add(parseInnerQueryBuilder(parser));
break;
default:
throw new ParsingException(parser.getTokenLocation(), "bool query does not support [" + currentFieldName + "]");
@ -338,11 +334,11 @@ public class BoolQueryBuilder extends AbstractQueryBuilder<BoolQueryBuilder> {
// ignore
} else if (MINIMUM_SHOULD_MATCH.match(currentFieldName)) {
minimumShouldMatch = parser.textOrNull();
} else if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName)) {
} else if (BOOST_FIELD.match(currentFieldName)) {
boost = parser.floatValue();
} else if (ADJUST_PURE_NEGATIVE.match(currentFieldName)) {
adjustPureNegative = parser.booleanValue();
} else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
} else if (NAME_FIELD.match(currentFieldName)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(), "[bool] query does not support [" + currentFieldName + "]");

View File

@ -32,6 +32,7 @@ import java.io.IOException;
import java.util.Map;
import java.util.Objects;
/**
* The BoostingQuery class can be used to effectively demote results that match a given query.
* Unlike the "NOT" clause, this still selects documents that contain undesirable terms,
@ -136,14 +137,12 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
builder.endObject();
}
public static BoostingQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static BoostingQueryBuilder fromXContent(XContentParser parser) throws IOException {
QueryBuilder positiveQuery = null;
boolean positiveQueryFound = false;
QueryBuilder negativeQuery = null;
boolean negativeQueryFound = false;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
float boost = DEFAULT_BOOST;
float negativeBoost = -1;
String queryName = null;
@ -154,10 +153,10 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (POSITIVE_FIELD.match(currentFieldName)) {
positiveQuery = parseContext.parseInnerQueryBuilder();
positiveQuery = parseInnerQueryBuilder(parser);
positiveQueryFound = true;
} else if (NEGATIVE_FIELD.match(currentFieldName)) {
negativeQuery = parseContext.parseInnerQueryBuilder();
negativeQuery = parseInnerQueryBuilder(parser);
negativeQueryFound = true;
} else {
throw new ParsingException(parser.getTokenLocation(), "[boosting] query does not support [" + currentFieldName + "]");
@ -165,9 +164,9 @@ public class BoostingQueryBuilder extends AbstractQueryBuilder<BoostingQueryBuil
} else if (token.isValue()) {
if (NEGATIVE_BOOST_FIELD.match(currentFieldName)) {
negativeBoost = parser.floatValue();
} else if (AbstractQueryBuilder.NAME_FIELD.match(currentFieldName)) {
} else if (NAME_FIELD.match(currentFieldName)) {
queryName = parser.text();
} else if (AbstractQueryBuilder.BOOST_FIELD.match(currentFieldName)) {
} else if (BOOST_FIELD.match(currentFieldName)) {
boost = parser.floatValue();
} else {
throw new ParsingException(parser.getTokenLocation(), "[boosting] query does not support [" + currentFieldName + "]");

View File

@ -248,9 +248,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
builder.endObject();
}
public static CommonTermsQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static CommonTermsQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
Object text = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -266,8 +264,6 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -85,9 +85,7 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
builder.endObject();
}
public static ConstantScoreQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static ConstantScoreQueryBuilder fromXContent(XContentParser parser) throws IOException {
QueryBuilder query = null;
boolean queryFound = false;
String queryName = null;
@ -98,15 +96,13 @@ public class ConstantScoreQueryBuilder extends AbstractQueryBuilder<ConstantScor
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
if (INNER_QUERY_FIELD.match(currentFieldName)) {
if (queryFound) {
throw new ParsingException(parser.getTokenLocation(), "[" + ConstantScoreQueryBuilder.NAME + "]"
+ " accepts only one 'filter' element.");
}
query = parseContext.parseInnerQueryBuilder();
query = parseInnerQueryBuilder(parser);
queryFound = true;
} else {
throw new ParsingException(parser.getTokenLocation(),

View File

@ -122,9 +122,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
builder.endObject();
}
public static DisMaxQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static DisMaxQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
float tieBreaker = DisMaxQueryBuilder.DEFAULT_TIE_BREAKER;
@ -140,7 +138,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERIES_FIELD.match(currentFieldName)) {
queriesFound = true;
queries.add(parseContext.parseInnerQueryBuilder());
queries.add(parseInnerQueryBuilder(parser));
} else {
throw new ParsingException(parser.getTokenLocation(), "[dis_max] query does not support [" + currentFieldName + "]");
}
@ -148,7 +146,7 @@ public class DisMaxQueryBuilder extends AbstractQueryBuilder<DisMaxQueryBuilder>
if (QUERIES_FIELD.match(currentFieldName)) {
queriesFound = true;
while (token != XContentParser.Token.END_ARRAY) {
queries.add(parseContext.parseInnerQueryBuilder());
queries.add(parseInnerQueryBuilder(parser));
token = parser.nextToken();
}
} else {

View File

@ -83,9 +83,7 @@ public class ExistsQueryBuilder extends AbstractQueryBuilder<ExistsQueryBuilder>
builder.endObject();
}
public static ExistsQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static ExistsQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldPattern = null;
String queryName = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;

View File

@ -100,9 +100,7 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
builder.endObject();
}
public static FieldMaskingSpanQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static FieldMaskingSpanQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
SpanQueryBuilder inner = null;
@ -116,7 +114,7 @@ public class FieldMaskingSpanQueryBuilder extends AbstractQueryBuilder<FieldMask
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERY_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "[field_masking_span] query must be of type span query");
}

View File

@ -251,8 +251,7 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
builder.endObject();
}
public static FuzzyQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static FuzzyQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
Object value = null;
Fuzziness fuzziness = FuzzyQueryBuilder.DEFAULT_FUZZINESS;
@ -267,8 +266,6 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -375,9 +375,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
builder.endObject();
}
public static GeoBoundingBoxQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static GeoBoundingBoxQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
double top = Double.NaN;
@ -406,9 +404,7 @@ public class GeoBoundingBoxQueryBuilder extends AbstractQueryBuilder<GeoBounding
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
token = parser.nextToken();
if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (FIELD_FIELD.match(currentFieldName)) {
if (FIELD_FIELD.match(currentFieldName)) {
fieldName = parser.text();
} else if (TOP_FIELD.match(currentFieldName)) {
top = parser.doubleValue();

View File

@ -269,9 +269,7 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
builder.endObject();
}
public static GeoDistanceQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static GeoDistanceQueryBuilder fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -288,8 +286,6 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_ARRAY) {
fieldName = currentFieldName;
GeoUtils.parseGeoPoint(parser, point);

View File

@ -221,9 +221,7 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
builder.endObject();
}
public static GeoPolygonQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static GeoPolygonQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
List<GeoPoint> shell = null;
@ -238,8 +236,6 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
fieldName = currentFieldName;
@ -248,7 +244,7 @@ public class GeoPolygonQueryBuilder extends AbstractQueryBuilder<GeoPolygonQuery
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
if (POINTS_FIELD.match(currentFieldName)) {
shell = new ArrayList<GeoPoint>();
shell = new ArrayList<>();
while ((token = parser.nextToken()) != Token.END_ARRAY) {
shell.add(GeoUtils.parseGeoPoint(parser));
}

View File

@ -457,9 +457,7 @@ public class GeoShapeQueryBuilder extends AbstractQueryBuilder<GeoShapeQueryBuil
builder.endObject();
}
public static GeoShapeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static GeoShapeQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
ShapeRelation shapeRelation = null;
SpatialStrategy strategy = null;

View File

@ -30,6 +30,7 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.mapper.UidFieldMapper;
@ -146,11 +147,11 @@ public class IdsQueryBuilder extends AbstractQueryBuilder<IdsQueryBuilder> {
declareStandardFields(PARSER);
}
public static IdsQueryBuilder fromXContent(QueryParseContext context) {
public static IdsQueryBuilder fromXContent(XContentParser parser) {
try {
return PARSER.apply(context.parser(), context);
return PARSER.apply(parser, null);
} catch (IllegalArgumentException e) {
throw new ParsingException(context.parser().getTokenLocation(), e.getMessage(), e);
throw new ParsingException(parser.getTokenLocation(), e.getMessage(), e);
}
}

View File

@ -75,23 +75,23 @@ public final class InnerHitBuilder extends ToXContentToBytes implements Writeabl
try {
Set<ScriptField> scriptFields = new HashSet<>();
for (XContentParser.Token token = p.nextToken(); token != END_OBJECT; token = p.nextToken()) {
scriptFields.add(new ScriptField(c));
scriptFields.add(new ScriptField(p));
}
i.setScriptFields(scriptFields);
} catch (IOException e) {
throw new ParsingException(p.getTokenLocation(), "Could not parse inner script definition", e);
}
}, SearchSourceBuilder.SCRIPT_FIELDS_FIELD, ObjectParser.ValueType.OBJECT);
PARSER.declareField((p, i, c) -> i.setSorts(SortBuilder.fromXContent(c)), SearchSourceBuilder.SORT_FIELD,
PARSER.declareField((p, i, c) -> i.setSorts(SortBuilder.fromXContent(p)), SearchSourceBuilder.SORT_FIELD,
ObjectParser.ValueType.OBJECT_ARRAY);
PARSER.declareField((p, i, c) -> {
try {
i.setFetchSourceContext(FetchSourceContext.fromXContent(c.parser()));
i.setFetchSourceContext(FetchSourceContext.fromXContent(p));
} catch (IOException e) {
throw new ParsingException(p.getTokenLocation(), "Could not parse inner _source definition", e);
}
}, SearchSourceBuilder._SOURCE_FIELD, ObjectParser.ValueType.OBJECT_ARRAY_BOOLEAN_OR_STRING);
PARSER.declareObject(InnerHitBuilder::setHighlightBuilder, (p, c) -> HighlightBuilder.fromXContent(c),
PARSER.declareObject(InnerHitBuilder::setHighlightBuilder, (p, c) -> HighlightBuilder.fromXContent(p),
SearchSourceBuilder.HIGHLIGHT_FIELD);
}
@ -582,7 +582,7 @@ public final class InnerHitBuilder extends ToXContentToBytes implements Writeabl
storedFieldsContext, docValueFields, scriptFields, fetchSourceContext, sorts, highlightBuilder);
}
public static InnerHitBuilder fromXContent(QueryParseContext context) throws IOException {
return PARSER.parse(context.parser(), new InnerHitBuilder(), context);
public static InnerHitBuilder fromXContent(XContentParser parser) throws IOException {
return PARSER.parse(parser, new InnerHitBuilder(), null);
}
}

View File

@ -26,9 +26,9 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Optional;
/**
* A query that matches on all documents.
@ -64,11 +64,11 @@ public class MatchAllQueryBuilder extends AbstractQueryBuilder<MatchAllQueryBuil
declareStandardFields(PARSER);
}
public static MatchAllQueryBuilder fromXContent(QueryParseContext context) {
public static MatchAllQueryBuilder fromXContent(XContentParser parser) {
try {
return PARSER.apply(context.parser(), context);
return PARSER.apply(parser, null);
} catch (IllegalArgumentException e) {
throw new ParsingException(context.parser().getTokenLocation(), e.getMessage(), e);
throw new ParsingException(parser.getTokenLocation(), e.getMessage(), e);
}
}

View File

@ -57,9 +57,7 @@ public class MatchNoneQueryBuilder extends AbstractQueryBuilder<MatchNoneQueryBu
builder.endObject();
}
public static MatchNoneQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static MatchNoneQueryBuilder fromXContent(XContentParser parser) throws IOException {
String currentFieldName = null;
XContentParser.Token token;
String queryName = null;

View File

@ -189,8 +189,7 @@ public class MatchPhrasePrefixQueryBuilder extends AbstractQueryBuilder<MatchPhr
return Objects.hash(fieldName, value, analyzer, slop, maxExpansions);
}
public static MatchPhrasePrefixQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static MatchPhrasePrefixQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -203,8 +202,6 @@ public class MatchPhrasePrefixQueryBuilder extends AbstractQueryBuilder<MatchPhr
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -161,8 +161,7 @@ public class MatchPhraseQueryBuilder extends AbstractQueryBuilder<MatchPhraseQue
return Objects.hash(fieldName, value, analyzer, slop);
}
public static MatchPhraseQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static MatchPhraseQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -174,8 +173,6 @@ public class MatchPhraseQueryBuilder extends AbstractQueryBuilder<MatchPhraseQue
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -491,8 +491,7 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
return NAME;
}
public static MatchQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static MatchQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
MatchQuery.Type type = MatchQuery.Type.BOOLEAN;
Object value = null;
@ -515,8 +514,6 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -809,9 +809,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
builder.endObject();
}
public static MoreLikeThisQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static MoreLikeThisQueryBuilder fromXContent(XContentParser parser) throws IOException {
// document inputs
List<String> fields = null;
List<String> likeTexts = new ArrayList<>();
@ -846,9 +844,9 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (Field.LIKE.match(currentFieldName)) {
parseLikeField(parseContext, likeTexts, likeItems);
parseLikeField(parser, likeTexts, likeItems);
} else if (Field.UNLIKE.match(currentFieldName)) {
parseLikeField(parseContext, unlikeTexts, unlikeItems);
parseLikeField(parser, unlikeTexts, unlikeItems);
} else if (Field.LIKE_TEXT.match(currentFieldName)) {
likeTexts.add(parser.text());
} else if (Field.MAX_QUERY_TERMS.match(currentFieldName)) {
@ -888,11 +886,11 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
}
} else if (Field.LIKE.match(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
parseLikeField(parseContext, likeTexts, likeItems);
parseLikeField(parser, likeTexts, likeItems);
}
} else if (Field.UNLIKE.match(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
parseLikeField(parseContext, unlikeTexts, unlikeItems);
parseLikeField(parser, unlikeTexts, unlikeItems);
}
} else if (Field.IDS.match(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
@ -918,9 +916,9 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
}
} else if (token == XContentParser.Token.START_OBJECT) {
if (Field.LIKE.match(currentFieldName)) {
parseLikeField(parseContext, likeTexts, likeItems);
parseLikeField(parser, likeTexts, likeItems);
} else if (Field.UNLIKE.match(currentFieldName)) {
parseLikeField(parseContext, unlikeTexts, unlikeItems);
parseLikeField(parser, unlikeTexts, unlikeItems);
} else {
throw new ParsingException(parser.getTokenLocation(), "[mlt] query does not support [" + currentFieldName + "]");
}
@ -962,8 +960,7 @@ public class MoreLikeThisQueryBuilder extends AbstractQueryBuilder<MoreLikeThisQ
return moreLikeThisQueryBuilder;
}
private static void parseLikeField(QueryParseContext parseContext, List<String> texts, List<Item> items) throws IOException {
XContentParser parser = parseContext.parser();
private static void parseLikeField(XContentParser parser, List<String> texts, List<Item> items) throws IOException {
if (parser.currentToken().isValue()) {
texts.add(parser.text());
} else if (parser.currentToken() == XContentParser.Token.START_OBJECT) {

View File

@ -554,9 +554,7 @@ public class MultiMatchQueryBuilder extends AbstractQueryBuilder<MultiMatchQuery
builder.endObject();
}
public static MultiMatchQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static MultiMatchQueryBuilder fromXContent(XContentParser parser) throws IOException {
Object value = null;
Map<String, Float> fieldsBoosts = new HashMap<>();
MultiMatchQueryBuilder.Type type = DEFAULT_TYPE;

View File

@ -178,8 +178,7 @@ public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder>
builder.endObject();
}
public static NestedQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static NestedQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
ScoreMode scoreMode = ScoreMode.Avg;
String queryName = null;
@ -194,9 +193,9 @@ public class NestedQueryBuilder extends AbstractQueryBuilder<NestedQueryBuilder>
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERY_FIELD.match(currentFieldName)) {
query = parseContext.parseInnerQueryBuilder();
query = parseInnerQueryBuilder(parser);
} else if (INNER_HITS_FIELD.match(currentFieldName)) {
innerHitBuilder = InnerHitBuilder.fromXContent(parseContext);
innerHitBuilder = InnerHitBuilder.fromXContent(parser);
} else {
throw new ParsingException(parser.getTokenLocation(), "[nested] query does not support [" + currentFieldName + "]");
}

View File

@ -116,9 +116,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
builder.endObject();
}
public static PrefixQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static PrefixQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
String value = null;
String rewrite = null;
@ -130,8 +128,6 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -19,20 +19,12 @@
package org.elasticsearch.index.query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.xcontent.NamedXContentRegistry.UnknownNamedObjectException;
import org.elasticsearch.common.xcontent.XContentLocation;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
import java.util.Objects;
public class QueryParseContext {
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 final XContentParser parser;
public QueryParseContext(XContentParser parser) {
@ -42,75 +34,4 @@ public class QueryParseContext {
public XContentParser parser() {
return this.parser;
}
public boolean isDeprecatedSetting(String setting) {
return CACHE.match(setting) || CACHE_KEY.match(setting);
}
/**
* Parses a top level query including the query element that wraps it
*/
public QueryBuilder parseTopLevelQueryBuilder() {
try {
QueryBuilder queryBuilder = null;
for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) {
if (token == XContentParser.Token.FIELD_NAME) {
String fieldName = parser.currentName();
if ("query".equals(fieldName)) {
queryBuilder = parseInnerQueryBuilder();
} else {
throw new ParsingException(parser.getTokenLocation(), "request does not support [" + parser.currentName() + "]");
}
}
}
return queryBuilder;
} catch (ParsingException e) {
throw e;
} catch (Exception e) {
throw new ParsingException(parser == null ? null : parser.getTokenLocation(), "Failed to parse", e);
}
}
/**
* Parses a query excluding the query element that wraps it
*/
public QueryBuilder parseInnerQueryBuilder() throws IOException {
if (parser.currentToken() != XContentParser.Token.START_OBJECT) {
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, must start with start_object");
}
}
if (parser.nextToken() == XContentParser.Token.END_OBJECT) {
// we encountered '{}' for a query clause, it used to be supported, deprecated in 5.0 and removed in 6.0
throw new IllegalArgumentException("query malformed, empty clause found at [" + parser.getTokenLocation() +"]");
}
if (parser.currentToken() != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[_na] query malformed, no field after start_object");
}
String queryName = parser.currentName();
// move to the next START_OBJECT
if (parser.nextToken() != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[" + queryName + "] query malformed, no start_object after query name");
}
QueryBuilder result;
try {
result = parser.namedObject(QueryBuilder.class, queryName, this);
} catch (UnknownNamedObjectException e) {
// Preserve the error message from 5.0 until we have a compellingly better message so we don't break BWC.
// This intentionally doesn't include the causing exception because that'd change the "root_cause" of any unknown query errors
throw new ParsingException(new XContentLocation(e.getLineNumber(), e.getColumnNumber()),
"no [query] registered for [" + e.getName() + "]");
}
//end_object of the specific query (e.g. match, multi_match etc.) element
if (parser.currentToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(),
"[" + queryName + "] malformed query, expected [END_OBJECT] but found [" + parser.currentToken() + "]");
}
//end_object of the query object
if (parser.nextToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(),
"[" + queryName + "] malformed query, expected [END_OBJECT] but found [" + parser.currentToken() + "]");
}
return result;
}
}

View File

@ -19,6 +19,8 @@
package org.elasticsearch.index.query;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
/**
@ -27,14 +29,9 @@ import java.io.IOException;
@FunctionalInterface
public interface QueryParser<QB extends QueryBuilder> {
/**
* Creates a new {@link QueryBuilder} from the query held by the {@link QueryParseContext}
* in {@link org.elasticsearch.common.xcontent.XContent} format
*
* @param parseContext
* the input parse context. The state on the parser contained in
* this context will be changed as a side effect of this method
* call
* @return the new QueryBuilder
* Creates a new {@link QueryBuilder} from the query held by the
* {@link XContentParser}. The state on the parser contained in this context
* will be changed as a side effect of this method call
*/
QB fromXContent(QueryParseContext parseContext) throws IOException;
QB fromXContent(XContentParser parser) throws IOException;
}

View File

@ -683,8 +683,7 @@ public class QueryStringQueryBuilder extends AbstractQueryBuilder<QueryStringQue
builder.endObject();
}
public static QueryStringQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static QueryStringQueryBuilder fromXContent(XContentParser parser) throws IOException {
String currentFieldName = null;
XContentParser.Token token;
String queryString = null;

View File

@ -343,9 +343,7 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
builder.endObject();
}
public static RangeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static RangeQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
Object from = null;
Object to = null;
@ -362,8 +360,6 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -177,8 +177,7 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
builder.endObject();
}
public static RegexpQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static RegexpQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
String rewrite = null;
String value = null;
@ -191,8 +190,6 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -84,8 +84,7 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
builder.endObject();
}
public static ScriptQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static ScriptQueryBuilder fromXContent(XContentParser parser) throws IOException {
// also, when caching, since its isCacheable is false, will result in loading all bit set...
Script script = null;
@ -97,8 +96,6 @@ public class ScriptQueryBuilder extends AbstractQueryBuilder<ScriptQueryBuilder>
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
if (Script.SCRIPT_PARSE_FIELD.match(currentFieldName)) {
script = Script.parse(parser);

View File

@ -462,9 +462,7 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
builder.endObject();
}
public static SimpleQueryStringBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SimpleQueryStringBuilder fromXContent(XContentParser parser) throws IOException {
String currentFieldName = null;
String queryBody = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;

View File

@ -99,8 +99,7 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
builder.endObject();
}
public static SpanContainingQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanContainingQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null;
SpanQueryBuilder big = null;
@ -113,13 +112,13 @@ public class SpanContainingQueryBuilder extends AbstractQueryBuilder<SpanContain
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (BIG_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_containing [big] must be of type span query");
}
big = (SpanQueryBuilder) query;
} else if (LITTLE_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_containing [little] must be of type span query");
}

View File

@ -99,9 +99,7 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
builder.endObject();
}
public static SpanFirstQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanFirstQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
SpanQueryBuilder match = null;
@ -115,7 +113,7 @@ public class SpanFirstQueryBuilder extends AbstractQueryBuilder<SpanFirstQueryBu
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (MATCH_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanFirst [match] must be of type span query");
}

View File

@ -81,8 +81,7 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
builder.endObject();
}
public static SpanMultiTermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanMultiTermQueryBuilder fromXContent(XContentParser parser) throws IOException {
String currentFieldName = null;
MultiTermQueryBuilder subQuery = null;
String queryName = null;
@ -93,7 +92,7 @@ public class SpanMultiTermQueryBuilder extends AbstractQueryBuilder<SpanMultiTer
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (MATCH_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof MultiTermQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(),
"[span_multi] [" + MATCH_FIELD.getPreferredName() + "] must be of type multi term query");

View File

@ -143,9 +143,7 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
builder.endObject();
}
public static SpanNearQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanNearQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
Integer slop = null;
boolean inOrder = SpanNearQueryBuilder.DEFAULT_IN_ORDER;
@ -161,7 +159,7 @@ public class SpanNearQueryBuilder extends AbstractQueryBuilder<SpanNearQueryBuil
} else if (token == XContentParser.Token.START_ARRAY) {
if (CLAUSES_FIELD.match(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanNear [clauses] must be of type span query");
}

View File

@ -160,9 +160,7 @@ public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilde
builder.endObject();
}
public static SpanNotQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanNotQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
SpanQueryBuilder include = null;
@ -181,13 +179,13 @@ public class SpanNotQueryBuilder extends AbstractQueryBuilder<SpanNotQueryBuilde
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (INCLUDE_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanNot [include] must be of type span query");
}
include = (SpanQueryBuilder) query;
} else if (EXCLUDE_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanNot [exclude] must be of type span query");
}

View File

@ -97,9 +97,7 @@ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder>
builder.endObject();
}
public static SpanOrQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanOrQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null;
@ -113,7 +111,7 @@ public class SpanOrQueryBuilder extends AbstractQueryBuilder<SpanOrQueryBuilder>
} else if (token == XContentParser.Token.START_ARRAY) {
if (CLAUSES_FIELD.match(currentFieldName)) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "spanOr [clauses] must be of type span query");
}

View File

@ -91,8 +91,7 @@ public class SpanTermQueryBuilder extends BaseTermQueryBuilder<SpanTermQueryBuil
return new SpanTermQuery(term);
}
public static SpanTermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
public static SpanTermQueryBuilder fromXContent(XContentParser parser) throws IOException, ParsingException {
String fieldName = null;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;

View File

@ -104,9 +104,7 @@ public class SpanWithinQueryBuilder extends AbstractQueryBuilder<SpanWithinQuery
builder.endObject();
}
public static SpanWithinQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static SpanWithinQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null;
SpanQueryBuilder big = null;
@ -119,13 +117,13 @@ public class SpanWithinQueryBuilder extends AbstractQueryBuilder<SpanWithinQuery
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (BIG_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_within [big] must be of type span query");
}
big = (SpanQueryBuilder) query;
} else if (LITTLE_FIELD.match(currentFieldName)) {
QueryBuilder query = parseContext.parseInnerQueryBuilder();
QueryBuilder query = parseInnerQueryBuilder(parser);
if (query instanceof SpanQueryBuilder == false) {
throw new ParsingException(parser.getTokenLocation(), "span_within [little] must be of type span query");
}

View File

@ -82,9 +82,7 @@ public class TermQueryBuilder extends BaseTermQueryBuilder<TermQueryBuilder> {
super(in);
}
public static TermQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static TermQueryBuilder fromXContent(XContentParser parser) throws IOException {
String queryName = null;
String fieldName = null;
Object value = null;
@ -94,8 +92,6 @@ public class TermQueryBuilder extends BaseTermQueryBuilder<TermQueryBuilder> {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -19,8 +19,8 @@
package org.elasticsearch.index.query;
import org.apache.lucene.search.TermInSetQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermInSetQuery;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.elasticsearch.action.get.GetRequest;
@ -205,7 +205,7 @@ public class TermsQueryBuilder extends AbstractQueryBuilder<TermsQueryBuilder> {
if (values instanceof List<?>) {
list = (List<?>) values;
} else {
ArrayList<Object> arrayList = new ArrayList<Object>();
ArrayList<Object> arrayList = new ArrayList<>();
for (Object o : values) {
arrayList.add(o);
}
@ -266,11 +266,13 @@ public class TermsQueryBuilder extends AbstractQueryBuilder<TermsQueryBuilder> {
}
final BytesReference bytes = bytesOut.bytes();
return new AbstractList<Object>() {
@Override
public Object get(int i) {
final int startOffset = i == 0 ? 0 : endOffsets[i-1];
final int endOffset = endOffsets[i];
return bytes.slice(startOffset, endOffset - startOffset).toBytesRef();
}
@Override
public int size() {
return endOffsets.length;
}
@ -320,9 +322,7 @@ public class TermsQueryBuilder extends AbstractQueryBuilder<TermsQueryBuilder> {
builder.endObject();
}
public static TermsQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static TermsQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
List<Object> values = null;
TermsLookup termsLookup = null;
@ -335,8 +335,6 @@ public class TermsQueryBuilder extends AbstractQueryBuilder<TermsQueryBuilder> {
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_ARRAY) {
if (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(),

View File

@ -80,13 +80,10 @@ public class TypeQueryBuilder extends AbstractQueryBuilder<TypeQueryBuilder> {
builder.endObject();
}
public static TypeQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static TypeQueryBuilder fromXContent(XContentParser parser) throws IOException {
BytesRef type = null;
String queryName = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {

View File

@ -132,8 +132,7 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
builder.endObject();
}
public static WildcardQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static WildcardQueryBuilder fromXContent(XContentParser parser) throws IOException {
String fieldName = null;
String rewrite = null;
String value = null;
@ -144,8 +143,6 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
throwParsingExceptionOnMultipleFields(NAME, parser.getTokenLocation(), fieldName, currentFieldName);
fieldName = currentFieldName;

View File

@ -115,9 +115,7 @@ public class WrapperQueryBuilder extends AbstractQueryBuilder<WrapperQueryBuilde
builder.endObject();
}
public static WrapperQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static WrapperQueryBuilder fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[wrapper] query malformed");
@ -161,9 +159,8 @@ public class WrapperQueryBuilder extends AbstractQueryBuilder<WrapperQueryBuilde
@Override
protected QueryBuilder doRewrite(QueryRewriteContext context) throws IOException {
try (XContentParser qSourceParser = XContentFactory.xContent(source).createParser(context.getXContentRegistry(), source)) {
QueryParseContext parseContext = context.newParseContext(qSourceParser);
final QueryBuilder queryBuilder = parseContext.parseInnerQueryBuilder();
final QueryBuilder queryBuilder = parseInnerQueryBuilder(qSourceParser);
if (boost() != DEFAULT_BOOST || queryName() != null) {
final BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
boolQueryBuilder.must(queryBuilder);

View File

@ -25,7 +25,6 @@ import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.plugins.SearchPlugin;
import org.elasticsearch.search.MultiValueMode;
import org.elasticsearch.search.SearchModule;
@ -97,8 +96,7 @@ public final class DecayFunctionParser<DFB extends DecayFunctionBuilder<DFB>> im
* </pre>
*/
@Override
public DFB fromXContent(QueryParseContext context) throws IOException, ParsingException {
XContentParser parser = context.parser();
public DFB fromXContent(XContentParser parser) throws IOException, ParsingException {
String currentFieldName;
XContentParser.Token token;
MultiValueMode multiValueMode = DecayFunctionBuilder.DEFAULT_MULTI_VALUE_MODE;

View File

@ -29,7 +29,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException;
@ -157,9 +156,8 @@ public class FieldValueFactorFunctionBuilder extends ScoreFunctionBuilder<FieldV
return new FieldValueFactorFunction(field, factor, modifier, missing, fieldData);
}
public static FieldValueFactorFunctionBuilder fromXContent(QueryParseContext parseContext)
public static FieldValueFactorFunctionBuilder fromXContent(XContentParser parser)
throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
String currentFieldName = null;
String field = null;
float boostFactor = FieldValueFactorFunctionBuilder.DEFAULT_FACTOR;

View File

@ -39,7 +39,6 @@ import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.InnerHitContextBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
@ -435,9 +434,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
InnerHitContextBuilder.extractInnerHits(query(), innerHits);
}
public static FunctionScoreQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static FunctionScoreQueryBuilder fromXContent(XContentParser parser) throws IOException {
QueryBuilder query = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null;
@ -464,7 +461,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. [query] is already defined.",
NAME);
}
query = parseContext.parseInnerQueryBuilder();
query = parseInnerQueryBuilder(parser);
} else {
if (singleFunctionFound) {
throw new ParsingException(parser.getTokenLocation(),
@ -480,7 +477,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
singleFunctionName = currentFieldName;
ScoreFunctionBuilder<?> scoreFunction = parser.namedObject(ScoreFunctionBuilder.class, currentFieldName,
parseContext);
null);
filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(scoreFunction));
}
} else if (token == XContentParser.Token.START_ARRAY) {
@ -490,7 +487,7 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
handleMisplacedFunctionsDeclaration(parser.getTokenLocation(), errorString);
}
functionArrayFound = true;
currentFieldName = parseFiltersAndFunctions(parseContext, filterFunctionBuilders);
currentFieldName = parseFiltersAndFunctions(parser, filterFunctionBuilders);
} else {
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. array [{}] is not supported",
NAME, currentFieldName);
@ -557,11 +554,10 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
MISPLACED_FUNCTION_MESSAGE_PREFIX + errorString);
}
private static String parseFiltersAndFunctions(QueryParseContext parseContext,
private static String parseFiltersAndFunctions(XContentParser parser,
List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders) throws IOException {
String currentFieldName = null;
XContentParser.Token token;
XContentParser parser = parseContext.parser();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
QueryBuilder filter = null;
ScoreFunctionBuilder<?> scoreFunction = null;
@ -576,14 +572,14 @@ public class FunctionScoreQueryBuilder extends AbstractQueryBuilder<FunctionScor
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (FILTER_FIELD.match(currentFieldName)) {
filter = parseContext.parseInnerQueryBuilder();
filter = parseInnerQueryBuilder(parser);
} else {
if (scoreFunction != null) {
throw new ParsingException(parser.getTokenLocation(),
"failed to parse function_score functions. already found [{}], now encountering [{}].",
scoreFunction.getName(), currentFieldName);
}
scoreFunction = parser.namedObject(ScoreFunctionBuilder.class, currentFieldName, parseContext);
scoreFunction = parser.namedObject(ScoreFunctionBuilder.class, currentFieldName, null);
}
} else if (token.isValue()) {
if (WEIGHT_FIELD.match(currentFieldName)) {

View File

@ -28,9 +28,7 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.mapper.IdFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.UidFieldMapper;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException;
@ -147,9 +145,8 @@ public class RandomScoreFunctionBuilder extends ScoreFunctionBuilder<RandomScore
return Long.hashCode(value);
}
public static RandomScoreFunctionBuilder fromXContent(QueryParseContext parseContext)
public static RandomScoreFunctionBuilder fromXContent(XContentParser parser)
throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
RandomScoreFunctionBuilder randomScoreFunctionBuilder = new RandomScoreFunctionBuilder();
String currentFieldName = null;
XContentParser.Token token;

View File

@ -19,7 +19,7 @@
package org.elasticsearch.index.query.functionscore;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.common.xcontent.XContentParser;
import java.io.IOException;
@ -28,5 +28,5 @@ import java.io.IOException;
*/
@FunctionalInterface
public interface ScoreFunctionParser<FB extends ScoreFunctionBuilder<FB>> {
FB fromXContent(QueryParseContext context) throws IOException;
FB fromXContent(XContentParser parser) throws IOException;
}

View File

@ -26,11 +26,9 @@ import org.elasticsearch.common.lucene.search.function.ScoreFunction;
import org.elasticsearch.common.lucene.search.function.ScriptScoreFunction;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.SearchScript;
import java.io.IOException;
@ -102,9 +100,8 @@ public class ScriptScoreFunctionBuilder extends ScoreFunctionBuilder<ScriptScore
}
}
public static ScriptScoreFunctionBuilder fromXContent(QueryParseContext parseContext)
public static ScriptScoreFunctionBuilder fromXContent(XContentParser parser)
throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
Script script = null;
String currentFieldName = null;
XContentParser.Token token;

View File

@ -89,7 +89,6 @@ import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.merge.MergeStats;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.recovery.RecoveryStats;
import org.elasticsearch.index.refresh.RefreshStats;
import org.elasticsearch.index.search.stats.SearchStats;
@ -140,6 +139,7 @@ import static java.util.Collections.emptyMap;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.common.collect.MapBuilder.newMapBuilder;
import static org.elasticsearch.common.util.CollectionUtils.arrayAsArrayList;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class IndicesService extends AbstractLifecycleComponent
implements IndicesClusterStateService.AllocatedIndices<IndexShard, IndexService>, IndexService.ShardStoreDeleter {
@ -1261,7 +1261,7 @@ public class IndicesService extends AbstractLifecycleComponent
* of dependencies we pass in a function that can perform the parsing. */
CheckedFunction<byte[], QueryBuilder, IOException> filterParser = bytes -> {
try (XContentParser parser = XContentFactory.xContent(bytes).createParser(xContentRegistry, bytes)) {
return new QueryParseContext(parser).parseInnerQueryBuilder();
return parseInnerQueryBuilder(parser);
}
};
String[] aliases = indexNameExpressionResolver.filteringAliases(state, index, expressions);

View File

@ -26,6 +26,7 @@ import org.elasticsearch.action.support.broadcast.BroadcastResponse;
import org.elasticsearch.action.support.nodes.BaseNodeResponse;
import org.elasticsearch.action.support.nodes.BaseNodesResponse;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.ToXContent.Params;
@ -34,7 +35,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.Operator;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.rest.BytesRestResponse;
import org.elasticsearch.rest.RestChannel;
@ -45,6 +45,8 @@ import org.elasticsearch.rest.RestStatus;
import java.io.IOException;
import java.util.List;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class RestActions {
public static final ParseField _SHARDS_FIELD = new ParseField("_shards");
@ -201,8 +203,7 @@ public class RestActions {
}
public static QueryBuilder getQueryContent(XContentParser requestParser) {
QueryParseContext context = new QueryParseContext(requestParser);
return context.parseTopLevelQueryBuilder();
return parseTopLevelQueryBuilder(requestParser);
}
/**
@ -232,4 +233,28 @@ public class RestActions {
}
/**
* Parses a top level query including the query element that wraps it
*/
private static QueryBuilder parseTopLevelQueryBuilder(XContentParser parser) {
try {
QueryBuilder queryBuilder = null;
for (XContentParser.Token token = parser.nextToken(); token != XContentParser.Token.END_OBJECT; token = parser.nextToken()) {
if (token == XContentParser.Token.FIELD_NAME) {
String fieldName = parser.currentName();
if ("query".equals(fieldName)) {
queryBuilder = parseInnerQueryBuilder(parser);
} else {
throw new ParsingException(parser.getTokenLocation(), "request does not support [" + parser.currentName() + "]");
}
}
}
return queryBuilder;
} catch (ParsingException e) {
throw e;
} catch (Exception e) {
throw new ParsingException(parser == null ? null : parser.getTokenLocation(), "Failed to parse", e);
}
}
}

View File

@ -54,7 +54,6 @@ import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.PrefixQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryStringQueryBuilder;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.RegexpQueryBuilder;
@ -606,7 +605,7 @@ public class SearchModule {
// TODO remove funky contexts
namedXContents.add(new NamedXContentRegistry.Entry(
ScoreFunctionBuilder.class, scoreFunction.getName(),
(XContentParser p, Object c) -> scoreFunction.getParser().fromXContent((QueryParseContext) c)));
(XContentParser p, Object c) -> scoreFunction.getParser().fromXContent(p)));
}
private void registerValueFormats() {
@ -751,7 +750,7 @@ public class SearchModule {
private void registerQuery(QuerySpec<?> spec) {
namedWriteables.add(new NamedWriteableRegistry.Entry(QueryBuilder.class, spec.getName().getPreferredName(), spec.getReader()));
namedXContents.add(new NamedXContentRegistry.Entry(QueryBuilder.class, spec.getName(),
(p, c) -> spec.getParser().fromXContent((QueryParseContext) c)));
(p, c) -> spec.getParser().fromXContent(p)));
}
public FetchPhase getFetchPhase() {

View File

@ -343,8 +343,8 @@ public class AggregatorFactories {
aggBuildersMap.put(aggBuilder.name, aggBuilder);
}
List<PipelineAggregationBuilder> orderedPipelineAggregatorrs = new LinkedList<>();
List<PipelineAggregationBuilder> unmarkedBuilders = new ArrayList<PipelineAggregationBuilder>(pipelineAggregatorBuilders);
Set<PipelineAggregationBuilder> temporarilyMarked = new HashSet<PipelineAggregationBuilder>();
List<PipelineAggregationBuilder> unmarkedBuilders = new ArrayList<>(pipelineAggregatorBuilders);
Set<PipelineAggregationBuilder> temporarilyMarked = new HashSet<>();
while (!unmarkedBuilders.isEmpty()) {
PipelineAggregationBuilder builder = unmarkedBuilders.get(0);
resolvePipelineAggregatorOrder(aggBuildersMap, pipelineAggregatorBuildersMap, orderedPipelineAggregatorrs, unmarkedBuilders,

View File

@ -27,10 +27,10 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.xcontent.ObjectParser.NamedObjectParser;
import org.elasticsearch.common.xcontent.ToXContent;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.ObjectParser.NamedObjectParser;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.aggregations.Aggregator;
@ -48,15 +48,17 @@ import java.util.List;
import java.util.Map;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
/**
* Aggregation for adjacency matrices.
*
*
* NOTE! This is an experimental class.
*
*
* TODO the aggregation produces a sparse response but in the
* computation it uses a non-sparse structure (an array of Bits
* objects). This could be changed to a sparse structure in future.
*
*
*/
public class AdjacencyMatrixAggregator extends BucketsAggregator {
@ -65,11 +67,11 @@ public class AdjacencyMatrixAggregator extends BucketsAggregator {
protected static class KeyedFilter implements Writeable, ToXContent {
private final String key;
private final QueryBuilder filter;
public static final NamedObjectParser<KeyedFilter, QueryParseContext> PARSER =
(XContentParser p, QueryParseContext c, String name) ->
new KeyedFilter(name, c.parseInnerQueryBuilder());
public static final NamedObjectParser<KeyedFilter, QueryParseContext> PARSER =
(XContentParser p, QueryParseContext c, String name) ->
new KeyedFilter(name, parseInnerQueryBuilder(p));
public KeyedFilter(String key, QueryBuilder filter) {
if (key == null) {
@ -134,8 +136,8 @@ public class AdjacencyMatrixAggregator extends BucketsAggregator {
private final int totalNumIntersections;
private final String separator;
public AdjacencyMatrixAggregator(String name, AggregatorFactories factories, String separator, String[] keys,
Weight[] filters, SearchContext context, Aggregator parent, List<PipelineAggregator> pipelineAggregators,
public AdjacencyMatrixAggregator(String name, AggregatorFactories factories, String separator, String[] keys,
Weight[] filters, SearchContext context, Aggregator parent, List<PipelineAggregator> pipelineAggregators,
Map<String, Object> metaData) throws IOException {
super(name, factories, context, parent, pipelineAggregators, metaData);
this.separator = separator;
@ -207,9 +209,9 @@ public class AdjacencyMatrixAggregator extends BucketsAggregator {
// a date-histogram where we will look for transactions over time and can expect many
// empty buckets.
if (docCount > 0) {
InternalAdjacencyMatrix.InternalBucket bucket = new InternalAdjacencyMatrix.InternalBucket(keys[i],
InternalAdjacencyMatrix.InternalBucket bucket = new InternalAdjacencyMatrix.InternalBucket(keys[i],
docCount, bucketAggregations(bucketOrd));
buckets.add(bucket);
buckets.add(bucket);
}
}
int pos = keys.length;
@ -220,7 +222,7 @@ public class AdjacencyMatrixAggregator extends BucketsAggregator {
// Empty buckets are not returned due to potential for very sparse matrices
if (docCount > 0) {
String intersectKey = keys[i] + separator + keys[j];
InternalAdjacencyMatrix.InternalBucket bucket = new InternalAdjacencyMatrix.InternalBucket(intersectKey,
InternalAdjacencyMatrix.InternalBucket bucket = new InternalAdjacencyMatrix.InternalBucket(intersectKey,
docCount, bucketAggregations(bucketOrd));
buckets.add(bucket);
}

View File

@ -32,6 +32,8 @@ import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class FilterAggregationBuilder extends AbstractAggregationBuilder<FilterAggregationBuilder> {
public static final String NAME = "filter";
@ -83,7 +85,7 @@ public class FilterAggregationBuilder extends AbstractAggregationBuilder<FilterA
}
public static FilterAggregationBuilder parse(String aggregationName, QueryParseContext context) throws IOException {
QueryBuilder filter = context.parseInnerQueryBuilder();
QueryBuilder filter = parseInnerQueryBuilder(context.parser());
return new FilterAggregationBuilder(aggregationName, filter);
}

View File

@ -40,6 +40,8 @@ import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class FiltersAggregationBuilder extends AbstractAggregationBuilder<FiltersAggregationBuilder> {
public static final String NAME = "filters";
@ -171,7 +173,7 @@ public class FiltersAggregationBuilder extends AbstractAggregationBuilder<Filter
throws IOException {
List<KeyedFilter> rewrittenFilters = new ArrayList<>(filters.size());
for(KeyedFilter kf : filters) {
rewrittenFilters.add(new KeyedFilter(kf.key(), QueryBuilder.rewriteQuery(kf.filter(),
rewrittenFilters.add(new KeyedFilter(kf.key(), QueryBuilder.rewriteQuery(kf.filter(),
context.getQueryShardContext())));
}
return new FiltersAggregatorFactory(name, rewrittenFilters, keyed, otherBucket, otherBucketKey, context, parent,
@ -236,7 +238,7 @@ public class FiltersAggregationBuilder extends AbstractAggregationBuilder<Filter
if (token == XContentParser.Token.FIELD_NAME) {
key = parser.currentName();
} else {
QueryBuilder filter = context.parseInnerQueryBuilder();
QueryBuilder filter = parseInnerQueryBuilder(context.parser());
keyedFilters.add(new FiltersAggregator.KeyedFilter(key, filter));
}
}
@ -248,7 +250,7 @@ public class FiltersAggregationBuilder extends AbstractAggregationBuilder<Filter
if (FILTERS_FIELD.match(currentFieldName)) {
nonKeyedFilters = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
QueryBuilder filter = context.parseInnerQueryBuilder();
QueryBuilder filter = parseInnerQueryBuilder(context.parser());
nonKeyedFilters.add(filter);
}
} else {

View File

@ -49,6 +49,8 @@ import org.elasticsearch.search.internal.SearchContext;
import java.io.IOException;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class SignificantTermsAggregationBuilder extends ValuesSourceAggregationBuilder<ValuesSource, SignificantTermsAggregationBuilder> {
public static final String NAME = "significant_terms";
@ -75,7 +77,7 @@ public class SignificantTermsAggregationBuilder extends ValuesSourceAggregationB
parser.declareString(SignificantTermsAggregationBuilder::executionHint, TermsAggregationBuilder.EXECUTION_HINT_FIELD_NAME);
parser.declareObject(SignificantTermsAggregationBuilder::backgroundFilter,
(p, context) -> context.parseInnerQueryBuilder(),
(p, context) -> parseInnerQueryBuilder(p),
SignificantTermsAggregationBuilder.BACKGROUND_FILTER);
parser.declareField((b, v) -> b.includeExclude(IncludeExclude.merge(v, b.includeExclude())),

View File

@ -25,6 +25,7 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ParseFieldRegistry;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
@ -54,7 +55,7 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
static final ParseField FILTER_DUPLICATE_TEXT_FIELD_NAME = new ParseField(
"filter_duplicate_text");
static final TermsAggregator.BucketCountThresholds DEFAULT_BUCKET_COUNT_THRESHOLDS =
static final TermsAggregator.BucketCountThresholds DEFAULT_BUCKET_COUNT_THRESHOLDS =
SignificantTermsAggregationBuilder.DEFAULT_BUCKET_COUNT_THRESHOLDS;
static final SignificanceHeuristic DEFAULT_SIGNIFICANCE_HEURISTIC = SignificantTermsAggregationBuilder.DEFAULT_SIGNIFICANCE_HEURISTIC;
@ -85,15 +86,15 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
TermsAggregationBuilder.REQUIRED_SIZE_FIELD_NAME);
parser.declareString(SignificantTextAggregationBuilder::fieldName, FIELD_NAME);
parser.declareStringArray(SignificantTextAggregationBuilder::sourceFieldNames, SOURCE_FIELDS_NAME);
parser.declareBoolean(SignificantTextAggregationBuilder::filterDuplicateText,
FILTER_DUPLICATE_TEXT_FIELD_NAME);
parser.declareObject(SignificantTextAggregationBuilder::backgroundFilter,
(p, context) -> context.parseInnerQueryBuilder(),
(p, context) -> AbstractQueryBuilder.parseInnerQueryBuilder(p),
SignificantTermsAggregationBuilder.BACKGROUND_FILTER);
parser.declareField((b, v) -> b.includeExclude(IncludeExclude.merge(v, b.includeExclude())),
@ -129,20 +130,20 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
public TermsAggregator.BucketCountThresholds bucketCountThresholds() {
return bucketCountThresholds;
}
@Override
public SignificantTextAggregationBuilder subAggregations(Builder subFactories) {
throw new AggregationInitializationException("Aggregator [" + name + "] of type ["
+ getType() + "] cannot accept sub-aggregations");
}
}
@Override
public SignificantTextAggregationBuilder subAggregation(AggregationBuilder aggregation) {
throw new AggregationInitializationException("Aggregator [" + name + "] of type ["
+ getType() + "] cannot accept sub-aggregations");
}
}
public SignificantTextAggregationBuilder bucketCountThresholds(
TermsAggregator.BucketCountThresholds bucketCountThresholds) {
if (bucketCountThresholds == null) {
@ -190,18 +191,18 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
return this;
}
/**
* Selects the fields to load from _source JSON and analyze.
* If none are specified, the indexed "fieldName" value is assumed
* If none are specified, the indexed "fieldName" value is assumed
* to also be the name of the JSON field holding the value
*/
public SignificantTextAggregationBuilder sourceFieldNames(List<String> names) {
this.sourceFieldNames = names.toArray(new String [names.size()]);
return this;
}
/**
* Control if duplicate paragraphs of text should try be filtered from the
* statistical text analysis. Can improve results but slows down analysis.
@ -288,7 +289,7 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
* @param fieldName
* the name of the text field that will be the subject of this
* aggregation
*
*
*/
public SignificantTextAggregationBuilder(String name, String fieldName) {
super(name);
@ -344,7 +345,7 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
if (sourceFieldNames != null) {
builder.array(SOURCE_FIELDS_NAME.getPreferredName(), sourceFieldNames);
}
if (filterDuplicateText) {
builder.field(FILTER_DUPLICATE_TEXT_FIELD_NAME.getPreferredName(), filterDuplicateText);
}
@ -356,7 +357,7 @@ public class SignificantTextAggregationBuilder extends AbstractAggregationBuilde
includeExclude.toXContent(builder, params);
}
significanceHeuristic.toXContent(builder, params);
builder.endObject();
return builder;
}

View File

@ -29,7 +29,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.SearchScript;
import org.elasticsearch.search.aggregations.AbstractAggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationInitializationException;
@ -671,9 +670,9 @@ public class TopHitsAggregationBuilder extends AbstractAggregationBuilder<TopHit
}
factory.scriptFields(scriptFields);
} else if (SearchSourceBuilder.HIGHLIGHT_FIELD.match(currentFieldName)) {
factory.highlighter(HighlightBuilder.fromXContent(context));
factory.highlighter(HighlightBuilder.fromXContent(parser));
} else if (SearchSourceBuilder.SORT_FIELD.match(currentFieldName)) {
List<SortBuilder<?>> sorts = SortBuilder.fromXContent(context);
List<SortBuilder<?>> sorts = SortBuilder.fromXContent(parser);
factory.sorts(sorts);
} else {
throw new ParsingException(parser.getTokenLocation(), "Unknown key for a " + token + " in [" + currentFieldName + "].",
@ -696,7 +695,7 @@ public class TopHitsAggregationBuilder extends AbstractAggregationBuilder<TopHit
}
factory.fieldDataFields(fieldDataFields);
} else if (SearchSourceBuilder.SORT_FIELD.match(currentFieldName)) {
List<SortBuilder<?>> sorts = SortBuilder.fromXContent(context);
List<SortBuilder<?>> sorts = SortBuilder.fromXContent(parser);
factory.sorts(sorts);
} else if (SearchSourceBuilder._SOURCE_FIELD.match(currentFieldName)) {
factory.fetchSource(FetchSourceContext.fromXContent(context.parser()));

View File

@ -63,6 +63,8 @@ import java.util.Collections;
import java.util.List;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
/**
* A search source builder allowing to easily build search source. Simple
* construction using
@ -1008,15 +1010,15 @@ public final class SearchSourceBuilder extends ToXContentToBytes implements Writ
}
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERY_FIELD.match(currentFieldName)) {
queryBuilder = context.parseInnerQueryBuilder();
queryBuilder = parseInnerQueryBuilder(parser);
} else if (POST_FILTER_FIELD.match(currentFieldName)) {
postQueryBuilder = context.parseInnerQueryBuilder();
postQueryBuilder = parseInnerQueryBuilder(parser);
} else if (_SOURCE_FIELD.match(currentFieldName)) {
fetchSourceContext = FetchSourceContext.fromXContent(context.parser());
} else if (SCRIPT_FIELDS_FIELD.match(currentFieldName)) {
scriptFields = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
scriptFields.add(new ScriptField(context));
scriptFields.add(new ScriptField(parser));
}
} else if (INDICES_BOOST_FIELD.match(currentFieldName)) {
DEPRECATION_LOGGER.deprecated(
@ -1035,11 +1037,11 @@ public final class SearchSourceBuilder extends ToXContentToBytes implements Writ
|| AGGS_FIELD.match(currentFieldName)) {
aggregations = AggregatorFactories.parseAggregators(context);
} else if (HIGHLIGHT_FIELD.match(currentFieldName)) {
highlightBuilder = HighlightBuilder.fromXContent(context);
highlightBuilder = HighlightBuilder.fromXContent(parser);
} else if (SUGGEST_FIELD.match(currentFieldName)) {
suggestBuilder = SuggestBuilder.fromXContent(context.parser());
} else if (SORT_FIELD.match(currentFieldName)) {
sorts = new ArrayList<>(SortBuilder.fromXContent(context));
sorts = new ArrayList<>(SortBuilder.fromXContent(parser));
} else if (RESCORE_FIELD.match(currentFieldName)) {
rescoreBuilders = new ArrayList<>();
rescoreBuilders.add(RescoreBuilder.parseFromXContent(context));
@ -1085,7 +1087,7 @@ public final class SearchSourceBuilder extends ToXContentToBytes implements Writ
indexBoosts.add(new IndexBoost(context));
}
} else if (SORT_FIELD.match(currentFieldName)) {
sorts = new ArrayList<>(SortBuilder.fromXContent(context));
sorts = new ArrayList<>(SortBuilder.fromXContent(parser));
} else if (RESCORE_FIELD.match(currentFieldName)) {
rescoreBuilders = new ArrayList<>();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
@ -1373,9 +1375,8 @@ public final class SearchSourceBuilder extends ToXContentToBytes implements Writ
out.writeBoolean(ignoreFailure);
}
public ScriptField(QueryParseContext context) throws IOException {
public ScriptField(XContentParser parser) throws IOException {
boolean ignoreFailure = false;
XContentParser parser = context.parser();
String scriptFieldName = parser.currentName();
Script script = null;

View File

@ -61,12 +61,12 @@ public class CollapseBuilder implements Writeable, ToXContentObject {
PARSER.declareField((parser, builder, context) -> {
XContentParser.Token currentToken = parser.currentToken();
if (currentToken == XContentParser.Token.START_OBJECT) {
builder.setInnerHits(InnerHitBuilder.fromXContent(context));
builder.setInnerHits(InnerHitBuilder.fromXContent(parser));
} else if (currentToken == XContentParser.Token.START_ARRAY) {
List<InnerHitBuilder> innerHitBuilders = new ArrayList<>();
for (currentToken = parser.nextToken(); currentToken != XContentParser.Token.END_ARRAY; currentToken = parser.nextToken()) {
if (currentToken == XContentParser.Token.START_OBJECT) {
innerHitBuilders.add(InnerHitBuilder.fromXContent(context));
innerHitBuilders.add(InnerHitBuilder.fromXContent(parser));
} else {
throw new ParsingException(parser.getTokenLocation(), "Invalid token in inner_hits array");
}

View File

@ -44,6 +44,7 @@ import java.util.Objects;
import java.util.function.BiFunction;
import static org.elasticsearch.common.xcontent.ObjectParser.fromList;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
/**
* This abstract class holds parameters shared by {@link HighlightBuilder} and {@link HighlightBuilder.Field}
@ -593,7 +594,7 @@ public abstract class AbstractHighlighterBuilder<HB extends AbstractHighlighterB
}
}
static <HB extends AbstractHighlighterBuilder<HB>> BiFunction<QueryParseContext, HB, HB> setupParser(
static <HB extends AbstractHighlighterBuilder<HB>> BiFunction<XContentParser, HB, HB> setupParser(
ObjectParser<HB, QueryParseContext> parser) {
parser.declareStringArray(fromList(String.class, HB::preTags), PRE_TAGS_FIELD);
parser.declareStringArray(fromList(String.class, HB::postTags), POST_TAGS_FIELD);
@ -620,16 +621,16 @@ public abstract class AbstractHighlighterBuilder<HB extends AbstractHighlighterB
}, OPTIONS_FIELD);
parser.declareObject(HB::highlightQuery, (XContentParser p, QueryParseContext c) -> {
try {
return c.parseInnerQueryBuilder();
return parseInnerQueryBuilder(p);
} catch (IOException e) {
throw new RuntimeException("Error parsing query", e);
}
}, HIGHLIGHT_QUERY_FIELD);
return (QueryParseContext c, HB hb) -> {
return (XContentParser p, HB hb) -> {
try {
parser.parse(c.parser(), hb, c);
parser.parse(p, hb, null);
if (hb.preTags() != null && hb.postTags() == null) {
throw new ParsingException(c.parser().getTokenLocation(),
throw new ParsingException(p.getTokenLocation(),
"pre_tags are set but post_tags are not set");
}
} catch (IOException e) {

View File

@ -256,7 +256,7 @@ public class HighlightBuilder extends AbstractHighlighterBuilder<HighlightBuilde
return builder;
}
private static final BiFunction<QueryParseContext, HighlightBuilder, HighlightBuilder> PARSER;
private static final BiFunction<XContentParser, HighlightBuilder, HighlightBuilder> PARSER;
static {
ObjectParser<HighlightBuilder, QueryParseContext> parser = new ObjectParser<>("highlight");
parser.declareString(HighlightBuilder::tagsSchema, new ParseField("tags_schema"));
@ -265,8 +265,8 @@ public class HighlightBuilder extends AbstractHighlighterBuilder<HighlightBuilde
FIELDS_FIELD);
PARSER = setupParser(parser);
}
public static HighlightBuilder fromXContent(QueryParseContext c) {
return PARSER.apply(c, new HighlightBuilder());
public static HighlightBuilder fromXContent(XContentParser p) {
return PARSER.apply(p, new HighlightBuilder());
}
public SearchContextHighlight build(QueryShardContext context) throws IOException {
@ -284,7 +284,7 @@ public class HighlightBuilder extends AbstractHighlighterBuilder<HighlightBuilde
final SearchContextHighlight.FieldOptions.Builder fieldOptionsBuilder = new SearchContextHighlight.FieldOptions.Builder();
fieldOptionsBuilder.fragmentOffset(field.fragmentOffset);
if (field.matchedFields != null) {
Set<String> matchedFields = new HashSet<String>(field.matchedFields.length);
Set<String> matchedFields = new HashSet<>(field.matchedFields.length);
Collections.addAll(matchedFields, field.matchedFields);
fieldOptionsBuilder.matchedFields(matchedFields);
}
@ -422,8 +422,8 @@ public class HighlightBuilder extends AbstractHighlighterBuilder<HighlightBuilde
ObjectParser<Field, QueryParseContext> parser = new ObjectParser<>("highlight_field");
parser.declareInt(Field::fragmentOffset, FRAGMENT_OFFSET_FIELD);
parser.declareStringArray(fromList(String.class, Field::matchedFields), MATCHED_FIELDS_FIELD);
BiFunction<QueryParseContext, Field, Field> decoratedParser = setupParser(parser);
PARSER = (XContentParser p, QueryParseContext c, String name) -> decoratedParser.apply(c, new Field(name));
BiFunction<XContentParser, Field, Field> decoratedParser = setupParser(parser);
PARSER = (XContentParser p, QueryParseContext c, String name) -> decoratedParser.apply(p, new Field(name));
}
private final String name;

View File

@ -35,6 +35,8 @@ import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
/**
* Represents a {@link QueryBuilder} and a list of alias names that filters the builder is composed of.
*/
@ -71,7 +73,7 @@ public final class AliasFilter implements Writeable {
* of dependencies we pass in a function that can perform the parsing. */
CheckedFunction<byte[], QueryBuilder, IOException> filterParser = bytes -> {
try (XContentParser parser = XContentFactory.xContent(bytes).createParser(context.getXContentRegistry(), bytes)) {
return context.newParseContext(parser).parseInnerQueryBuilder();
return parseInnerQueryBuilder(parser);
}
};
return ShardSearchRequest.parseAliasFilter(filterParser, indexMetaData, aliases);

View File

@ -34,6 +34,8 @@ import java.io.IOException;
import java.util.Locale;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class QueryRescorerBuilder extends RescoreBuilder<QueryRescorerBuilder> {
public static final String NAME = "query";
@ -56,7 +58,7 @@ public class QueryRescorerBuilder extends RescoreBuilder<QueryRescorerBuilder> {
static {
QUERY_RESCORE_PARSER.declareObject(InnerBuilder::setQueryBuilder, (p, c) -> {
try {
return c.parseInnerQueryBuilder();
return parseInnerQueryBuilder(p);
} catch (IOException e) {
throw new ParsingException(p.getTokenLocation(), "Could not parse inner query", e);
}

View File

@ -26,6 +26,7 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser.ValueType;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexFieldData;
import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested;
import org.elasticsearch.index.fielddata.IndexNumericFieldData;
@ -315,13 +316,13 @@ public class FieldSortBuilder extends SortBuilder<FieldSortBuilder> {
* Creates a new {@link FieldSortBuilder} from the query held by the {@link QueryParseContext} in
* {@link org.elasticsearch.common.xcontent.XContent} format.
*
* @param context the input parse context. The state on the parser contained in this context will be changed as a side effect of this
* @param parser the input parser. The state on the parser contained in this context will be changed as a side effect of this
* method call
* @param fieldName in some sort syntax variations the field name precedes the xContent object that specifies further parameters, e.g.
* in '{ "foo": { "order" : "asc"} }'. When parsing the inner object, the field name can be passed in via this argument
*/
public static FieldSortBuilder fromXContent(QueryParseContext context, String fieldName) throws IOException {
return PARSER.parse(context.parser(), new FieldSortBuilder(fieldName), context);
public static FieldSortBuilder fromXContent(XContentParser parser, String fieldName) throws IOException {
return PARSER.parse(parser, new FieldSortBuilder(fieldName), null);
}
private static ObjectParser<FieldSortBuilder, QueryParseContext> PARSER = new ObjectParser<>(NAME);
@ -332,6 +333,6 @@ public class FieldSortBuilder extends SortBuilder<FieldSortBuilder> {
PARSER.declareString(FieldSortBuilder::unmappedType , UNMAPPED_TYPE);
PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)) , ORDER_FIELD);
PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORT_MODE);
PARSER.declareObject(FieldSortBuilder::setNestedFilter, SortBuilder::parseNestedFilter, NESTED_FILTER_FIELD);
PARSER.declareObject(FieldSortBuilder::setNestedFilter, (p, c) -> SortBuilder.parseNestedFilter(p), NESTED_FILTER_FIELD);
}
}

View File

@ -60,6 +60,7 @@ import java.util.List;
import java.util.Locale;
import java.util.Objects;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
/**
* A geo distance based sorting on a geo point like field.
*/
@ -386,14 +387,13 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
* Creates a new {@link GeoDistanceSortBuilder} from the query held by the {@link QueryParseContext} in
* {@link org.elasticsearch.common.xcontent.XContent} format.
*
* @param context the input parse context. The state on the parser contained in this context will be changed as a
* @param parser the input parser. The state on the parser contained in this context will be changed as a
* side effect of this method call
* @param elementName in some sort syntax variations the field name precedes the xContent object that specifies
* further parameters, e.g. in '{ "foo": { "order" : "asc"} }'. When parsing the inner object,
* the field name can be passed in via this argument
*/
public static GeoDistanceSortBuilder fromXContent(QueryParseContext context, String elementName) throws IOException {
XContentParser parser = context.parser();
public static GeoDistanceSortBuilder fromXContent(XContentParser parser, String elementName) throws IOException {
String fieldName = null;
List<GeoPoint> geoPoints = new ArrayList<>();
DistanceUnit unit = DistanceUnit.DEFAULT;
@ -415,7 +415,7 @@ public class GeoDistanceSortBuilder extends SortBuilder<GeoDistanceSortBuilder>
fieldName = currentName;
} else if (token == XContentParser.Token.START_OBJECT) {
if (NESTED_FILTER_FIELD.match(currentName)) {
nestedFilter = context.parseInnerQueryBuilder();
nestedFilter = parseInnerQueryBuilder(parser);
} else {
// the json in the format of -> field : { lat : 30, lon : 12 }
if (fieldName != null && fieldName.equals(currentName) == false) {

View File

@ -24,6 +24,7 @@ import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.ObjectParser;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.DocValueFormat;
@ -76,13 +77,13 @@ public class ScoreSortBuilder extends SortBuilder<ScoreSortBuilder> {
* Creates a new {@link ScoreSortBuilder} from the query held by the {@link QueryParseContext} in
* {@link org.elasticsearch.common.xcontent.XContent} format.
*
* @param context the input parse context. The state on the parser contained in this context will be changed as a side effect of this
* @param parser the input parser. The state on the parser contained in this context will be changed as a side effect of this
* method call
* @param fieldName in some sort syntax variations the field name precedes the xContent object that specifies further parameters, e.g.
* in '{ "foo": { "order" : "asc"} }'. When parsing the inner object, the field name can be passed in via this argument
*/
public static ScoreSortBuilder fromXContent(QueryParseContext context, String fieldName) throws IOException {
return PARSER.apply(context.parser(), context);
public static ScoreSortBuilder fromXContent(XContentParser parser, String fieldName) throws IOException {
return PARSER.apply(parser, null);
}
private static ObjectParser<ScoreSortBuilder, QueryParseContext> PARSER = new ObjectParser<>(NAME, ScoreSortBuilder::new);

View File

@ -32,6 +32,7 @@ import org.elasticsearch.common.io.stream.Writeable;
import org.elasticsearch.common.xcontent.ConstructingObjectParser;
import org.elasticsearch.common.xcontent.ObjectParser.ValueType;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.AbstractBinaryDocValues;
import org.elasticsearch.index.fielddata.FieldData;
import org.elasticsearch.index.fielddata.IndexFieldData;
@ -221,20 +222,20 @@ public class ScriptSortBuilder extends SortBuilder<ScriptSortBuilder> {
PARSER.declareString((b, v) -> b.order(SortOrder.fromString(v)), ORDER_FIELD);
PARSER.declareString((b, v) -> b.sortMode(SortMode.fromString(v)), SORTMODE_FIELD);
PARSER.declareString(ScriptSortBuilder::setNestedPath , NESTED_PATH_FIELD);
PARSER.declareObject(ScriptSortBuilder::setNestedFilter, SortBuilder::parseNestedFilter, NESTED_FILTER_FIELD);
PARSER.declareObject(ScriptSortBuilder::setNestedFilter, (p,c) -> SortBuilder.parseNestedFilter(p), NESTED_FILTER_FIELD);
}
/**
* Creates a new {@link ScriptSortBuilder} from the query held by the {@link QueryParseContext} in
* {@link org.elasticsearch.common.xcontent.XContent} format.
*
* @param context the input parse context. The state on the parser contained in this context will be changed as a side effect of this
* @param parser the input parser. The state on the parser contained in this context will be changed as a side effect of this
* method call
* @param elementName in some sort syntax variations the field name precedes the xContent object that specifies further parameters, e.g.
* in '{ "foo": { "order" : "asc"} }'. When parsing the inner object, the field name can be passed in via this argument
*/
public static ScriptSortBuilder fromXContent(QueryParseContext context, String elementName) throws IOException {
return PARSER.apply(context.parser(), context);
public static ScriptSortBuilder fromXContent(XContentParser parser, String elementName) throws IOException {
return PARSER.apply(parser, null);
}

View File

@ -32,7 +32,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.fielddata.IndexFieldData.XFieldComparatorSource.Nested;
import org.elasticsearch.index.mapper.ObjectMapper;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.search.DocValueFormat;
@ -46,6 +45,7 @@ import java.util.Objects;
import java.util.Optional;
import static java.util.Collections.unmodifiableMap;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentToBytes implements NamedWriteable {
@ -89,14 +89,13 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
return this.order;
}
public static List<SortBuilder<?>> fromXContent(QueryParseContext context) throws IOException {
public static List<SortBuilder<?>> fromXContent(XContentParser parser) throws IOException {
List<SortBuilder<?>> sortFields = new ArrayList<>(2);
XContentParser parser = context.parser();
XContentParser.Token token = parser.currentToken();
if (token == XContentParser.Token.START_ARRAY) {
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
if (token == XContentParser.Token.START_OBJECT) {
parseCompoundSortField(context, sortFields);
parseCompoundSortField(parser, sortFields);
} else if (token == XContentParser.Token.VALUE_STRING) {
String fieldName = parser.text();
sortFields.add(fieldOrScoreSort(fieldName));
@ -109,7 +108,7 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
String fieldName = parser.text();
sortFields.add(fieldOrScoreSort(fieldName));
} else if (token == XContentParser.Token.START_OBJECT) {
parseCompoundSortField(context, sortFields);
parseCompoundSortField(parser, sortFields);
} else {
throw new IllegalArgumentException("malformed sort format, either start with array, object, or an actual string");
}
@ -124,10 +123,9 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
}
}
private static void parseCompoundSortField(QueryParseContext context, List<SortBuilder<?>> sortFields)
private static void parseCompoundSortField(XContentParser parser, List<SortBuilder<?>> sortFields)
throws IOException {
XContentParser.Token token;
XContentParser parser = context.parser();
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
String fieldName = parser.currentName();
@ -137,9 +135,9 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
sortFields.add(fieldOrScoreSort(fieldName).order(order));
} else {
if (PARSERS.containsKey(fieldName)) {
sortFields.add(PARSERS.get(fieldName).fromXContent(context, fieldName));
sortFields.add(PARSERS.get(fieldName).fromXContent(parser, fieldName));
} else {
sortFields.add(FieldSortBuilder.fromXContent(context, fieldName));
sortFields.add(FieldSortBuilder.fromXContent(parser, fieldName));
}
}
}
@ -201,9 +199,9 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
return nested;
}
protected static QueryBuilder parseNestedFilter(XContentParser parser, QueryParseContext context) {
protected static QueryBuilder parseNestedFilter(XContentParser parser) {
try {
return context.parseInnerQueryBuilder();
return parseInnerQueryBuilder(parser);
} catch (Exception e) {
throw new ParsingException(parser.getTokenLocation(), "Expected " + NESTED_FILTER_FIELD.getPreferredName() + " element.", e);
}
@ -211,6 +209,6 @@ public abstract class SortBuilder<T extends SortBuilder<T>> extends ToXContentTo
@FunctionalInterface
private interface Parser<T extends SortBuilder<?>> {
T fromXContent(QueryParseContext context, String elementName) throws IOException;
T fromXContent(XContentParser parser, String elementName) throws IOException;
}
}

View File

@ -28,15 +28,14 @@ import org.apache.lucene.search.spell.DirectSpellChecker;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.BytesRefBuilder;
import org.apache.lucene.util.CharsRefBuilder;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.ParsedQuery;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.script.ExecutableScript;
import org.elasticsearch.script.TemplateScript;
import org.elasticsearch.search.suggest.Suggest.Suggestion;
import org.elasticsearch.search.suggest.Suggest.Suggestion.Entry;
@ -49,7 +48,6 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
public final class PhraseSuggester extends Suggester<PhraseSuggestionContext> {
private final BytesRef SEPARATOR = new BytesRef(" ");
@ -119,7 +117,7 @@ public final class PhraseSuggester extends Suggester<PhraseSuggestionContext> {
final String querySource = scriptFactory.newInstance(vars).execute();
try (XContentParser parser = XContentFactory.xContent(querySource).createParser(shardContext.getXContentRegistry(),
querySource)) {
QueryBuilder innerQueryBuilder = shardContext.newParseContext(parser).parseInnerQueryBuilder();
QueryBuilder innerQueryBuilder = AbstractQueryBuilder.parseInnerQueryBuilder(parser);
final ParsedQuery parsedQuery = shardContext.toQuery(innerQueryBuilder);
collateMatch = Lucene.exists(searcher, parsedQuery.query());
}

View File

@ -27,7 +27,6 @@ import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.rest.action.search.RestMultiSearchAction;
import org.elasticsearch.test.ESTestCase;
@ -182,6 +181,6 @@ public class MultiSearchRequestTests extends ESTestCase {
@Override
protected NamedXContentRegistry xContentRegistry() {
return new NamedXContentRegistry(singletonList(new NamedXContentRegistry.Entry(QueryBuilder.class,
new ParseField(MatchAllQueryBuilder.NAME), (p, c) -> MatchAllQueryBuilder.fromXContent((QueryParseContext) c))));
new ParseField(MatchAllQueryBuilder.NAME), (p, c) -> MatchAllQueryBuilder.fromXContent(p))));
}
}

View File

@ -123,8 +123,7 @@ public class InnerHitBuilderTests extends ESTestCase {
//fields is printed out as an object but parsed into a List where order matters, we disable shuffling
XContentBuilder shuffled = shuffleXContent(builder, "fields");
XContentParser parser = createParser(shuffled);
QueryParseContext context = new QueryParseContext(parser);
InnerHitBuilder secondInnerHits = InnerHitBuilder.fromXContent(context);
InnerHitBuilder secondInnerHits = InnerHitBuilder.fromXContent(parser);
assertThat(innerHit, not(sameInstance(secondInnerHits)));
assertThat(innerHit, equalTo(secondInnerHits));
assertThat(innerHit.hashCode(), equalTo(secondInnerHits.hashCode()));

View File

@ -36,6 +36,7 @@ import org.junit.BeforeClass;
import java.io.IOException;
import static java.util.Collections.emptyList;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class QueryParseContextTests extends ESTestCase {
private static NamedXContentRegistry xContentRegistry;
@ -64,40 +65,11 @@ public class QueryParseContextTests extends ESTestCase {
this.threadContext.close();
}
public void testParseTopLevelBuilder() throws IOException {
QueryBuilder query = new MatchQueryBuilder("foo", "bar");
String requestBody = "{ \"query\" : " + query.toString() + "}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, requestBody)) {
QueryParseContext context = new QueryParseContext(parser);
QueryBuilder actual = context.parseTopLevelQueryBuilder();
assertEquals(query, actual);
}
}
public void testParseTopLevelBuilderEmptyObject() throws IOException {
String requestBody = "{}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, requestBody)) {
QueryParseContext context = new QueryParseContext(parser);
QueryBuilder query = context.parseTopLevelQueryBuilder();
assertNull(query);
}
}
public void testParseTopLevelBuilderUnknownParameter() throws IOException {
String requestBody = "{ \"foo\" : \"bar\"}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, requestBody)) {
QueryParseContext context = new QueryParseContext(parser);
ParsingException exception = expectThrows(ParsingException.class, () -> context.parseTopLevelQueryBuilder());
assertEquals("request does not support [foo]", exception.getMessage());
}
}
public void testParseInnerQueryBuilder() throws IOException {
QueryBuilder query = new MatchQueryBuilder("foo", "bar");
String source = query.toString();
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryParseContext context = new QueryParseContext(parser);
QueryBuilder actual = context.parseInnerQueryBuilder();
QueryBuilder actual = parseInnerQueryBuilder(parser);
assertEquals(query, actual);
}
}
@ -107,29 +79,26 @@ public class QueryParseContextTests extends ESTestCase {
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
parser.nextToken();
parser.nextToken(); // don't start with START_OBJECT to provoke exception
QueryParseContext context = new QueryParseContext(parser);
ParsingException exception = expectThrows(ParsingException.class, () -> context.parseInnerQueryBuilder());
ParsingException exception = expectThrows(ParsingException.class, () -> parseInnerQueryBuilder(parser));
assertEquals("[_na] query malformed, must start with start_object", exception.getMessage());
}
source = "{}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryParseContext context = new QueryParseContext(parser);
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> context.parseInnerQueryBuilder());
IllegalArgumentException exception = expectThrows(IllegalArgumentException.class, () -> parseInnerQueryBuilder(parser));
assertEquals("query malformed, empty clause found at [1:2]", exception.getMessage());
}
source = "{ \"foo\" : \"bar\" }";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryParseContext context = new QueryParseContext(parser);
ParsingException exception = expectThrows(ParsingException.class, () -> context.parseInnerQueryBuilder());
ParsingException exception = expectThrows(ParsingException.class, () -> parseInnerQueryBuilder(parser));
assertEquals("[foo] query malformed, no start_object after query name", exception.getMessage());
}
source = "{ \"foo\" : {} }";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, source)) {
QueryParseContext context = new QueryParseContext(parser);
ParsingException exception = expectThrows(ParsingException.class, () -> context.parseInnerQueryBuilder());
ParsingException exception = expectThrows(ParsingException.class, () -> parseInnerQueryBuilder(parser));
assertEquals("no [query] registered for [foo]", exception.getMessage());
}
}

View File

@ -65,6 +65,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertBooleanSubQuery;
import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertDisjunctionSubQuery;
@ -521,7 +522,7 @@ public class QueryStringQueryBuilderTests extends AbstractQueryTestCase<QueryStr
}
builder.endObject();
QueryBuilder queryBuilder = new QueryParseContext(createParser(builder)).parseInnerQueryBuilder();
QueryBuilder queryBuilder = parseInnerQueryBuilder(createParser(builder));
TooComplexToDeterminizeException e = expectThrows(TooComplexToDeterminizeException.class,
() -> queryBuilder.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("Determinizing [ac]*"));
@ -545,8 +546,7 @@ public class QueryStringQueryBuilderTests extends AbstractQueryTestCase<QueryStr
}
builder.endObject();
QueryStringQueryBuilder queryBuilder = (QueryStringQueryBuilder) new QueryParseContext(createParser(builder))
.parseInnerQueryBuilder();
QueryStringQueryBuilder queryBuilder = (QueryStringQueryBuilder) parseInnerQueryBuilder(createParser(builder));
assertFalse(queryBuilder.enablePositionIncrements());
}

View File

@ -20,6 +20,7 @@
package org.elasticsearch.index.query.functionscore;
import com.fasterxml.jackson.core.JsonParseException;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.MatchAllDocsQuery;
import org.apache.lucene.search.Query;
@ -40,7 +41,6 @@ import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.RandomQueryBuilder;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.query.WrapperQueryBuilder;
@ -796,9 +796,9 @@ public class FunctionScoreQueryBuilderTests extends AbstractQueryTestCase<Functi
return NAME;
}
public static RandomScoreFunctionBuilder fromXContent(QueryParseContext parseContext)
public static RandomScoreFunctionBuilder fromXContent(XContentParser parser)
throws IOException, ParsingException {
RandomScoreFunctionBuilder builder = RandomScoreFunctionBuilder.fromXContent(parseContext);
RandomScoreFunctionBuilder builder = RandomScoreFunctionBuilder.fromXContent(parser);
RandomScoreFunctionBuilderWithFixedSeed replacement = new RandomScoreFunctionBuilderWithFixedSeed();
if (builder.getSeed() != null) {
replacement.seed(builder.getSeed());

View File

@ -25,7 +25,6 @@ import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.plugin.DummyQueryParserPlugin.DummyQuery;
@ -51,8 +50,8 @@ public class DummyQueryBuilder extends AbstractQueryBuilder<DummyQueryBuilder> {
builder.startObject(NAME).endObject();
}
public static DummyQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser.Token token = parseContext.parser().nextToken();
public static DummyQueryBuilder fromXContent(XContentParser parser) throws IOException {
XContentParser.Token token = parser.nextToken();
assert token == XContentParser.Token.END_OBJECT;
return new DummyQueryBuilder();
}

View File

@ -0,0 +1,82 @@
/*
* Licensed to Elasticsearch under one or more contributor
* license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright
* ownership. Elasticsearch licenses this file to you under
* the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.rest.action;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.NamedXContentRegistry;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.ESTestCase;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.io.IOException;
import static java.util.Collections.emptyList;
public class RestActionsTests extends ESTestCase {
private static NamedXContentRegistry xContentRegistry;
@BeforeClass
public static void init() {
xContentRegistry = new NamedXContentRegistry(new SearchModule(Settings.EMPTY, false, emptyList()).getNamedXContents());
}
@AfterClass
public static void cleanup() {
xContentRegistry = null;
}
public void testParseTopLevelBuilder() throws IOException {
QueryBuilder query = new MatchQueryBuilder("foo", "bar");
String requestBody = "{ \"query\" : " + query.toString() + "}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, requestBody)) {
QueryBuilder actual = RestActions.getQueryContent(parser);
assertEquals(query, actual);
}
}
public void testParseTopLevelBuilderEmptyObject() throws IOException {
String requestBody = "{}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, requestBody)) {
QueryBuilder query = RestActions.getQueryContent(parser);
assertNull(query);
}
}
public void testParseTopLevelBuilderUnknownParameter() throws IOException {
String requestBody = "{ \"foo\" : \"bar\"}";
try (XContentParser parser = createParser(JsonXContent.jsonXContent, requestBody)) {
ParsingException exception = expectThrows(ParsingException.class, () -> RestActions.getQueryContent(parser));
assertEquals("request does not support [foo]", exception.getMessage());
}
}
@Override
protected NamedXContentRegistry xContentRegistry() {
return xContentRegistry;
}
}

View File

@ -43,7 +43,6 @@ import org.elasticsearch.index.mapper.TextFieldMapper;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchModule;
@ -138,11 +137,10 @@ public class HighlightBuilderTests extends ESTestCase {
}
XContentParser parser = createParser(shuffled);
QueryParseContext context = new QueryParseContext(parser);
parser.nextToken();
HighlightBuilder secondHighlightBuilder;
try {
secondHighlightBuilder = HighlightBuilder.fromXContent(context);
secondHighlightBuilder = HighlightBuilder.fromXContent(parser);
} catch (RuntimeException e) {
throw new RuntimeException("Error parsing " + highlightBuilder, e);
}
@ -179,8 +177,7 @@ public class HighlightBuilderTests extends ESTestCase {
private <T extends Throwable> T expectParseThrows(Class<T> exceptionClass, String highlightElement) throws IOException {
XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement);
QueryParseContext context = new QueryParseContext(parser);
return expectThrows(exceptionClass, () -> HighlightBuilder.fromXContent(context));
return expectThrows(exceptionClass, () -> HighlightBuilder.fromXContent(parser));
}
/**
@ -390,8 +387,7 @@ public class HighlightBuilderTests extends ESTestCase {
"}\n";
XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement);
QueryParseContext context = new QueryParseContext(parser);
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(context);
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
assertArrayEquals("setting tags_schema 'styled' should alter pre_tags", HighlightBuilder.DEFAULT_STYLED_PRE_TAG,
highlightBuilder.preTags());
assertArrayEquals("setting tags_schema 'styled' should alter post_tags", HighlightBuilder.DEFAULT_STYLED_POST_TAGS,
@ -402,8 +398,7 @@ public class HighlightBuilderTests extends ESTestCase {
"}\n";
parser = createParser(JsonXContent.jsonXContent, highlightElement);
context = new QueryParseContext(parser);
highlightBuilder = HighlightBuilder.fromXContent(context);
highlightBuilder = HighlightBuilder.fromXContent(parser);
assertArrayEquals("setting tags_schema 'default' should alter pre_tags", HighlightBuilder.DEFAULT_PRE_TAGS,
highlightBuilder.preTags());
assertArrayEquals("setting tags_schema 'default' should alter post_tags", HighlightBuilder.DEFAULT_POST_TAGS,
@ -423,22 +418,19 @@ public class HighlightBuilderTests extends ESTestCase {
String highlightElement = "{ }";
XContentParser parser = createParser(JsonXContent.jsonXContent, highlightElement);
QueryParseContext context = new QueryParseContext(parser);
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(context);
HighlightBuilder highlightBuilder = HighlightBuilder.fromXContent(parser);
assertEquals("expected plain HighlightBuilder", new HighlightBuilder(), highlightBuilder);
highlightElement = "{ \"fields\" : { } }";
parser = createParser(JsonXContent.jsonXContent, highlightElement);
context = new QueryParseContext(parser);
highlightBuilder = HighlightBuilder.fromXContent(context);
highlightBuilder = HighlightBuilder.fromXContent(parser);
assertEquals("defining no field should return plain HighlightBuilder", new HighlightBuilder(), highlightBuilder);
highlightElement = "{ \"fields\" : { \"foo\" : { } } }";
parser = createParser(JsonXContent.jsonXContent, highlightElement);
context = new QueryParseContext(parser);
highlightBuilder = HighlightBuilder.fromXContent(context);
highlightBuilder = HighlightBuilder.fromXContent(parser);
assertEquals("expected HighlightBuilder with field", new HighlightBuilder().field(new Field("foo")), highlightBuilder);
}

View File

@ -40,7 +40,6 @@ import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.IndexSettings;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.RandomQueryBuilder;
import org.elasticsearch.index.shard.ShardId;
@ -50,6 +49,7 @@ import org.elasticsearch.search.AbstractSearchTestCase;
import java.io.IOException;
import java.util.Base64;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@ -165,7 +165,7 @@ public class ShardSearchTransportRequestTests extends AbstractSearchTestCase {
public QueryBuilder aliasFilter(IndexMetaData indexMetaData, String... aliasNames) {
CheckedFunction<byte[], QueryBuilder, IOException> filterParser = bytes -> {
try (XContentParser parser = XContentFactory.xContent(bytes).createParser(xContentRegistry(), bytes)) {
return new QueryParseContext(parser).parseInnerQueryBuilder();
return parseInnerQueryBuilder(parser);
}
};
return ShardSearchRequest.parseAliasFilter(filterParser, indexMetaData, aliasNames);

View File

@ -45,13 +45,11 @@ import org.elasticsearch.index.mapper.ObjectMapper.Nested;
import org.elasticsearch.index.query.IdsQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.indices.fielddata.cache.IndicesFieldDataCache;
import org.elasticsearch.script.MockScriptEngine;
import org.elasticsearch.script.ScriptContext;
import org.elasticsearch.script.ScriptEngine;
import org.elasticsearch.script.ScriptModule;
import org.elasticsearch.script.ScriptService;
@ -63,7 +61,6 @@ import org.junit.AfterClass;
import org.junit.BeforeClass;
import java.io.IOException;
import java.nio.file.Path;
import java.util.Collections;
import java.util.Map;
import java.util.function.Function;
@ -106,7 +103,7 @@ public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends EST
protected abstract T mutate(T original) throws IOException;
/** Parse the sort from xContent. Just delegate to the SortBuilder's static fromXContent method. */
protected abstract T fromXContent(QueryParseContext context, String fieldName) throws IOException;
protected abstract T fromXContent(XContentParser parser, String fieldName) throws IOException;
/**
* Test that creates new sort from a random test sort and checks both for equality
@ -131,8 +128,7 @@ public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends EST
String elementName = itemParser.currentName();
itemParser.nextToken();
QueryParseContext context = new QueryParseContext(itemParser);
T parsedItem = fromXContent(context, elementName);
T parsedItem = fromXContent(itemParser, elementName);
assertNotSame(testItem, parsedItem);
assertEquals(testItem, parsedItem);
assertEquals(testItem.hashCode(), parsedItem.hashCode());
@ -241,7 +237,7 @@ public abstract class AbstractSortTestCase<T extends SortBuilder<T>> extends EST
private T copy(T original) throws IOException {
/* The cast below is required to make Java 9 happy. Java 8 infers the T in copyWriterable to be the same as AbstractSortTestCase's
* T but Java 9 infers it to be SortBuilder. */
return (T) copyWriteable(original, namedWriteableRegistry,
return copyWriteable(original, namedWriteableRegistry,
namedWriteableRegistry.getReader(SortBuilder.class, original.getWriteableName()));
}
}

View File

@ -22,7 +22,6 @@ package org.elasticsearch.search.sort;
import org.apache.lucene.search.SortField;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.DocValueFormat;
import java.io.IOException;
@ -133,10 +132,8 @@ public class FieldSortBuilderTests extends AbstractSortTestCase<FieldSortBuilder
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
try {
FieldSortBuilder.fromXContent(context, "");
FieldSortBuilder.fromXContent(parser, "");
fail("adding reverse sorting option should fail with an exception");
} catch (IllegalArgumentException e) {
// all good
@ -145,7 +142,7 @@ public class FieldSortBuilderTests extends AbstractSortTestCase<FieldSortBuilder
@Override
protected FieldSortBuilder fromXContent(QueryParseContext context, String fieldName) throws IOException {
return FieldSortBuilder.fromXContent(context, fieldName);
protected FieldSortBuilder fromXContent(XContentParser parser, String fieldName) throws IOException {
return FieldSortBuilder.fromXContent(parser, fieldName);
}
}

View File

@ -32,7 +32,6 @@ import org.elasticsearch.index.mapper.GeoPointFieldMapper;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.query.GeoValidationMethod;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.search.DocValueFormat;
import org.elasticsearch.test.geo.RandomGeoGenerator;
@ -206,9 +205,8 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
XContentParser itemParser = createParser(JsonXContent.jsonXContent, json);
itemParser.nextToken();
QueryParseContext context = new QueryParseContext(itemParser);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> GeoDistanceSortBuilder.fromXContent(context, ""));
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> GeoDistanceSortBuilder.fromXContent(itemParser, ""));
assertEquals("sort_mode [sum] isn't supported for sorting by geo distance", e.getMessage());
}
@ -231,9 +229,7 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
XContentParser itemParser = createParser(JsonXContent.jsonXContent, json);
itemParser.nextToken();
QueryParseContext context = new QueryParseContext(itemParser);
GeoDistanceSortBuilder result = GeoDistanceSortBuilder.fromXContent(context, json);
GeoDistanceSortBuilder result = GeoDistanceSortBuilder.fromXContent(itemParser, json);
assertEquals("[-19.700583312660456, -2.8225036337971687, "
+ "31.537466906011105, -74.63590376079082, "
+ "43.71844606474042, -5.548660643398762, "
@ -353,14 +349,13 @@ public class GeoDistanceSortBuilderTests extends AbstractSortTestCase<GeoDistanc
private GeoDistanceSortBuilder parse(XContentBuilder sortBuilder) throws Exception {
XContentParser parser = createParser(sortBuilder);
QueryParseContext parseContext = new QueryParseContext(parser);
parser.nextToken();
return GeoDistanceSortBuilder.fromXContent(parseContext, null);
return GeoDistanceSortBuilder.fromXContent(parser, null);
}
@Override
protected GeoDistanceSortBuilder fromXContent(QueryParseContext context, String fieldName) throws IOException {
return GeoDistanceSortBuilder.fromXContent(context, fieldName);
protected GeoDistanceSortBuilder fromXContent(XContentParser parser, String fieldName) throws IOException {
return GeoDistanceSortBuilder.fromXContent(parser, fieldName);
}
public void testCommonCaseIsOptimized() throws IOException {

View File

@ -23,7 +23,6 @@ package org.elasticsearch.search.sort;
import org.apache.lucene.search.SortField;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.DocValueFormat;
import java.io.IOException;
@ -67,8 +66,7 @@ public class ScoreSortBuilderTests extends AbstractSortTestCase<ScoreSortBuilder
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
ScoreSortBuilder scoreSort = ScoreSortBuilder.fromXContent(context, "_score");
ScoreSortBuilder scoreSort = ScoreSortBuilder.fromXContent(parser, "_score");
assertEquals(order, scoreSort.order());
}
@ -80,10 +78,8 @@ public class ScoreSortBuilderTests extends AbstractSortTestCase<ScoreSortBuilder
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
try {
ScoreSortBuilder.fromXContent(context, "_score");
ScoreSortBuilder.fromXContent(parser, "_score");
fail("adding reverse sorting option should fail with an exception");
} catch (IllegalArgumentException e) {
// all good
@ -97,7 +93,7 @@ public class ScoreSortBuilderTests extends AbstractSortTestCase<ScoreSortBuilder
}
@Override
protected ScoreSortBuilder fromXContent(QueryParseContext context, String fieldName) throws IOException {
return ScoreSortBuilder.fromXContent(context, fieldName);
protected ScoreSortBuilder fromXContent(XContentParser parser, String fieldName) throws IOException {
return ScoreSortBuilder.fromXContent(parser, fieldName);
}
}

View File

@ -23,7 +23,6 @@ package org.elasticsearch.search.sort;
import org.apache.lucene.search.SortField;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.DocValueFormat;
@ -171,8 +170,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(context, null);
ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(parser, null);
assertEquals("doc['field_name'].value * factor", builder.script().getIdOrCode());
assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang());
assertEquals(1.1, builder.script().getParams().get("factor"));
@ -197,8 +195,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(context, null);
ScriptSortBuilder builder = ScriptSortBuilder.fromXContent(parser, null);
assertEquals("doc['field_name'].value", builder.script().getIdOrCode());
assertEquals(Script.DEFAULT_SCRIPT_LANG, builder.script().getLang());
assertEquals(builder.script().getParams(), Collections.emptyMap());
@ -217,8 +214,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(context, null));
Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(parser, null));
assertEquals("[_script] unknown field [bad_field], parser not found", e.getMessage());
}
@ -230,8 +226,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(context, null));
Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(parser, null));
assertEquals("[_script] unknown field [bad_field], parser not found", e.getMessage());
}
@ -242,8 +237,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
parser.nextToken();
parser.nextToken();
QueryParseContext context = new QueryParseContext(parser);
Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(context, null));
Exception e = expectThrows(IllegalArgumentException.class, () -> ScriptSortBuilder.fromXContent(parser, null));
assertEquals("[_script] script doesn't support values of type: START_ARRAY", e.getMessage());
}
@ -258,7 +252,7 @@ public class ScriptSortBuilderTests extends AbstractSortTestCase<ScriptSortBuild
}
@Override
protected ScriptSortBuilder fromXContent(QueryParseContext context, String fieldName) throws IOException {
return ScriptSortBuilder.fromXContent(context, fieldName);
protected ScriptSortBuilder fromXContent(XContentParser parser, String fieldName) throws IOException {
return ScriptSortBuilder.fromXContent(parser, fieldName);
}
}

View File

@ -27,7 +27,6 @@ import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.search.SearchModule;
import org.elasticsearch.test.ESTestCase;
import org.junit.AfterClass;
@ -237,12 +236,11 @@ public class SortBuilderTests extends ESTestCase {
private List<SortBuilder<?>> parseSort(String jsonString) throws IOException {
XContentParser itemParser = createParser(JsonXContent.jsonXContent, jsonString);
QueryParseContext context = new QueryParseContext(itemParser);
assertEquals(XContentParser.Token.START_OBJECT, itemParser.nextToken());
assertEquals(XContentParser.Token.FIELD_NAME, itemParser.nextToken());
assertEquals("sort", itemParser.currentName());
itemParser.nextToken();
return SortBuilder.fromXContent(context);
return SortBuilder.fromXContent(itemParser);
}
}

View File

@ -68,3 +68,9 @@ This comma-separation for retrieving multiple pieces of information has been
removed.. `GET /_all` can be used to retrieve all aliases, settings, and
mappings for all indices. In order to retrieve only the mappings for an index,
`GET /myindex/_mappings` (or `_aliases`, or `_settings`).
==== Dissallow using `_cache` and `_cache_key`
The `_cache` and `_cache_key` options in queries have been deprecated since version 2.0.0 and
have been ignored since then, issuing a deprecation warning. These options have now been completely
removed, so using them now will throw an error.

View File

@ -45,7 +45,6 @@ import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.index.query.InnerHitContextBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
@ -242,8 +241,7 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
builder.endObject();
}
public static HasChildQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static HasChildQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String childType = null;
ScoreMode scoreMode = ScoreMode.None;
@ -258,13 +256,11 @@ public class HasChildQueryBuilder extends AbstractQueryBuilder<HasChildQueryBuil
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERY_FIELD.match(currentFieldName)) {
iqb = parseContext.parseInnerQueryBuilder();
iqb = parseInnerQueryBuilder(parser);
} else if (INNER_HITS_FIELD.match(currentFieldName)) {
innerHitBuilder = InnerHitBuilder.fromXContent(parseContext);
innerHitBuilder = InnerHitBuilder.fromXContent(parser);
} else {
throw new ParsingException(parser.getTokenLocation(), "[has_child] query does not support [" + currentFieldName + "]");
}

View File

@ -39,7 +39,6 @@ import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.InnerHitBuilder;
import org.elasticsearch.index.query.InnerHitContextBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
@ -282,8 +281,7 @@ public class HasParentQueryBuilder extends AbstractQueryBuilder<HasParentQueryBu
builder.endObject();
}
public static HasParentQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static HasParentQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String parentType = null;
boolean score = false;
@ -299,9 +297,9 @@ public class HasParentQueryBuilder extends AbstractQueryBuilder<HasParentQueryBu
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (QUERY_FIELD.match(currentFieldName)) {
iqb = parseContext.parseInnerQueryBuilder();
iqb = parseInnerQueryBuilder(parser);
} else if (INNER_HITS_FIELD.match(currentFieldName)) {
innerHits = InnerHitBuilder.fromXContent(parseContext);
innerHits = InnerHitBuilder.fromXContent(parser);
} else {
throw new ParsingException(parser.getTokenLocation(),
"[has_parent] query does not support [" + currentFieldName + "]");

View File

@ -36,7 +36,6 @@ import org.elasticsearch.index.mapper.DocumentMapper;
import org.elasticsearch.index.mapper.ParentFieldMapper;
import org.elasticsearch.index.mapper.TypeFieldMapper;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.join.mapper.ParentIdFieldMapper;
@ -121,8 +120,7 @@ public final class ParentIdQueryBuilder extends AbstractQueryBuilder<ParentIdQue
builder.endObject();
}
public static ParentIdQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static ParentIdQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String type = null;
String id = null;

View File

@ -68,7 +68,6 @@ import org.elasticsearch.index.mapper.MapperService;
import org.elasticsearch.index.mapper.ParsedDocument;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryRewriteContext;
import org.elasticsearch.index.query.QueryShardContext;
import org.elasticsearch.index.query.QueryShardException;
@ -285,8 +284,7 @@ public class PercolateQueryBuilder extends AbstractQueryBuilder<PercolateQueryBu
builder.endObject();
}
public static PercolateQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
public static PercolateQueryBuilder fromXContent(XContentParser parser) throws IOException {
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String field = null;

View File

@ -72,6 +72,8 @@ import java.util.List;
import java.util.Map;
import java.util.function.Supplier;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
public class PercolatorFieldMapper extends FieldMapper {
public static final XContentType QUERY_BUILDER_CONTENT_TYPE = XContentType.SMILE;
@ -348,7 +350,7 @@ public class PercolatorFieldMapper extends FieldMapper {
private static QueryBuilder parseQueryBuilder(QueryParseContext context, XContentLocation location) {
try {
return context.parseInnerQueryBuilder();
return parseInnerQueryBuilder(context.parser());
} catch (IOException e) {
throw new ParsingException(location, "Failed to parse", e);
}

View File

@ -58,7 +58,6 @@ import org.elasticsearch.index.query.ConstantScoreQueryBuilder;
import org.elasticsearch.index.query.DisMaxQueryBuilder;
import org.elasticsearch.index.query.MatchAllQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardException;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
@ -85,6 +84,7 @@ import java.util.Map;
import java.util.function.Function;
import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchPhraseQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchQuery;
@ -474,10 +474,7 @@ public class PercolatorFieldMapperTests extends ESSingleNodeTestCase {
private void assertQueryBuilder(BytesRef actual, QueryBuilder expected) throws IOException {
XContentParser sourceParser = createParser(PercolatorFieldMapper.QUERY_BUILDER_CONTENT_TYPE.xContent(),
new BytesArray(actual));
QueryParseContext qsc = indexService.newQueryShardContext(
randomInt(20), null, () -> { throw new UnsupportedOperationException(); })
.newParseContext(sourceParser);
assertThat(qsc.parseInnerQueryBuilder(), equalTo(expected));
assertThat(parseInnerQueryBuilder(sourceParser), equalTo(expected));
}
public void testEmptyName() throws Exception {

View File

@ -29,7 +29,6 @@ import org.elasticsearch.common.lucene.search.Queries;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentParser;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.QueryParseContext;
import org.elasticsearch.index.query.QueryShardContext;
import java.io.IOException;
@ -65,9 +64,7 @@ public class TestDeprecatedQueryBuilder extends AbstractQueryBuilder<TestDepreca
builder.startObject(NAME).endObject();
}
public static TestDeprecatedQueryBuilder fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
public static TestDeprecatedQueryBuilder fromXContent(XContentParser parser) throws IOException, ParsingException {
if (parser.nextToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[{}] query does not have any fields", NAME);
}

View File

@ -120,6 +120,7 @@ import java.util.stream.Stream;
import static java.util.Collections.emptyList;
import static java.util.stream.Collectors.toList;
import static org.elasticsearch.index.query.AbstractQueryBuilder.parseInnerQueryBuilder;
import static org.elasticsearch.test.EqualsHashCodeTestUtils.checkEqualsAndHashCode;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.Matchers.containsString;
@ -127,6 +128,7 @@ import static org.hamcrest.Matchers.either;
import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.instanceOf;
public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>> extends ESTestCase {
public static final String STRING_FIELD_NAME = "mapped_string";
@ -545,8 +547,7 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
}
protected static QueryBuilder parseQuery(XContentParser parser) throws IOException {
QueryParseContext context = createParseContext(parser);
QueryBuilder parseInnerQueryBuilder = context.parseInnerQueryBuilder();
QueryBuilder parseInnerQueryBuilder = parseInnerQueryBuilder(parser);
assertNull(parser.nextToken());
return parseInnerQueryBuilder;
}