Merge pull request #19791 from javanna/fix/multiple_fields_queries

Query parsers to throw exception when multiple field names are provided
This commit is contained in:
Luca Cavanna 2016-08-05 15:53:35 +02:00 committed by GitHub
commit 4c1a3b9a53
55 changed files with 1075 additions and 1423 deletions

View File

@ -102,7 +102,7 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
throw new IllegalArgumentException("field name is null or empty");
}
if (text == null) {
throw new IllegalArgumentException("text cannot be null.");
throw new IllegalArgumentException("text cannot be null");
}
this.fieldName = fieldName;
this.text = text;
@ -265,11 +265,8 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
public static Optional<CommonTermsQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] query malformed, no field");
}
String fieldName = parser.currentName();
String fieldName = null;
Object text = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String analyzer = null;
@ -280,78 +277,79 @@ public class CommonTermsQueryBuilder extends AbstractQueryBuilder<CommonTermsQue
Operator lowFreqOperator = CommonTermsQueryBuilder.DEFAULT_LOW_FREQ_OCCUR;
float cutoffFrequency = CommonTermsQueryBuilder.DEFAULT_CUTOFF_FREQ;
String queryName = null;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
String innerFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
innerFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(innerFieldName, LOW_FREQ_FIELD)) {
lowFreqMinimumShouldMatch = parser.text();
} else if (parseContext.getParseFieldMatcher().match(innerFieldName, HIGH_FREQ_FIELD)) {
highFreqMinimumShouldMatch = parser.text();
XContentParser.Token token;
String currentFieldName = null;
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 (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[common] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
String innerFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
innerFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(innerFieldName, LOW_FREQ_FIELD)) {
lowFreqMinimumShouldMatch = parser.text();
} else if (parseContext.getParseFieldMatcher().match(innerFieldName, HIGH_FREQ_FIELD)) {
highFreqMinimumShouldMatch = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] query does not support [" + innerFieldName
+ "] for [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] query does not support [" + innerFieldName
+ "] for [" + currentFieldName + "]");
"] unexpected token type [" + token
+ "] after [" + innerFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] unexpected token type [" + token
+ "] after [" + innerFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
text = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, DISABLE_COORD_FIELD)) {
disableCoord = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, HIGH_FREQ_OPERATOR_FIELD)) {
highFreqOperator = Operator.fromString(parser.text());
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, LOW_FREQ_OPERATOR_FIELD)) {
lowFreqOperator = Operator.fromString(parser.text());
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
lowFreqMinimumShouldMatch = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutoffFrequency = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] query does not support [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] query does not support [" + currentFieldName + "]");
}
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
text = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, DISABLE_COORD_FIELD)) {
disableCoord = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, HIGH_FREQ_OPERATOR_FIELD)) {
highFreqOperator = Operator.fromString(parser.text());
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, LOW_FREQ_OPERATOR_FIELD)) {
lowFreqOperator = Operator.fromString(parser.text());
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
lowFreqMinimumShouldMatch = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutoffFrequency = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + CommonTermsQueryBuilder.NAME +
"] query does not support [" + currentFieldName + "]");
}
}
}
parser.nextToken();
} else {
text = parser.objectText();
// move to the next token
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(),
"[common] query parsed in simplified form, with direct field name, but included more options than just " +
"the field name, possibly use its 'options' form, with 'query' element?");
} else {
fieldName = parser.currentName();
text = parser.objectText();
}
}
if (text == null) {
throw new ParsingException(parser.getTokenLocation(), "No text specified for text query");
}
return Optional.of(new CommonTermsQueryBuilder(fieldName, text)
.lowFreqMinimumShouldMatch(lowFreqMinimumShouldMatch)
.highFreqMinimumShouldMatch(highFreqMinimumShouldMatch)

View File

@ -152,7 +152,7 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
*/
public FuzzyQueryBuilder(String fieldName, Object value) {
if (Strings.isEmpty(fieldName)) {
throw new IllegalArgumentException("field name cannot be null or empty.");
throw new IllegalArgumentException("field name cannot be null or empty");
}
if (value == null) {
throw new IllegalArgumentException("query value cannot be null");
@ -258,63 +258,60 @@ public class FuzzyQueryBuilder extends AbstractQueryBuilder<FuzzyQueryBuilder> i
public static Optional<FuzzyQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[fuzzy] query malformed, no field");
}
String fieldName = parser.currentName();
String fieldName = null;
Object value = null;
Fuzziness fuzziness = FuzzyQueryBuilder.DEFAULT_FUZZINESS;
int prefixLength = FuzzyQueryBuilder.DEFAULT_PREFIX_LENGTH;
int maxExpansions = FuzzyQueryBuilder.DEFAULT_MAX_EXPANSIONS;
boolean transpositions = FuzzyQueryBuilder.DEFAULT_TRANSPOSITIONS;
String rewrite = null;
String queryName = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if (parseContext.getParseFieldMatcher().match(currentFieldName, TERM_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, VALUE_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser);
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansions = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, TRANSPOSITIONS_FIELD)) {
transpositions = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
String currentFieldName = null;
XContentParser.Token token;
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 (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[fuzzy] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
throw new ParsingException(parser.getTokenLocation(), "[fuzzy] query does not support [" + currentFieldName + "]");
if (parseContext.getParseFieldMatcher().match(currentFieldName, TERM_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, VALUE_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser);
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansions = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, TRANSPOSITIONS_FIELD)) {
transpositions = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[fuzzy] query does not support [" + currentFieldName + "]");
}
}
}
} else {
fieldName = parser.currentName();
value = parser.objectBytes();
}
parser.nextToken();
} else {
value = parser.objectBytes();
// move to the next token
parser.nextToken();
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "no value specified for fuzzy query");
}
return Optional.of(new FuzzyQueryBuilder(fieldName, value)
.fuzziness(fuzziness)

View File

@ -359,9 +359,12 @@ public class GeoDistanceQueryBuilder extends AbstractQueryBuilder<GeoDistanceQue
fieldName = currentFieldName;
GeoUtils.parseGeoPoint(parser, point);
} else if (token == XContentParser.Token.START_OBJECT) {
if (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[geo_distance] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
// the json in the format of -> field : { lat : 30, lon : 12 }
String currentName = parser.currentName();
assert currentFieldName != null;
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {

View File

@ -192,62 +192,55 @@ public class MatchPhrasePrefixQueryBuilder extends AbstractQueryBuilder<MatchPhr
public static Optional<MatchPhrasePrefixQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] query malformed, no field");
}
String fieldName = parser.currentName();
String fieldName = null;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String analyzer = null;
int slop = MatchQuery.DEFAULT_PHRASE_SLOP;
int maxExpansion = FuzzyQuery.defaultMaxExpansions;
String queryName = null;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.QUERY_FIELD)) {
value = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchPhraseQueryBuilder.SLOP_FIELD)) {
slop = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansion = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
XContentParser.Token token;
String currentFieldName = null;
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 (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[match_phrase_prefix] query doesn't support multiple " +
"fields, found [" + fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.QUERY_FIELD)) {
value = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchPhraseQueryBuilder.SLOP_FIELD)) {
slop = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansion = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] query does not support [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] query does not support [" + currentFieldName + "]");
"[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
}
} else {
fieldName = parser.currentName();
value = parser.objectText();
}
parser.nextToken();
} else {
value = parser.objectText();
// move to the next token
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME
+ "] query parsed in simplified form, with direct field name, "
+ "but included more options than just the field name, possibly use its 'options' form, with 'query' element?");
}
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No text specified for text query");
}
MatchPhrasePrefixQueryBuilder matchQuery = new MatchPhrasePrefixQueryBuilder(fieldName, value);

View File

@ -22,6 +22,7 @@ package org.elasticsearch.index.query;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParseField;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;
import org.elasticsearch.common.xcontent.XContentBuilder;
@ -49,7 +50,7 @@ public class MatchPhraseQueryBuilder extends AbstractQueryBuilder<MatchPhraseQue
private int slop = MatchQuery.DEFAULT_PHRASE_SLOP;
public MatchPhraseQueryBuilder(String fieldName, Object value) {
if (fieldName == null) {
if (Strings.isEmpty(fieldName)) {
throw new IllegalArgumentException("[" + NAME + "] requires fieldName");
}
if (value == null) {
@ -163,59 +164,52 @@ public class MatchPhraseQueryBuilder extends AbstractQueryBuilder<MatchPhraseQue
public static Optional<MatchPhraseQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] query malformed, no field");
}
String fieldName = parser.currentName();
String fieldName = null;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String analyzer = null;
int slop = MatchQuery.DEFAULT_PHRASE_SLOP;
String queryName = null;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.QUERY_FIELD)) {
value = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, SLOP_FIELD)) {
slop = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
String currentFieldName = null;
XContentParser.Token token;
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 (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[match_phrase] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.QUERY_FIELD)) {
value = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MatchQueryBuilder.ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, SLOP_FIELD)) {
slop = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] query does not support [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] query does not support [" + currentFieldName + "]");
"[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
}
} else {
fieldName = parser.currentName();
value = parser.objectText();
}
parser.nextToken();
} else {
value = parser.objectText();
// move to the next token
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME
+ "] query parsed in simplified form, with direct field name, "
+ "but included more options than just the field name, possibly use its 'options' form, with 'query' element?");
}
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No text specified for text query");
}
MatchPhraseQueryBuilder matchQuery = new MatchPhraseQueryBuilder(fieldName, value);

View File

@ -510,13 +510,7 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
public static Optional<MatchQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[" + MatchQueryBuilder.NAME + "] query malformed, no field");
}
String fieldName = parser.currentName();
String fieldName = null;
MatchQuery.Type type = MatchQuery.Type.BOOLEAN;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
@ -533,80 +527,84 @@ public class MatchQueryBuilder extends AbstractQueryBuilder<MatchQueryBuilder> {
Float cutOffFrequency = null;
ZeroTermsQuery zeroTermsQuery = MatchQuery.DEFAULT_ZERO_TERMS_QUERY;
String queryName = null;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
value = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
String tStr = parser.text();
if ("boolean".equals(tStr)) {
type = MatchQuery.Type.BOOLEAN;
} else if ("phrase".equals(tStr)) {
type = MatchQuery.Type.PHRASE;
} else if ("phrase_prefix".equals(tStr) || ("phrasePrefix".equals(tStr))) {
type = MatchQuery.Type.PHRASE_PREFIX;
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] query does not support type " + tStr);
}
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, SLOP_FIELD)) {
slop = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser);
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansion = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, OPERATOR_FIELD)) {
operator = Operator.fromString(parser.text());
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
minimumShouldMatch = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, FUZZY_REWRITE_FIELD)) {
fuzzyRewrite = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, FUZZY_TRANSPOSITIONS_FIELD)) {
fuzzyTranspositions = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, LENIENT_FIELD)) {
lenient = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutOffFrequency = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, ZERO_TERMS_QUERY_FIELD)) {
String zeroTermsDocs = parser.text();
if ("none".equalsIgnoreCase(zeroTermsDocs)) {
zeroTermsQuery = MatchQuery.ZeroTermsQuery.NONE;
} else if ("all".equalsIgnoreCase(zeroTermsDocs)) {
zeroTermsQuery = MatchQuery.ZeroTermsQuery.ALL;
String currentFieldName = null;
XContentParser.Token token;
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 (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[match] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token.isValue()) {
if (parseContext.getParseFieldMatcher().match(currentFieldName, QUERY_FIELD)) {
value = parser.objectText();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, TYPE_FIELD)) {
String tStr = parser.text();
if ("boolean".equals(tStr)) {
type = MatchQuery.Type.BOOLEAN;
} else if ("phrase".equals(tStr)) {
type = MatchQuery.Type.PHRASE;
} else if ("phrase_prefix".equals(tStr) || ("phrasePrefix".equals(tStr))) {
type = MatchQuery.Type.PHRASE_PREFIX;
} else {
throw new ParsingException(parser.getTokenLocation(), "[" + NAME + "] query does not support type " + tStr);
}
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, ANALYZER_FIELD)) {
analyzer = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, SLOP_FIELD)) {
slop = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, Fuzziness.FIELD)) {
fuzziness = Fuzziness.parse(parser);
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, PREFIX_LENGTH_FIELD)) {
prefixLength = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MAX_EXPANSIONS_FIELD)) {
maxExpansion = parser.intValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, OPERATOR_FIELD)) {
operator = Operator.fromString(parser.text());
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, MINIMUM_SHOULD_MATCH_FIELD)) {
minimumShouldMatch = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, FUZZY_REWRITE_FIELD)) {
fuzzyRewrite = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, FUZZY_TRANSPOSITIONS_FIELD)) {
fuzzyTranspositions = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, LENIENT_FIELD)) {
lenient = parser.booleanValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, CUTOFF_FREQUENCY_FIELD)) {
cutOffFrequency = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, ZERO_TERMS_QUERY_FIELD)) {
String zeroTermsDocs = parser.text();
if ("none".equalsIgnoreCase(zeroTermsDocs)) {
zeroTermsQuery = MatchQuery.ZeroTermsQuery.NONE;
} else if ("all".equalsIgnoreCase(zeroTermsDocs)) {
zeroTermsQuery = MatchQuery.ZeroTermsQuery.ALL;
} else {
throw new ParsingException(parser.getTokenLocation(),
"Unsupported zero_terms_docs value [" + zeroTermsDocs + "]");
}
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"Unsupported zero_terms_docs value [" + zeroTermsDocs + "]");
"[" + NAME + "] query does not support [" + currentFieldName + "]");
}
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] query does not support [" + currentFieldName + "]");
"[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
}
} else {
throw new ParsingException(parser.getTokenLocation(),
"[" + NAME + "] unknown token [" + token + "] after [" + currentFieldName + "]");
}
}
parser.nextToken();
} else {
value = parser.objectText();
// move to the next token
token = parser.nextToken();
if (token != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "[match] query parsed in simplified form, with direct field name, "
+ "but included more options than just the field name, possibly use its 'options' form, with 'query' element?");
} else {
fieldName = parser.currentName();
value = parser.objectText();
}
}

View File

@ -64,7 +64,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
throw new IllegalArgumentException("field name is null or empty");
}
if (value == null) {
throw new IllegalArgumentException("value cannot be null.");
throw new IllegalArgumentException("value cannot be null");
}
this.fieldName = fieldName;
this.value = value;
@ -120,7 +120,7 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
public static Optional<PrefixQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
String fieldName = parser.currentName();
String fieldName = null;
String value = null;
String rewrite = null;
@ -134,6 +134,10 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
if (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[prefix] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
@ -149,19 +153,16 @@ public class PrefixQueryBuilder extends AbstractQueryBuilder<PrefixQueryBuilder>
rewrite = parser.textOrNull();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[regexp] query does not support [" + currentFieldName + "]");
"[prefix] query does not support [" + currentFieldName + "]");
}
}
}
} else {
fieldName = currentFieldName;
value = parser.textOrNull();
fieldName = currentFieldName;
value = parser.textOrNull();
}
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No value specified for prefix query");
}
return Optional.of(new PrefixQueryBuilder(fieldName, value)
.rewrite(rewrite)
.boost(boost)

View File

@ -115,10 +115,11 @@ public class QueryParseContext implements ParseFieldMatcherSupplier {
@SuppressWarnings("unchecked")
Optional<QueryBuilder> result = (Optional<QueryBuilder>) indicesQueriesRegistry.lookup(queryName, parseFieldMatcher,
parser.getTokenLocation()).fromXContent(this);
if (parser.currentToken() == XContentParser.Token.END_OBJECT) {
// if we are at END_OBJECT, move to the next one...
parser.nextToken();
if (parser.currentToken() != XContentParser.Token.END_OBJECT) {
throw new ParsingException(parser.getTokenLocation(),
"[" + queryName + "] malformed query, expected [END_OBJECT] but found [" + parser.currentToken() + "]");
}
parser.nextToken();
return result;
}

View File

@ -318,6 +318,10 @@ public class RangeQueryBuilder extends AbstractQueryBuilder<RangeQueryBuilder> i
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
if (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[range] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {

View File

@ -77,7 +77,7 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
throw new IllegalArgumentException("field name is null or empty");
}
if (value == null) {
throw new IllegalArgumentException("value cannot be null.");
throw new IllegalArgumentException("value cannot be null");
}
this.fieldName = fieldName;
this.value = value;
@ -180,10 +180,8 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
public static Optional<RegexpQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
String fieldName = parser.currentName();
String fieldName = null;
String rewrite = null;
String value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
int flagsValue = RegexpQueryBuilder.DEFAULT_FLAGS_VALUE;
@ -197,6 +195,10 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
} else if (parseContext.isDeprecatedSetting(currentFieldName)) {
// skip
} else if (token == XContentParser.Token.START_OBJECT) {
if (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[regexp] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
@ -233,9 +235,6 @@ public class RegexpQueryBuilder extends AbstractQueryBuilder<RegexpQueryBuilder>
}
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No value specified for regexp query");
}
return Optional.of(new RegexpQueryBuilder(fieldName, value)
.flags(flagsValue)
.maxDeterminizedStates(maxDeterminizedStates)

View File

@ -186,7 +186,7 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
/** Add a field to run the query against. */
public SimpleQueryStringBuilder field(String field) {
if (Strings.isEmpty(field)) {
throw new IllegalArgumentException("supplied field is null or empty.");
throw new IllegalArgumentException("supplied field is null or empty");
}
this.fieldsAndWeights.put(field, AbstractQueryBuilder.DEFAULT_BOOST);
return this;
@ -195,7 +195,7 @@ public class SimpleQueryStringBuilder extends AbstractQueryBuilder<SimpleQuerySt
/** Add a field to run the query against with a specific boost. */
public SimpleQueryStringBuilder field(String field, float boost) {
if (Strings.isEmpty(field)) {
throw new IllegalArgumentException("supplied field is null or empty.");
throw new IllegalArgumentException("supplied field is null or empty");
}
this.fieldsAndWeights.put(field, boost);
return this;

View File

@ -94,49 +94,43 @@ public class SpanTermQueryBuilder extends BaseTermQueryBuilder<SpanTermQueryBuil
public static Optional<SpanTermQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException, ParsingException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.currentToken();
if (token == XContentParser.Token.START_OBJECT) {
token = parser.nextToken();
}
assert token == XContentParser.Token.FIELD_NAME;
String fieldName = parser.currentName();
String fieldName = null;
Object value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if (parseContext.getParseFieldMatcher().match(currentFieldName, TERM_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, BaseTermQueryBuilder.VALUE_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
String currentFieldName = null;
XContentParser.Token token;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else if (token == XContentParser.Token.START_OBJECT) {
if (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[span_term] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[span_term] query does not support [" + currentFieldName + "]");
if (parseContext.getParseFieldMatcher().match(currentFieldName, TERM_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, BaseTermQueryBuilder.VALUE_FIELD)) {
value = parser.objectBytes();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[span_term] query does not support [" + currentFieldName + "]");
}
}
}
} else {
fieldName = parser.currentName();
value = parser.objectBytes();
}
parser.nextToken();
} else {
value = parser.objectBytes();
// move to the next token
parser.nextToken();
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No value specified for term query");
}
SpanTermQueryBuilder result = new SpanTermQueryBuilder(fieldName, value);

View File

@ -75,7 +75,7 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
throw new IllegalArgumentException("field name is null or empty");
}
if (value == null) {
throw new IllegalArgumentException("value cannot be null.");
throw new IllegalArgumentException("value cannot be null");
}
this.fieldName = fieldName;
this.value = value;
@ -135,49 +135,50 @@ public class WildcardQueryBuilder extends AbstractQueryBuilder<WildcardQueryBuil
public static Optional<WildcardQueryBuilder> fromXContent(QueryParseContext parseContext) throws IOException {
XContentParser parser = parseContext.parser();
XContentParser.Token token = parser.nextToken();
if (token != XContentParser.Token.FIELD_NAME) {
throw new ParsingException(parser.getTokenLocation(), "[wildcard] query malformed, no field");
}
String fieldName = parser.currentName();
String fieldName = null;
String rewrite = null;
String value = null;
float boost = AbstractQueryBuilder.DEFAULT_BOOST;
String queryName = null;
token = parser.nextToken();
if (token == XContentParser.Token.START_OBJECT) {
String currentFieldName = null;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
if (parseContext.getParseFieldMatcher().match(currentFieldName, WILDCARD_FIELD)) {
value = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, VALUE_FIELD)) {
value = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
String currentFieldName = null;
XContentParser.Token token;
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 (fieldName != null) {
throw new ParsingException(parser.getTokenLocation(), "[wildcard] query doesn't support multiple fields, found ["
+ fieldName + "] and [" + currentFieldName + "]");
}
fieldName = currentFieldName;
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentFieldName = parser.currentName();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[wildcard] query does not support [" + currentFieldName + "]");
if (parseContext.getParseFieldMatcher().match(currentFieldName, WILDCARD_FIELD)) {
value = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, VALUE_FIELD)) {
value = parser.text();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.BOOST_FIELD)) {
boost = parser.floatValue();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, REWRITE_FIELD)) {
rewrite = parser.textOrNull();
} else if (parseContext.getParseFieldMatcher().match(currentFieldName, AbstractQueryBuilder.NAME_FIELD)) {
queryName = parser.text();
} else {
throw new ParsingException(parser.getTokenLocation(),
"[wildcard] query does not support [" + currentFieldName + "]");
}
}
}
} else {
fieldName = parser.currentName();
value = parser.text();
}
parser.nextToken();
} else {
value = parser.text();
parser.nextToken();
}
if (value == null) {
throw new ParsingException(parser.getTokenLocation(), "No value specified for wildcard query");
}
return Optional.of(new WildcardQueryBuilder(fieldName, value)
.rewrite(rewrite)
.boost(boost)

View File

@ -30,23 +30,11 @@ public abstract class AbstractTermQueryTestCase<QB extends BaseTermQueryBuilder<
protected abstract QB createQueryBuilder(String fieldName, Object value);
public void testIllegalArguments() throws QueryShardException {
try {
if (randomBoolean()) {
createQueryBuilder(null, randomAsciiOfLengthBetween(1, 30));
} else {
createQueryBuilder("", randomAsciiOfLengthBetween(1, 30));
}
fail("fieldname cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
try {
createQueryBuilder("field", null);
fail("value cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
String term = randomAsciiOfLengthBetween(1, 30);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> createQueryBuilder(null, term));
assertEquals("field name is null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> createQueryBuilder("", term));
assertEquals("field name is null or empty", e.getMessage());
}
@Override

View File

@ -163,30 +163,10 @@ public class BoolQueryBuilderTests extends AbstractQueryTestCase<BoolQueryBuilde
public void testIllegalArguments() {
BoolQueryBuilder booleanQuery = new BoolQueryBuilder();
try {
booleanQuery.must(null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
}
try {
booleanQuery.mustNot(null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
}
try {
booleanQuery.filter(null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
}
try {
booleanQuery.should(null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
}
expectThrows(IllegalArgumentException.class, () -> booleanQuery.must(null));
expectThrows(IllegalArgumentException.class, () -> booleanQuery.mustNot(null));
expectThrows(IllegalArgumentException.class, () -> booleanQuery.filter(null));
expectThrows(IllegalArgumentException.class, () -> booleanQuery.should(null));
}
// https://github.com/elastic/elasticsearch/issues/7240

View File

@ -54,26 +54,10 @@ public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQue
}
public void testIllegalArguments() {
try {
new BoostingQueryBuilder(null, new MatchAllQueryBuilder());
fail("must not be null");
} catch (IllegalArgumentException e) {
//
}
try {
new BoostingQueryBuilder(new MatchAllQueryBuilder(), null);
fail("must not be null");
} catch (IllegalArgumentException e) {
//
}
try {
new BoostingQueryBuilder(new MatchAllQueryBuilder(), new MatchAllQueryBuilder()).negativeBoost(-1.0f);
fail("must not be negative");
} catch (IllegalArgumentException e) {
//
}
expectThrows(IllegalArgumentException.class, () -> new BoostingQueryBuilder(null, new MatchAllQueryBuilder()));
expectThrows(IllegalArgumentException.class, () -> new BoostingQueryBuilder(new MatchAllQueryBuilder(), null));
expectThrows(IllegalArgumentException.class,
() -> new BoostingQueryBuilder(new MatchAllQueryBuilder(), new MatchAllQueryBuilder()).negativeBoost(-1.0f));
}
public void testFromJson() throws IOException {
@ -103,7 +87,6 @@ public class BoostingQueryBuilderTests extends AbstractQueryTestCase<BoostingQue
BoostingQueryBuilder queryBuilder = (BoostingQueryBuilder) parseQuery(query);
checkGeneratedJson(query, queryBuilder);
assertEquals(query, 42, queryBuilder.boost(), 0.00001);
assertEquals(query, 23, queryBuilder.negativeBoost(), 0.00001);
assertEquals(query, 8, queryBuilder.negativeQuery().boost(), 0.00001);

View File

@ -21,9 +21,12 @@ package org.elasticsearch.index.query;
import org.apache.lucene.queries.ExtendedCommonTermsQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.index.query.QueryBuilders.commonTermsQuery;
import static org.elasticsearch.test.StreamsUtils.copyToStringFromClasspath;
@ -81,6 +84,20 @@ public class CommonTermsQueryBuilderTests extends AbstractQueryTestCase<CommonTe
return query;
}
@Override
protected Map<String, CommonTermsQueryBuilder> getAlternateVersions() {
Map<String, CommonTermsQueryBuilder> alternateVersions = new HashMap<>();
CommonTermsQueryBuilder commonTermsQuery = new CommonTermsQueryBuilder(randomAsciiOfLengthBetween(1, 10),
randomAsciiOfLengthBetween(1, 10));
String contentString = "{\n" +
" \"common\" : {\n" +
" \"" + commonTermsQuery.fieldName() + "\" : \"" + commonTermsQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, commonTermsQuery);
return alternateVersions;
}
@Override
protected void doAssertLuceneQuery(CommonTermsQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, instanceOf(ExtendedCommonTermsQuery.class));
@ -90,23 +107,12 @@ public class CommonTermsQueryBuilderTests extends AbstractQueryTestCase<CommonTe
}
public void testIllegalArguments() {
try {
if (randomBoolean()) {
new CommonTermsQueryBuilder(null, "text");
} else {
new CommonTermsQueryBuilder("", "text");
}
fail("must be non null");
} catch (IllegalArgumentException e) {
// okay
}
try {
new CommonTermsQueryBuilder("fieldName", null);
fail("must be non null");
} catch (IllegalArgumentException e) {
// okay
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new CommonTermsQueryBuilder(null, "text"));
assertEquals("field name is null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new CommonTermsQueryBuilder("", "text"));
assertEquals("field name is null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new CommonTermsQueryBuilder("fieldName", null));
assertEquals("text cannot be null", e.getMessage());
}
public void testFromJson() throws IOException {
@ -173,4 +179,20 @@ public class CommonTermsQueryBuilderTests extends AbstractQueryTestCase<CommonTe
ExtendedCommonTermsQuery ectQuery = (ExtendedCommonTermsQuery) parsedQuery;
assertThat(ectQuery.isCoordDisabled(), equalTo(disableCoord));
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"common\" : {\n" +
" \"message1\" : {\n" +
" \"query\" : \"nelly the elephant not as a cartoon\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"query\" : \"nelly the elephant not as a cartoon\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[common] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
}
}

View File

@ -61,12 +61,8 @@ public class ConstantScoreQueryBuilderTests extends AbstractQueryTestCase<Consta
*/
public void testFilterElement() throws IOException {
String queryString = "{ \"" + ConstantScoreQueryBuilder.NAME + "\" : {} }";
try {
parseQuery(queryString);
fail("Expected ParsingException");
} catch (ParsingException e) {
assertThat(e.getMessage(), containsString("requires a 'filter' element"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryString));
assertThat(e.getMessage(), containsString("requires a 'filter' element"));
}
/**
@ -77,12 +73,8 @@ public class ConstantScoreQueryBuilderTests extends AbstractQueryTestCase<Consta
"\"filter\" : { \"term\": { \"foo\": \"a\" } },\n" +
"\"filter\" : { \"term\": { \"foo\": \"x\" } },\n" +
"} }";
try {
parseQuery(queryString);
fail("Expected ParsingException");
} catch (ParsingException e) {
assertThat(e.getMessage(), containsString("accepts only one 'filter' element"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryString));
assertThat(e.getMessage(), containsString("accepts only one 'filter' element"));
}
/**
@ -93,12 +85,8 @@ public class ConstantScoreQueryBuilderTests extends AbstractQueryTestCase<Consta
"\"filter\" : [ { \"term\": { \"foo\": \"a\" } },\n" +
"{ \"term\": { \"foo\": \"x\" } } ]\n" +
"} }";
try {
parseQuery(queryString);
fail("Expected ParsingException");
} catch (ParsingException e) {
assertThat(e.getMessage(), containsString("unexpected token [START_ARRAY]"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryString));
assertThat(e.getMessage(), containsString("unexpected token [START_ARRAY]"));
}
public void testIllegalArguments() {

View File

@ -102,12 +102,7 @@ public class DisMaxQueryBuilderTests extends AbstractQueryTestCase<DisMaxQueryBu
public void testIllegalArguments() {
DisMaxQueryBuilder disMaxQuery = new DisMaxQueryBuilder();
try {
disMaxQuery.add(null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> disMaxQuery.add(null));
}
public void testToQueryInnerPrefixQuery() throws Exception {

View File

@ -56,24 +56,10 @@ public class FieldMaskingSpanQueryBuilderTests extends AbstractQueryTestCase<Fie
}
public void testIllegalArguments() {
try {
new FieldMaskingSpanQueryBuilder(null, "maskedField");
fail("must be non null");
} catch (IllegalArgumentException e) {
// okay
}
try {
SpanQueryBuilder span = new SpanTermQueryBuilder("name", "value");
if (randomBoolean()) {
new FieldMaskingSpanQueryBuilder(span, null);
} else {
new FieldMaskingSpanQueryBuilder(span, "");
}
fail("must be non null");
} catch (IllegalArgumentException e) {
// okay
}
expectThrows(IllegalArgumentException.class, () -> new FieldMaskingSpanQueryBuilder(null, "maskedField"));
SpanQueryBuilder span = new SpanTermQueryBuilder("name", "value");
expectThrows(IllegalArgumentException.class, () -> new FieldMaskingSpanQueryBuilder(span, null));
expectThrows(IllegalArgumentException.class, () -> new FieldMaskingSpanQueryBuilder(span, ""));
}
public void testFromJson() throws IOException {
@ -93,10 +79,8 @@ public class FieldMaskingSpanQueryBuilderTests extends AbstractQueryTestCase<Fie
" \"_name\" : \"KPI\"\n" +
" }\n" +
"}";
FieldMaskingSpanQueryBuilder parsed = (FieldMaskingSpanQueryBuilder) parseQuery(json);
checkGeneratedJson(json, parsed);
assertEquals(json, 42.0, parsed.boost(), 0.00001);
assertEquals(json, 0.23, parsed.innerQuery().boost(), 0.00001);
}

View File

@ -23,12 +23,15 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.BoostQuery;
import org.apache.lucene.search.FuzzyQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.test.AbstractQueryTestCase;
import org.hamcrest.Matchers;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
@ -55,47 +58,42 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
return query;
}
@Override
protected Map<String, FuzzyQueryBuilder> getAlternateVersions() {
Map<String, FuzzyQueryBuilder> alternateVersions = new HashMap<>();
FuzzyQueryBuilder fuzzyQuery = new FuzzyQueryBuilder(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
String contentString = "{\n" +
" \"fuzzy\" : {\n" +
" \"" + fuzzyQuery.fieldName() + "\" : \"" + fuzzyQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, fuzzyQuery);
return alternateVersions;
}
@Override
protected void doAssertLuceneQuery(FuzzyQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, instanceOf(FuzzyQuery.class));
}
public void testIllegalArguments() {
try {
new FuzzyQueryBuilder(null, "text");
fail("must not be null");
} catch (IllegalArgumentException e) {
// expected
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new FuzzyQueryBuilder(null, "text"));
assertEquals("field name cannot be null or empty", e.getMessage());
try {
new FuzzyQueryBuilder("", "text");
fail("must not be empty");
} catch (IllegalArgumentException e) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new FuzzyQueryBuilder("", "text"));
assertEquals("field name cannot be null or empty", e.getMessage());
try {
new FuzzyQueryBuilder("field", null);
fail("must not be null");
} catch (IllegalArgumentException e) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new FuzzyQueryBuilder("field", null));
assertEquals("query value cannot be null", e.getMessage());
}
public void testUnsupportedFuzzinessForStringType() throws IOException {
QueryShardContext context = createShardContext();
context.setAllowUnmappedFields(true);
FuzzyQueryBuilder fuzzyQueryBuilder = new FuzzyQueryBuilder(STRING_FIELD_NAME, "text");
fuzzyQueryBuilder.fuzziness(Fuzziness.build(randomFrom("a string which is not auto", "3h", "200s")));
try {
fuzzyQueryBuilder.toQuery(context);
fail("should have failed with NumberFormatException");
} catch (NumberFormatException e) {
assertThat(e.getMessage(), Matchers.containsString("For input string"));
}
NumberFormatException e = expectThrows(NumberFormatException.class, () -> fuzzyQueryBuilder.toQuery(context));
assertThat(e.getMessage(), containsString("For input string"));
}
public void testToQueryWithStringField() throws IOException {
@ -119,7 +117,6 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
assertThat(fuzzyQuery.getTerm(), equalTo(new Term(STRING_FIELD_NAME, "sh")));
assertThat(fuzzyQuery.getMaxEdits(), equalTo(Fuzziness.AUTO.asDistance("sh")));
assertThat(fuzzyQuery.getPrefixLength(), equalTo(1));
}
public void testToQueryWithNumericField() throws IOException {
@ -157,4 +154,20 @@ public class FuzzyQueryBuilderTests extends AbstractQueryTestCase<FuzzyQueryBuil
assertEquals(json, 42.0, parsed.boost(), 0.00001);
assertEquals(json, 2, parsed.fuzziness().asFloat(), 0f);
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"fuzzy\" : {\n" +
" \"message1\" : {\n" +
" \"value\" : \"this is a test\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"value\" : \"this is a test\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[fuzzy] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
}
}

View File

@ -44,7 +44,6 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class GeoBoundingBoxQueryBuilderTests extends AbstractQueryTestCase<GeoBoundingBoxQueryBuilder> {
/** Randomly generate either NaN or one of the two infinity values. */
@ -104,22 +103,14 @@ public class GeoBoundingBoxQueryBuilderTests extends AbstractQueryTestCase<GeoBo
public void testValidationNullType() {
GeoBoundingBoxQueryBuilder qb = new GeoBoundingBoxQueryBuilder("teststring");
try {
qb.type((GeoExecType) null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("Type is not allowed to be null."));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.type((GeoExecType) null));
assertEquals("Type is not allowed to be null.", e.getMessage());
}
public void testValidationNullTypeString() {
GeoBoundingBoxQueryBuilder qb = new GeoBoundingBoxQueryBuilder("teststring");
try {
qb.type((String) null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("cannot parse type from null string"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.type((String) null));
assertEquals("cannot parse type from null string", e.getMessage());
}
@Override
@ -130,27 +121,17 @@ public class GeoBoundingBoxQueryBuilderTests extends AbstractQueryTestCase<GeoBo
public void testExceptionOnMissingTypes() throws IOException {
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length == 0);
try {
super.testToQuery();
fail("Expected IllegalArgumentException");
} catch (QueryShardException e) {
assertThat(e.getMessage(), is("failed to find geo_point field [mapped_geo_point]"));
}
QueryShardException e = expectThrows(QueryShardException.class, () -> super.testToQuery());
assertEquals("failed to find geo_point field [mapped_geo_point]", e.getMessage());
}
public void testBrokenCoordinateCannotBeSet() {
PointTester[] testers = { new TopTester(), new LeftTester(), new BottomTester(), new RightTester() };
GeoBoundingBoxQueryBuilder builder = createTestQueryBuilder();
builder.setValidationMethod(GeoValidationMethod.STRICT);
for (PointTester tester : testers) {
try {
tester.invalidateCoordinate(builder, true);
fail("expected exception for broken " + tester.getClass().getName() + " coordinate");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> tester.invalidateCoordinate(builder, true));
}
}
@ -215,12 +196,9 @@ public class GeoBoundingBoxQueryBuilderTests extends AbstractQueryTestCase<GeoBo
assumeTrue("top should not be equal to bottom for flip check", top != bottom);
logger.info("top: {} bottom: {}", top, bottom);
try {
builder.setValidationMethod(GeoValidationMethod.STRICT).setCorners(bottom, left, top, right);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("top is below bottom corner:"));
}
builder.setValidationMethod(GeoValidationMethod.STRICT);
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.setCorners(bottom, left, top, right));
assertThat(e.getMessage(), containsString("top is below bottom corner:"));
}
public void testTopBottomCanBeFlippedOnIgnoreMalformed() {
@ -482,7 +460,7 @@ public class GeoBoundingBoxQueryBuilderTests extends AbstractQueryTestCase<GeoBo
assertEquals(json, 40.01, parsed.bottomRight().getLat(), 0.0001);
assertEquals(json, 1.0, parsed.boost(), 0.0001);
assertEquals(json, GeoExecType.MEMORY, parsed.type());
json =
String deprecatedJson =
"{\n" +
" \"geo_bbox\" : {\n" +
" \"pin.location\" : {\n" +
@ -498,12 +476,8 @@ public class GeoBoundingBoxQueryBuilderTests extends AbstractQueryTestCase<GeoBo
QueryBuilder parsedGeoBboxShortcut = parseQuery(json, ParseFieldMatcher.EMPTY);
assertThat(parsedGeoBboxShortcut, equalTo(parsed));
try {
parseQuery(json);
fail("parse query should have failed in strict mode");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Deprecated field [geo_bbox] used, expected [geo_bounding_box] instead"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(deprecatedJson));
assertEquals("Deprecated field [geo_bbox] used, expected [geo_bounding_box] instead", e.getMessage());
}
public void testFromJsonCoerceFails() throws IOException {

View File

@ -23,6 +23,7 @@ import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.spatial.geopoint.search.GeoPointDistanceQuery;
import org.elasticsearch.Version;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.geo.GeoDistance;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.geo.GeoUtils;
@ -85,82 +86,41 @@ public class GeoDistanceQueryBuilderTests extends AbstractQueryTestCase<GeoDista
}
public void testIllegalValues() {
try {
if (randomBoolean()) {
new GeoDistanceQueryBuilder("");
} else {
new GeoDistanceQueryBuilder((String) null);
}
fail("must not be null or empty");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("fieldName must not be null or empty"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new GeoDistanceQueryBuilder(""));
assertEquals("fieldName must not be null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new GeoDistanceQueryBuilder((String) null));
assertEquals("fieldName must not be null or empty", e.getMessage());
GeoDistanceQueryBuilder query = new GeoDistanceQueryBuilder("fieldName");
try {
if (randomBoolean()) {
query.distance("");
} else {
query.distance(null);
}
fail("must not be null or empty");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("distance must not be null or empty"));
}
e = expectThrows(IllegalArgumentException.class, () -> query.distance(""));
assertEquals("distance must not be null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> query.distance(null));
assertEquals("distance must not be null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> query.distance("", DistanceUnit.DEFAULT));
assertEquals("distance must not be null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> query.distance(null, DistanceUnit.DEFAULT));
assertEquals("distance must not be null or empty", e.getMessage());
try {
if (randomBoolean()) {
query.distance("", DistanceUnit.DEFAULT);
} else {
query.distance(null, DistanceUnit.DEFAULT);
}
fail("distance must not be null or empty");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("distance must not be null or empty"));
}
e = expectThrows(IllegalArgumentException.class, () -> query.distance("1", null));
assertEquals("distance unit must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> query.distance(1, null));
assertEquals("distance unit must not be null", e.getMessage());
try {
if (randomBoolean()) {
query.distance("1", null);
} else {
query.distance(1, null);
}
fail("distance must not be null");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("distance unit must not be null"));
}
e = expectThrows(IllegalArgumentException.class, () -> query.distance(
randomIntBetween(Integer.MIN_VALUE, 0), DistanceUnit.DEFAULT));
assertEquals("distance must be greater than zero", e.getMessage());
try {
query.distance(randomIntBetween(Integer.MIN_VALUE, 0), DistanceUnit.DEFAULT);
fail("distance must be greater than zero");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("distance must be greater than zero"));
}
e = expectThrows(IllegalArgumentException.class, () -> query.geohash(null));
assertEquals("geohash must not be null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> query.geohash(""));
assertEquals("geohash must not be null or empty", e.getMessage());
try {
if (randomBoolean()) {
query.geohash(null);
} else {
query.geohash("");
}
fail("geohash must not be null");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("geohash must not be null or empty"));
}
e = expectThrows(IllegalArgumentException.class, () -> query.geoDistance(null));
assertEquals("geoDistance must not be null", e.getMessage());
try {
query.geoDistance(null);
fail("geodistance must not be null");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("geoDistance must not be null"));
}
try {
query.optimizeBbox(null);
fail("optimizeBbox must not be null");
} catch (IllegalArgumentException ex) {
assertThat(ex.getMessage(), equalTo("optimizeBbox must not be null"));
}
e = expectThrows(IllegalArgumentException.class, () -> query.optimizeBbox(null));
assertEquals("optimizeBbox must not be null", e.getMessage());
}
/**
@ -474,4 +434,19 @@ public class GeoDistanceQueryBuilderTests extends AbstractQueryTestCase<GeoDista
QueryShardException e = expectThrows(QueryShardException.class, () -> failingQueryBuilder.toQuery(shardContext));
assertThat(e.getMessage(), containsString("failed to find geo_point field [unmapped]"));
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"geo_distance\" : {\n" +
" \"point1\" : {\n" +
" \"lat\" : 30, \"lon\" : 12\n" +
" },\n" +
" \"point2\" : {\n" +
" \"lat\" : 30, \"lon\" : 12\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[geo_distance] query doesn't support multiple fields, found [point1] and [point2]", e.getMessage());
}
}

View File

@ -41,7 +41,6 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class GeoDistanceRangeQueryTests extends AbstractQueryTestCase<GeoDistanceRangeQueryBuilder> {
@ -213,96 +212,57 @@ public class GeoDistanceRangeQueryTests extends AbstractQueryTestCase<GeoDistanc
}
public void testNullFieldName() {
try {
if (randomBoolean()) {
new GeoDistanceRangeQueryBuilder(null, new GeoPoint());
} else {
new GeoDistanceRangeQueryBuilder("", new GeoPoint());
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("fieldName must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoDistanceRangeQueryBuilder(null, new GeoPoint()));
assertEquals("fieldName must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class,
() -> new GeoDistanceRangeQueryBuilder("", new GeoPoint()));
assertEquals("fieldName must not be null", e.getMessage());
}
public void testNoPoint() {
try {
if (randomBoolean()) {
new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, (GeoPoint) null);
} else {
new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, (String) null);
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("point must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, (GeoPoint) null));
assertEquals("point must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class,
() -> new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, (String) null));
assertEquals("point must not be null", e.getMessage());
}
public void testInvalidFrom() {
GeoDistanceRangeQueryBuilder builder = new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, new GeoPoint());
try {
if (randomBoolean()) {
builder.from((String) null);
} else {
builder.from((Number) null);
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("[from] must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.from((String) null));
assertEquals("[from] must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> builder.from((Number) null));
assertEquals("[from] must not be null", e.getMessage());
}
public void testInvalidTo() {
GeoDistanceRangeQueryBuilder builder = new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, new GeoPoint());
try {
if (randomBoolean()) {
builder.to((String) null);
} else {
builder.to((Number) null);
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("[to] must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.to((String) null));
assertEquals("[to] must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> builder.to((Number) null));
assertEquals("[to] must not be null", e.getMessage());
}
public void testInvalidOptimizeBBox() {
GeoDistanceRangeQueryBuilder builder = new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, new GeoPoint());
if (randomBoolean()) {
try {
builder.optimizeBbox(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("optimizeBbox must not be null"));
}
} else {
try {
builder.optimizeBbox("foo");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("optimizeBbox must be one of [none, memory, indexed]"));
}
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.optimizeBbox(null));
assertEquals("optimizeBbox must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> builder.optimizeBbox("foo"));
assertEquals("optimizeBbox must be one of [none, memory, indexed]", e.getMessage());
}
public void testInvalidGeoDistance() {
GeoDistanceRangeQueryBuilder builder = new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, new GeoPoint());
try {
builder.geoDistance(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("geoDistance calculation mode must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.geoDistance(null));
assertEquals("geoDistance calculation mode must not be null", e.getMessage());
}
public void testInvalidDistanceUnit() {
GeoDistanceRangeQueryBuilder builder = new GeoDistanceRangeQueryBuilder(GEO_POINT_FIELD_NAME, new GeoPoint());
try {
builder.unit(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("distance unit must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.unit(null));
assertEquals("distance unit must not be null", e.getMessage());
}
public void testNestedRangeQuery() throws IOException {

View File

@ -20,7 +20,6 @@
package org.elasticsearch.index.query;
import com.vividsolutions.jts.geom.Coordinate;
import org.apache.lucene.search.MatchNoDocsQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.spatial.geopoint.search.GeoPointInPolygonQuery;
@ -39,6 +38,7 @@ import org.locationtech.spatial4j.shape.jts.JtsGeometry;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import static org.elasticsearch.test.StreamsUtils.copyToStringFromClasspath;
@ -47,7 +47,6 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.closeTo;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class GeoPolygonQueryBuilderTests extends AbstractQueryTestCase<GeoPolygonQueryBuilder> {
@Override
@ -144,25 +143,17 @@ public class GeoPolygonQueryBuilderTests extends AbstractQueryTestCase<GeoPolygo
}
public void testNullFieldName() {
try {
new GeoPolygonQueryBuilder(null, randomPolygon(5));
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("fieldName must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new GeoPolygonQueryBuilder(null, randomPolygon(5)));
assertEquals("fieldName must not be null", e.getMessage());
}
public void testEmptyPolygon() {
try {
if (randomBoolean()) {
new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, new ArrayList<GeoPoint>());
} else {
new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, null);
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("polygon must not be null or empty"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, Collections.emptyList()));
assertEquals("polygon must not be null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, null));
assertEquals("polygon must not be null or empty", e.getMessage());
}
public void testInvalidClosedPolygon() {
@ -170,24 +161,18 @@ public class GeoPolygonQueryBuilderTests extends AbstractQueryTestCase<GeoPolygo
points.add(new GeoPoint(0, 90));
points.add(new GeoPoint(90, 90));
points.add(new GeoPoint(0, 90));
try {
new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, points);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("too few points defined for geo_polygon query"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, points));
assertEquals("too few points defined for geo_polygon query", e.getMessage());
}
public void testInvalidOpenPolygon() {
List<GeoPoint> points = new ArrayList<>();
points.add(new GeoPoint(0, 90));
points.add(new GeoPoint(90, 90));
try {
new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, points);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("too few points defined for geo_polygon query"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoPolygonQueryBuilder(GEO_POINT_FIELD_NAME, points));
assertEquals("too few points defined for geo_polygon query", e.getMessage());
}
public void testDeprecatedXContent() throws IOException {
@ -205,12 +190,8 @@ public class GeoPolygonQueryBuilderTests extends AbstractQueryTestCase<GeoPolygo
builder.field("normalize", true); // deprecated
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("normalize is deprecated");
} catch (IllegalArgumentException ex) {
assertEquals("Deprecated field [normalize] used, replaced by [use validation_method instead]", ex.getMessage());
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(builder.string()));
assertEquals("Deprecated field [normalize] used, replaced by [use validation_method instead]", e.getMessage());
}
public void testParsingAndToQueryParsingExceptions() throws IOException {
@ -223,12 +204,7 @@ public class GeoPolygonQueryBuilderTests extends AbstractQueryTestCase<GeoPolygo
};
for (String brokenFile : brokenFiles) {
String query = copyToStringFromClasspath(brokenFile);
try {
parseQuery(query);
fail("parsing a broken geo_polygon filter didn't fail as expected while parsing: " + brokenFile);
} catch (ParsingException e) {
// success!
}
expectThrows(ParsingException.class, () -> parseQuery(query));
}
}

View File

@ -20,7 +20,6 @@
package org.elasticsearch.index.query;
import com.vividsolutions.jts.geom.Coordinate;
import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.ConstantScoreQuery;
import org.apache.lucene.search.MatchNoDocsQuery;
@ -50,7 +49,6 @@ import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class GeoShapeQueryBuilderTests extends AbstractQueryTestCase<GeoShapeQueryBuilder> {
@ -156,70 +154,44 @@ public class GeoShapeQueryBuilderTests extends AbstractQueryTestCase<GeoShapeQue
public void testNoFieldName() throws Exception {
ShapeBuilder shape = RandomShapeGenerator.createShapeWithin(random(), null);
try {
new GeoShapeQueryBuilder(null, shape);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("fieldName is required"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new GeoShapeQueryBuilder(null, shape));
assertEquals("fieldName is required", e.getMessage());
}
public void testNoShape() throws IOException {
try {
new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, (ShapeBuilder) null);
fail("exception expected");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, null));
}
public void testNoIndexedShape() throws IOException {
try {
new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, null, "type");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("either shapeBytes or indexedShapeId and indexedShapeType are required"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, null, "type"));
assertEquals("either shapeBytes or indexedShapeId and indexedShapeType are required", e.getMessage());
}
public void testNoIndexedShapeType() throws IOException {
try {
new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, "id", null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("indexedShapeType is required if indexedShapeId is specified"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, "id", null));
assertEquals("indexedShapeType is required if indexedShapeId is specified", e.getMessage());
}
public void testNoRelation() throws IOException {
ShapeBuilder shape = RandomShapeGenerator.createShapeWithin(random(), null);
GeoShapeQueryBuilder builder = new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, shape);
try {
builder.relation(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("No Shape Relation defined"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.relation(null));
assertEquals("No Shape Relation defined", e.getMessage());
}
public void testInvalidRelation() throws IOException {
ShapeBuilder shape = RandomShapeGenerator.createShapeWithin(random(), null);
GeoShapeQueryBuilder builder = new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, shape);
try {
builder.strategy(SpatialStrategy.TERM);
builder.relation(randomFrom(ShapeRelation.DISJOINT, ShapeRelation.WITHIN));
fail("Illegal combination of strategy and relation setting");
} catch (IllegalArgumentException e) {
// okay
}
try {
builder.relation(randomFrom(ShapeRelation.DISJOINT, ShapeRelation.WITHIN));
builder.strategy(SpatialStrategy.TERM);
fail("Illegal combination of strategy and relation setting");
} catch (IllegalArgumentException e) {
// okay
}
builder.strategy(SpatialStrategy.TERM);
expectThrows(IllegalArgumentException.class, () -> builder.relation(randomFrom(ShapeRelation.DISJOINT, ShapeRelation.WITHIN)));
GeoShapeQueryBuilder builder2 = new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, shape);
builder2.relation(randomFrom(ShapeRelation.DISJOINT, ShapeRelation.WITHIN));
expectThrows(IllegalArgumentException.class, () -> builder2.strategy(SpatialStrategy.TERM));
GeoShapeQueryBuilder builder3 = new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, shape);
builder3.strategy(SpatialStrategy.TERM);
expectThrows(IllegalArgumentException.class, () -> builder3.relation(randomFrom(ShapeRelation.DISJOINT, ShapeRelation.WITHIN)));
}
// see #3878
@ -256,16 +228,15 @@ public class GeoShapeQueryBuilderTests extends AbstractQueryTestCase<GeoShapeQue
sqb = doCreateTestQueryBuilder();
// do this until we get one without a shape
} while (sqb.shape() != null);
try {
sqb.toQuery(createShardContext());
fail();
} catch (UnsupportedOperationException e) {
assertEquals("query must be rewritten first", e.getMessage());
}
QueryBuilder rewrite = sqb.rewrite(createShardContext());
GeoShapeQueryBuilder query = sqb;
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class, () -> query.toQuery(createShardContext()));
assertEquals("query must be rewritten first", e.getMessage());
QueryBuilder rewrite = query.rewrite(createShardContext());
GeoShapeQueryBuilder geoShapeQueryBuilder = new GeoShapeQueryBuilder(GEO_SHAPE_FIELD_NAME, indexedShapeToReturn);
geoShapeQueryBuilder.strategy(sqb.strategy());
geoShapeQueryBuilder.relation(sqb.relation());
geoShapeQueryBuilder.strategy(query.strategy());
geoShapeQueryBuilder.relation(query.relation());
assertEquals(geoShapeQueryBuilder, rewrite);
}

View File

@ -39,7 +39,6 @@ import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
public class GeohashCellQueryBuilderTests extends AbstractQueryTestCase<Builder> {
@ -92,39 +91,23 @@ public class GeohashCellQueryBuilderTests extends AbstractQueryTestCase<Builder>
}
public void testNullField() {
try {
if (randomBoolean()) {
new Builder(null, new GeoPoint());
} else {
new Builder("", new GeoPoint());
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("fieldName must not be null"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new Builder(null, new GeoPoint()));
assertEquals("fieldName must not be null", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new Builder("", new GeoPoint()));
assertEquals("fieldName must not be null", e.getMessage());
}
public void testNullGeoPoint() {
try {
if (randomBoolean()) {
new Builder(GEO_POINT_FIELD_NAME, (GeoPoint) null);
} else {
new Builder(GEO_POINT_FIELD_NAME, "");
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("geohash or point must be defined"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new Builder(GEO_POINT_FIELD_NAME, (GeoPoint) null));
assertEquals("geohash or point must be defined", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new Builder(GEO_POINT_FIELD_NAME, ""));
assertEquals("geohash or point must be defined", e.getMessage());
}
public void testInvalidPrecision() {
GeohashCellQuery.Builder builder = new Builder(GEO_POINT_FIELD_NAME, new GeoPoint());
try {
builder.precision(-1);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("precision must be greater than 0"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> builder.precision(-1));
assertThat(e.getMessage(), containsString("precision must be greater than 0"));
}
public void testLocationParsing() throws IOException {

View File

@ -21,7 +21,6 @@ package org.elasticsearch.index.query;
import com.carrotsearch.randomizedtesting.generators.RandomPicks;
import com.fasterxml.jackson.core.JsonParseException;
import org.apache.lucene.queries.TermsQuery;
import org.apache.lucene.search.BooleanClause;
import org.apache.lucene.search.BooleanQuery;
@ -63,7 +62,6 @@ import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.hamcrest.Matchers.is;
public class HasChildQueryBuilderTests extends AbstractQueryTestCase<HasChildQueryBuilder> {
protected static final String PARENT_TYPE = "parent";
@ -367,24 +365,17 @@ public class HasChildQueryBuilderTests extends AbstractQueryTestCase<HasChildQue
* Should throw {@link IllegalArgumentException} instead of NPE.
*/
public void testThatNullFromStringThrowsException() {
try {
HasChildQueryBuilder.parseScoreMode(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("No score mode for child query [null] found"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> HasChildQueryBuilder.parseScoreMode(null));
assertEquals("No score mode for child query [null] found", e.getMessage());
}
/**
* Failure should not change (and the value should never match anything...).
*/
public void testThatUnrecognizedFromStringThrowsException() {
try {
HasChildQueryBuilder.parseScoreMode("unrecognized value");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("No score mode for child query [unrecognized value] found"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> HasChildQueryBuilder.parseScoreMode("unrecognized value"));
assertEquals("No score mode for child query [unrecognized value] found", e.getMessage());
}
public void testIgnoreUnmapped() throws IOException {

View File

@ -157,12 +157,8 @@ public class HasParentQueryBuilderTests extends AbstractQueryTestCase<HasParentQ
builder.field("type", "foo"); // deprecated
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("type is deprecated");
} catch (IllegalArgumentException ex) {
assertEquals("Deprecated field [type] used, expected [parent_type] instead", ex.getMessage());
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(builder.string()));
assertEquals("Deprecated field [type] used, expected [parent_type] instead", e.getMessage());
HasParentQueryBuilder queryBuilder = (HasParentQueryBuilder) parseQuery(builder.string(), ParseFieldMatcher.EMPTY);
assertEquals("foo", queryBuilder.type());

View File

@ -32,7 +32,6 @@ import java.io.IOException;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.is;
public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder> {
/**
@ -40,12 +39,8 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
*/
public void testIdsNotProvided() throws IOException {
String noIdsFieldQuery = "{\"ids\" : { \"type\" : \"my_type\" }";
try {
parseQuery(noIdsFieldQuery);
fail("Expected ParsingException");
} catch (ParsingException e) {
assertThat(e.getMessage(), containsString("no ids values provided"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(noIdsFieldQuery));
assertThat(e.getMessage(), containsString("no ids values provided"));
}
@Override
@ -94,30 +89,19 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
}
public void testIllegalArguments() {
try {
new IdsQueryBuilder((String[])null);
fail("must be not null");
} catch(IllegalArgumentException e) {
//all good
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new IdsQueryBuilder((String[]) null));
assertEquals("[ids] types cannot be null", e.getMessage());
try {
new IdsQueryBuilder().addIds((String[])null);
fail("must be not null");
} catch(IllegalArgumentException e) {
//all good
}
IdsQueryBuilder idsQueryBuilder = new IdsQueryBuilder();
e = expectThrows(IllegalArgumentException.class, () -> idsQueryBuilder.addIds((String[])null));
assertEquals("[ids] ids cannot be null", e.getMessage());
}
// see #7686.
public void testIdsQueryWithInvalidValues() throws Exception {
String query = "{ \"ids\": { \"values\": [[1]] } }";
try {
parseQuery(query);
fail("Expected ParsingException");
} catch (ParsingException e) {
assertThat(e.getMessage(), is("Illegal value for id, expecting a string or number, got: START_ARRAY"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(query));
assertEquals("Illegal value for id, expecting a string or number, got: START_ARRAY", e.getMessage());
}
public void testFromJson() throws IOException {
@ -143,7 +127,7 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
IdsQueryBuilder testQuery = new IdsQueryBuilder(type);
//single value type can also be called _type
String contentString = "{\n" +
final String contentString = "{\n" +
" \"ids\" : {\n" +
" \"_type\" : \"" + type + "\",\n" +
" \"values\" : []\n" +
@ -153,15 +137,11 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
IdsQueryBuilder parsed = (IdsQueryBuilder) parseQuery(contentString, ParseFieldMatcher.EMPTY);
assertEquals(testQuery, parsed);
try {
parseQuery(contentString);
fail("parse should have failed");
} catch(IllegalArgumentException e) {
assertEquals("Deprecated field [_type] used, expected [type] instead", e.getMessage());
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(contentString));
assertEquals("Deprecated field [_type] used, expected [type] instead", e.getMessage());
//array of types can also be called type rather than types
contentString = "{\n" +
final String contentString2 = "{\n" +
" \"ids\" : {\n" +
" \"types\" : [\"" + type + "\"],\n" +
" \"values\" : []\n" +
@ -169,11 +149,8 @@ public class IdsQueryBuilderTests extends AbstractQueryTestCase<IdsQueryBuilder>
"}";
parsed = (IdsQueryBuilder) parseQuery(contentString, ParseFieldMatcher.EMPTY);
assertEquals(testQuery, parsed);
try {
parseQuery(contentString);
fail("parse should have failed");
} catch(IllegalArgumentException e) {
assertEquals("Deprecated field [types] used, expected [type] instead", e.getMessage());
}
e = expectThrows(IllegalArgumentException.class, () -> parseQuery(contentString2));
assertEquals("Deprecated field [types] used, expected [type] instead", e.getMessage());
}
}

View File

@ -61,12 +61,7 @@ public class IndicesQueryBuilderTests extends AbstractQueryTestCase<IndicesQuery
}
public void testIllegalArguments() {
try {
new IndicesQueryBuilder(null, "index");
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> new IndicesQueryBuilder(null, "index"));
expectThrows(IllegalArgumentException.class, () -> new IndicesQueryBuilder(new MatchAllQueryBuilder(), (String[]) null));
expectThrows(IllegalArgumentException.class, () -> new IndicesQueryBuilder(new MatchAllQueryBuilder(), new String[0]));

View File

@ -23,11 +23,15 @@ import org.apache.lucene.search.BooleanQuery;
import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.search.MatchNoDocsQuery;
import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.containsString;
@ -69,6 +73,20 @@ public class MatchPhrasePrefixQueryBuilderTests extends AbstractQueryTestCase<Ma
return matchQuery;
}
@Override
protected Map<String, MatchPhrasePrefixQueryBuilder> getAlternateVersions() {
Map<String, MatchPhrasePrefixQueryBuilder> alternateVersions = new HashMap<>();
MatchPhrasePrefixQueryBuilder matchPhrasePrefixQuery = new MatchPhrasePrefixQueryBuilder(randomAsciiOfLengthBetween(1, 10),
randomAsciiOfLengthBetween(1, 10));
String contentString = "{\n" +
" \"match_phrase_prefix\" : {\n" +
" \"" + matchPhrasePrefixQuery.fieldName() + "\" : \"" + matchPhrasePrefixQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, matchPhrasePrefixQuery);
return alternateVersions;
}
@Override
protected void doAssertLuceneQuery(MatchPhrasePrefixQueryBuilder queryBuilder, Query query, QueryShardContext context)
throws IOException {
@ -79,39 +97,22 @@ public class MatchPhrasePrefixQueryBuilderTests extends AbstractQueryTestCase<Ma
}
public void testIllegalValues() {
try {
new MatchPhrasePrefixQueryBuilder(null, "value");
fail("value must not be non-null");
} catch (IllegalArgumentException ex) {
// expected
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new MatchPhrasePrefixQueryBuilder(null, "value"));
assertEquals("[match_phrase_prefix] requires fieldName", e.getMessage());
try {
new MatchPhrasePrefixQueryBuilder("fieldName", null);
fail("value must not be non-null");
} catch (IllegalArgumentException ex) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new MatchPhrasePrefixQueryBuilder("fieldName", null));
assertEquals("[match_phrase_prefix] requires query value", e.getMessage());
MatchPhrasePrefixQueryBuilder matchQuery = new MatchPhrasePrefixQueryBuilder("fieldName", "text");
try {
matchQuery.maxExpansions(-1);
fail("must not be positive");
} catch (IllegalArgumentException ex) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> matchQuery.maxExpansions(-1));
}
public void testBadAnalyzer() throws IOException {
MatchPhrasePrefixQueryBuilder matchQuery = new MatchPhrasePrefixQueryBuilder("fieldName", "text");
matchQuery.analyzer("bogusAnalyzer");
try {
matchQuery.toQuery(createShardContext());
fail("Expected QueryShardException");
} catch (QueryShardException e) {
assertThat(e.getMessage(), containsString("analyzer [bogusAnalyzer] not found"));
}
QueryShardException e = expectThrows(QueryShardException.class, () -> matchQuery.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("analyzer [bogusAnalyzer] not found"));
}
public void testPhrasePrefixMatchQuery() throws IOException {
@ -155,4 +156,20 @@ public class MatchPhrasePrefixQueryBuilderTests extends AbstractQueryTestCase<Ma
qb = (MatchPhrasePrefixQueryBuilder) parseQuery(json3);
checkGeneratedJson(expected, qb);
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"match_phrase_prefix\" : {\n" +
" \"message1\" : {\n" +
" \"query\" : \"this is a test\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"query\" : \"this is a test\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[match_phrase_prefix] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
}
}

View File

@ -24,10 +24,13 @@ import org.apache.lucene.search.PhraseQuery;
import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.search.MatchNoDocsQuery;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.instanceOf;
@ -66,6 +69,20 @@ public class MatchPhraseQueryBuilderTests extends AbstractQueryTestCase<MatchPhr
return matchQuery;
}
@Override
protected Map<String, MatchPhraseQueryBuilder> getAlternateVersions() {
Map<String, MatchPhraseQueryBuilder> alternateVersions = new HashMap<>();
MatchPhraseQueryBuilder matchPhraseQuery = new MatchPhraseQueryBuilder(randomAsciiOfLengthBetween(1, 10),
randomAsciiOfLengthBetween(1, 10));
String contentString = "{\n" +
" \"match_phrase\" : {\n" +
" \"" + matchPhraseQuery.fieldName() + "\" : \"" + matchPhraseQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, matchPhraseQuery);
return alternateVersions;
}
@Override
protected void doAssertLuceneQuery(MatchPhraseQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, notNullValue());
@ -74,30 +91,18 @@ public class MatchPhraseQueryBuilderTests extends AbstractQueryTestCase<MatchPhr
}
public void testIllegalValues() {
try {
new MatchPhraseQueryBuilder(null, "value");
fail("value must not be non-null");
} catch (IllegalArgumentException ex) {
// expected
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new MatchPhraseQueryBuilder(null, "value"));
assertEquals("[match_phrase] requires fieldName", e.getMessage());
try {
new MatchPhraseQueryBuilder("fieldName", null);
fail("value must not be non-null");
} catch (IllegalArgumentException ex) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new MatchPhraseQueryBuilder("fieldName", null));
assertEquals("[match_phrase] requires query value", e.getMessage());
}
public void testBadAnalyzer() throws IOException {
MatchPhraseQueryBuilder matchQuery = new MatchPhraseQueryBuilder("fieldName", "text");
matchQuery.analyzer("bogusAnalyzer");
try {
matchQuery.toQuery(createShardContext());
fail("Expected QueryShardException");
} catch (QueryShardException e) {
assertThat(e.getMessage(), containsString("analyzer [bogusAnalyzer] not found"));
}
QueryShardException e = expectThrows(QueryShardException.class, () -> matchQuery.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("analyzer [bogusAnalyzer] not found"));
}
public void testPhraseMatchQuery() throws IOException {
@ -119,4 +124,19 @@ public class MatchPhraseQueryBuilderTests extends AbstractQueryTestCase<MatchPhr
MatchPhraseQueryBuilder qb = (MatchPhraseQueryBuilder) parseQuery(json1);
checkGeneratedJson(expected, qb);
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"match_phrase\" : {\n" +
" \"message1\" : {\n" +
" \"query\" : \"this is a test\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"query\" : \"this is a test\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[match_phrase] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
}
}

View File

@ -29,6 +29,7 @@ import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.search.MatchNoDocsQuery;
import org.elasticsearch.common.lucene.search.MultiPhrasePrefixQuery;
import org.elasticsearch.common.lucene.search.Queries;
@ -40,7 +41,9 @@ import org.elasticsearch.test.AbstractQueryTestCase;
import org.hamcrest.Matcher;
import java.io.IOException;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import static org.hamcrest.CoreMatchers.either;
import static org.hamcrest.CoreMatchers.instanceOf;
@ -118,6 +121,19 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
return matchQuery;
}
@Override
protected Map<String, MatchQueryBuilder> getAlternateVersions() {
Map<String, MatchQueryBuilder> alternateVersions = new HashMap<>();
MatchQueryBuilder matchQuery = new MatchQueryBuilder(randomAsciiOfLengthBetween(1, 10), randomAsciiOfLengthBetween(1, 10));
String contentString = "{\n" +
" \"match\" : {\n" +
" \"" + matchQuery.fieldName() + "\" : \"" + matchQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, matchQuery);
return alternateVersions;
}
@Override
protected void doAssertLuceneQuery(MatchQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, notNullValue());
@ -297,13 +313,9 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
assertSerialization(qb);
// Now check with strict parsing an exception is thrown
try {
parseQuery(json, ParseFieldMatcher.STRICT);
fail("Expected query to fail with strict parsing");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(),
containsString("Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query]"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(json, ParseFieldMatcher.STRICT));
assertThat(e.getMessage(),
containsString("Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query]"));
}
public void testLegacyMatchPhraseQuery() throws IOException {
@ -334,13 +346,9 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
assertSerialization(qb);
// Now check with strict parsing an exception is thrown
try {
parseQuery(json, ParseFieldMatcher.STRICT);
fail("Expected query to fail with strict parsing");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(),
containsString("Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query]"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(json, ParseFieldMatcher.STRICT));
assertThat(e.getMessage(),
containsString("Deprecated field [type] used, replaced by [match_phrase and match_phrase_prefix query]"));
}
public void testLegacyFuzzyMatchQuery() throws IOException {
@ -365,13 +373,8 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
assertThat(qb, equalTo(expectedQB));
// Now check with strict parsing an exception is thrown
try {
parseQuery(json, ParseFieldMatcher.STRICT);
fail("Expected query to fail with strict parsing");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(),
containsString("Deprecated field [" + type + "] used, expected [match] instead"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(json, ParseFieldMatcher.STRICT));
assertThat(e.getMessage(), containsString("Deprecated field [" + type + "] used, expected [match] instead"));
}
public void testFuzzinessOnNonStringField() throws Exception {
@ -399,11 +402,24 @@ public class MatchQueryBuilderTests extends AbstractQueryTestCase<MatchQueryBuil
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
MatchQueryBuilder query = new MatchQueryBuilder(GEO_POINT_FIELD_NAME, "2,3");
QueryShardContext context = createShardContext();
QueryShardException e = expectThrows(QueryShardException.class,
() -> query.toQuery(context));
assertEquals("Geo fields do not support exact searching, use dedicated geo queries instead: [mapped_geo_point]",
e.getMessage());
QueryShardException e = expectThrows(QueryShardException.class, () -> query.toQuery(context));
assertEquals("Geo fields do not support exact searching, use dedicated geo queries instead: [mapped_geo_point]", e.getMessage());
query.lenient(true);
query.toQuery(context); // no exception
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"match\" : {\n" +
" \"message1\" : {\n" +
" \"query\" : \"this is a test\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"query\" : \"this is a test\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[match] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
}
}

View File

@ -245,23 +245,16 @@ public class MoreLikeThisQueryBuilderTests extends AbstractQueryTestCase<MoreLik
}
public void testValidateEmptyFields() {
try {
new MoreLikeThisQueryBuilder(new String[0], new String[]{"likeText"}, null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("requires 'fields' to be specified"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> new MoreLikeThisQueryBuilder(new String[0], new String[]{"likeText"}, null));
assertThat(e.getMessage(), containsString("requires 'fields' to be specified"));
}
public void testValidateEmptyLike() {
String[] likeTexts = randomBoolean() ? null : new String[0];
Item[] likeItems = randomBoolean() ? null : new Item[0];
try {
new MoreLikeThisQueryBuilder(likeTexts, likeItems);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("requires either 'like' texts or items to be specified"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new MoreLikeThisQueryBuilder(likeTexts, likeItems));
assertThat(e.getMessage(), containsString("requires either 'like' texts or items to be specified"));
}
public void testUnsupportedFields() throws IOException {
@ -269,12 +262,8 @@ public class MoreLikeThisQueryBuilderTests extends AbstractQueryTestCase<MoreLik
String unsupportedField = randomFrom(INT_FIELD_NAME, DOUBLE_FIELD_NAME, DATE_FIELD_NAME);
MoreLikeThisQueryBuilder queryBuilder = new MoreLikeThisQueryBuilder(new String[] {unsupportedField}, new String[]{"some text"}, null)
.failOnUnsupportedField(true);
try {
queryBuilder.toQuery(createShardContext());
fail("should have failed with IllegalArgumentException for field: " + unsupportedField);
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), containsString("more_like_this only supports text/keyword fields"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> queryBuilder.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("more_like_this only supports text/keyword fields"));
}
public void testMoreLikeThisBuilder() throws Exception {
@ -337,7 +326,7 @@ public class MoreLikeThisQueryBuilderTests extends AbstractQueryTestCase<MoreLik
assertEquals(json, 2, parsed.fields().length);
assertEquals(json, "and potentially some more text here as well", parsed.likeTexts()[0]);
json =
String deprecatedJson =
"{\n" +
" \"mlt\" : {\n" +
" \"fields\" : [ \"title\", \"description\" ],\n" +
@ -364,14 +353,10 @@ public class MoreLikeThisQueryBuilderTests extends AbstractQueryTestCase<MoreLik
" }\n" +
"}";
MoreLikeThisQueryBuilder parsedQueryMltShortcut = (MoreLikeThisQueryBuilder) parseQuery(json, ParseFieldMatcher.EMPTY);
MoreLikeThisQueryBuilder parsedQueryMltShortcut = (MoreLikeThisQueryBuilder) parseQuery(deprecatedJson, ParseFieldMatcher.EMPTY);
assertThat(parsedQueryMltShortcut, equalTo(parsed));
try {
parseQuery(json);
fail("parse query should have failed in strict mode");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Deprecated field [mlt] used, expected [more_like_this] instead"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(deprecatedJson));
assertEquals("Deprecated field [mlt] used, expected [more_like_this] instead", e.getMessage());
}
}

View File

@ -154,33 +154,10 @@ public class MultiMatchQueryBuilderTests extends AbstractQueryTestCase<MultiMatc
}
public void testIllegaArguments() {
try {
new MultiMatchQueryBuilder(null, "field");
fail("value must not be null");
} catch (IllegalArgumentException e) {
// expected
}
try {
new MultiMatchQueryBuilder("value", (String[]) null);
fail("initial fields must be supplied at construction time must not be null");
} catch (IllegalArgumentException e) {
// expected
}
try {
new MultiMatchQueryBuilder("value", new String[]{""});
fail("field names cannot be empty");
} catch (IllegalArgumentException e) {
// expected
}
try {
new MultiMatchQueryBuilder("value", "field").type(null);
fail("type must not be null");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> new MultiMatchQueryBuilder(null, "field"));
expectThrows(IllegalArgumentException.class, () -> new MultiMatchQueryBuilder("value", (String[]) null));
expectThrows(IllegalArgumentException.class, () -> new MultiMatchQueryBuilder("value", new String[]{""}));
expectThrows(IllegalArgumentException.class, () -> new MultiMatchQueryBuilder("value", "field").type(null));
}
public void testToQueryBoost() throws IOException {

View File

@ -23,9 +23,12 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.MultiTermQuery;
import org.apache.lucene.search.PrefixQuery;
import org.apache.lucene.search.Query;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.elasticsearch.index.query.QueryBuilders.prefixQuery;
import static org.hamcrest.Matchers.equalTo;
@ -35,16 +38,32 @@ public class PrefixQueryBuilderTests extends AbstractQueryTestCase<PrefixQueryBu
@Override
protected PrefixQueryBuilder doCreateTestQueryBuilder() {
String fieldName = randomBoolean() ? STRING_FIELD_NAME : randomAsciiOfLengthBetween(1, 10);
String value = randomAsciiOfLengthBetween(1, 10);
PrefixQueryBuilder query = new PrefixQueryBuilder(fieldName, value);
PrefixQueryBuilder query = randomPrefixQuery();
if (randomBoolean()) {
query.rewrite(getRandomRewriteMethod());
}
return query;
}
@Override
protected Map<String, PrefixQueryBuilder> getAlternateVersions() {
Map<String, PrefixQueryBuilder> alternateVersions = new HashMap<>();
PrefixQueryBuilder prefixQuery = randomPrefixQuery();
String contentString = "{\n" +
" \"prefix\" : {\n" +
" \"" + prefixQuery.fieldName() + "\" : \"" + prefixQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, prefixQuery);
return alternateVersions;
}
private static PrefixQueryBuilder randomPrefixQuery() {
String fieldName = randomBoolean() ? STRING_FIELD_NAME : randomAsciiOfLengthBetween(1, 10);
String value = randomAsciiOfLengthBetween(1, 10);
return new PrefixQueryBuilder(fieldName, value);
}
@Override
protected void doAssertLuceneQuery(PrefixQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, instanceOf(PrefixQuery.class));
@ -54,23 +73,13 @@ public class PrefixQueryBuilderTests extends AbstractQueryTestCase<PrefixQueryBu
}
public void testIllegalArguments() {
try {
if (randomBoolean()) {
new PrefixQueryBuilder(null, "text");
} else {
new PrefixQueryBuilder("", "text");
}
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new PrefixQueryBuilder(null, "text"));
assertEquals("field name is null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new PrefixQueryBuilder("", "text"));
assertEquals("field name is null or empty", e.getMessage());
try {
new PrefixQueryBuilder("field", null);
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new PrefixQueryBuilder("field", null));
assertEquals("value cannot be null", e.getMessage());
}
public void testBlendedRewriteMethod() throws IOException {
@ -103,4 +112,20 @@ public class PrefixQueryBuilderTests extends AbstractQueryTestCase<PrefixQueryBu
assertEquals("Can only use prefix queries on keyword and text fields - not on [mapped_int] which is of type [integer]",
e.getMessage());
}
public void testParseFailsWithMultipleFields() throws IOException {
String json =
"{\n" +
" \"prefix\": {\n" +
" \"user1\": {\n" +
" \"value\": \"ki\"\n" +
" },\n" +
" \"user2\": {\n" +
" \"value\": \"ki\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[prefix] query doesn't support multiple fields, found [user1] and [user2]", e.getMessage());
}
}

View File

@ -54,12 +54,8 @@ public class QueryShardContextTests extends ESTestCase {
MappedFieldType fieldType = new TextFieldMapper.TextFieldType();
MappedFieldType result = context.failIfFieldMappingNotFound("name", fieldType);
assertThat(result, sameInstance(fieldType));
try {
context.failIfFieldMappingNotFound("name", null);
fail("exception expected");
} catch (QueryShardException e) {
assertThat(e.getMessage(), equalTo("No field mapping can be found for the field with name [name]"));
}
QueryShardException e = expectThrows(QueryShardException.class, () -> context.failIfFieldMappingNotFound("name", null));
assertEquals("No field mapping can be found for the field with name [name]", e.getMessage());
context.setAllowUnmappedFields(true);
result = context.failIfFieldMappingNotFound("name", fieldType);

View File

@ -382,13 +382,12 @@ public class QueryStringQueryBuilderTests extends AbstractQueryTestCase<QueryStr
public void testToQueryRegExpQueryTooComplex() throws Exception {
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
try {
queryStringQuery("/[ac]*a[ac]{50,200}/").defaultField(STRING_FIELD_NAME).toQuery(createShardContext());
fail("Expected TooComplexToDeterminizeException");
} catch (TooComplexToDeterminizeException e) {
assertThat(e.getMessage(), containsString("Determinizing [ac]*"));
assertThat(e.getMessage(), containsString("would result in more than 10000 states"));
}
QueryStringQueryBuilder queryBuilder = queryStringQuery("/[ac]*a[ac]{50,200}/").defaultField(STRING_FIELD_NAME);
TooComplexToDeterminizeException e = expectThrows(TooComplexToDeterminizeException.class,
() -> queryBuilder.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("Determinizing [ac]*"));
assertThat(e.getMessage(), containsString("would result in more than 10000 states"));
}
public void testFuzzyNumeric() throws Exception {
@ -440,18 +439,13 @@ public class QueryStringQueryBuilderTests extends AbstractQueryTestCase<QueryStr
QueryStringQueryBuilder queryStringQueryBuilder = (QueryStringQueryBuilder) queryBuilder;
assertThat(queryStringQueryBuilder.timeZone(), equalTo(DateTimeZone.forID("Europe/Paris")));
try {
queryAsString = "{\n" +
" \"query_string\":{\n" +
" \"time_zone\":\"This timezone does not exist\",\n" +
" \"query\":\"" + DATE_FIELD_NAME + ":[2012 TO 2014]\"\n" +
" }\n" +
"}";
parseQuery(queryAsString);
fail("we expect a ParsingException as we are providing an unknown time_zome");
} catch (IllegalArgumentException e) {
// We expect this one
}
String invalidQueryAsString = "{\n" +
" \"query_string\":{\n" +
" \"time_zone\":\"This timezone does not exist\",\n" +
" \"query\":\"" + DATE_FIELD_NAME + ":[2012 TO 2014]\"\n" +
" }\n" +
"}";
expectThrows(IllegalArgumentException.class, () -> parseQuery(invalidQueryAsString));
}
public void testToQueryBooleanQueryMultipleBoosts() throws Exception {

View File

@ -27,6 +27,7 @@ import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermRangeQuery;
import org.elasticsearch.ElasticsearchParseException;
import org.elasticsearch.common.ParseFieldMatcher;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.index.mapper.MappedFieldType;
import org.elasticsearch.index.mapper.MappedFieldType.Relation;
@ -171,27 +172,10 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
expectThrows(IllegalArgumentException.class, () -> new RangeQueryBuilder(""));
RangeQueryBuilder rangeQueryBuilder = new RangeQueryBuilder("test");
try {
if (randomBoolean()) {
rangeQueryBuilder.timeZone(null);
} else {
rangeQueryBuilder.timeZone("badID");
}
fail("cannot be null or unknown id");
} catch (IllegalArgumentException e) {
// expected
}
try {
if (randomBoolean()) {
rangeQueryBuilder.format(null);
} else {
rangeQueryBuilder.format("badFormat");
}
fail("cannot be null or bad format");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> rangeQueryBuilder.timeZone(null));
expectThrows(IllegalArgumentException.class, () -> rangeQueryBuilder.timeZone("badID"));
expectThrows(IllegalArgumentException.class, () -> rangeQueryBuilder.format(null));
expectThrows(IllegalArgumentException.class, () -> rangeQueryBuilder.format("badFormat"));
}
/**
@ -200,12 +184,8 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
public void testToQueryNonDateWithTimezone() throws QueryShardException, IOException {
RangeQueryBuilder query = new RangeQueryBuilder(INT_FIELD_NAME);
query.from(1).to(10).timeZone("UTC");
try {
query.toQuery(createShardContext());
fail("Expected QueryShardException");
} catch (QueryShardException e) {
assertThat(e.getMessage(), containsString("[range] time_zone can not be applied"));
}
QueryShardException e = expectThrows(QueryShardException.class, () -> query.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("[range] time_zone can not be applied"));
}
/**
@ -214,12 +194,8 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
public void testToQueryUnmappedWithTimezone() throws QueryShardException, IOException {
RangeQueryBuilder query = new RangeQueryBuilder("bogus_field");
query.from(1).to(10).timeZone("UTC");
try {
query.toQuery(createShardContext());
fail("Expected QueryShardException");
} catch (QueryShardException e) {
assertThat(e.getMessage(), containsString("[range] time_zone can not be applied"));
}
QueryShardException e = expectThrows(QueryShardException.class, () -> query.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("[range] time_zone can not be applied"));
}
public void testToQueryNumericField() throws IOException {
@ -270,7 +246,7 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
}
// Test Invalid format
query = "{\n" +
final String invalidQuery = "{\n" +
" \"range\" : {\n" +
" \"" + DATE_FIELD_NAME + "\" : {\n" +
" \"gte\": \"01/01/2012\",\n" +
@ -279,12 +255,8 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
" }\n" +
" }\n" +
"}";
try {
parseQuery(query).toQuery(createShardContext()).rewrite(null);
fail("A Range Query with a specific format but with an unexpected date should raise a ParsingException");
} catch (ElasticsearchParseException e) {
// We expect it
}
Query rewrittenQuery = parseQuery(invalidQuery).toQuery(createShardContext());
expectThrows(ElasticsearchParseException.class, () -> rewrittenQuery.rewrite(null));
}
public void testDateRangeBoundaries() throws IOException {
@ -382,12 +354,8 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
" }\n" +
" }\n" +
"}";
try {
parseQuery(query).toQuery(createShardContext());
fail("A Range Query on a numeric field with a TimeZone should raise a ParsingException");
} catch (QueryShardException e) {
// We expect it
}
QueryBuilder queryBuilder = parseQuery(query);
expectThrows(QueryShardException.class, () -> queryBuilder.toQuery(createShardContext()));
}
public void testFromJson() throws IOException {
@ -426,7 +394,7 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
"}";
assertNotNull(parseQuery(json));
json =
final String deprecatedJson =
"{\n" +
" \"range\" : {\n" +
" \"timestamp\" : {\n" +
@ -442,12 +410,10 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
assertNotNull(parseQuery(json, ParseFieldMatcher.EMPTY));
// with strict parsing, ParseField will throw exception
try {
parseQuery(json, ParseFieldMatcher.STRICT);
fail("Strict parsing should trigger exception for '_name' on top level");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Deprecated field [_name] used, replaced by [query name is not supported in short version of range query]"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class,
() -> parseQuery(deprecatedJson, ParseFieldMatcher.STRICT));
assertEquals("Deprecated field [_name] used, replaced by [query name is not supported in short version of range query]",
e.getMessage());
}
public void testRewriteDateToMatchAll() throws IOException {
@ -460,8 +426,6 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
};
DateTime queryFromValue = new DateTime(2015, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
DateTime queryToValue = new DateTime(2016, 1, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
DateTime shardMinValue = new DateTime(2015, 3, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
DateTime shardMaxValue = new DateTime(2015, 9, 1, 0, 0, 0, ISOChronology.getInstanceUTC());
query.from(queryFromValue);
query.to(queryToValue);
QueryShardContext queryShardContext = createShardContext();
@ -519,4 +483,22 @@ public class RangeQueryBuilderTests extends AbstractQueryTestCase<RangeQueryBuil
QueryBuilder rewritten = query.rewrite(queryShardContext);
assertThat(rewritten, sameInstance(query));
}
public void testParseFailsWithMultipleFields() throws IOException {
String json =
"{\n" +
" \"range\": {\n" +
" \"age\": {\n" +
" \"gte\": 30,\n" +
" \"lte\": 40\n" +
" },\n" +
" \"price\": {\n" +
" \"gte\": 10,\n" +
" \"lte\": 30\n" +
" }\n" +
" }\n" +
" }";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[range] query doesn't support multiple fields, found [age] and [price]", e.getMessage());
}
}

View File

@ -21,11 +21,14 @@ package org.elasticsearch.index.query;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.RegexpQuery;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
@ -34,11 +37,7 @@ public class RegexpQueryBuilderTests extends AbstractQueryTestCase<RegexpQueryBu
@Override
protected RegexpQueryBuilder doCreateTestQueryBuilder() {
// mapped or unmapped fields
String fieldName = randomBoolean() ? STRING_FIELD_NAME : randomAsciiOfLengthBetween(1, 10);
String value = randomAsciiOfLengthBetween(1, 10);
RegexpQueryBuilder query = new RegexpQueryBuilder(fieldName, value);
RegexpQueryBuilder query = randomRegexpQuery();
if (randomBoolean()) {
List<RegexpFlag> flags = new ArrayList<>();
int iter = randomInt(5);
@ -56,6 +55,26 @@ public class RegexpQueryBuilderTests extends AbstractQueryTestCase<RegexpQueryBu
return query;
}
@Override
protected Map<String, RegexpQueryBuilder> getAlternateVersions() {
Map<String, RegexpQueryBuilder> alternateVersions = new HashMap<>();
RegexpQueryBuilder regexpQuery = randomRegexpQuery();
String contentString = "{\n" +
" \"regexp\" : {\n" +
" \"" + regexpQuery.fieldName() + "\" : \"" + regexpQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, regexpQuery);
return alternateVersions;
}
private static RegexpQueryBuilder randomRegexpQuery() {
// mapped or unmapped fields
String fieldName = randomBoolean() ? STRING_FIELD_NAME : randomAsciiOfLengthBetween(1, 10);
String value = randomAsciiOfLengthBetween(1, 10);
return new RegexpQueryBuilder(fieldName, value);
}
@Override
protected void doAssertLuceneQuery(RegexpQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, instanceOf(RegexpQuery.class));
@ -64,23 +83,13 @@ public class RegexpQueryBuilderTests extends AbstractQueryTestCase<RegexpQueryBu
}
public void testIllegalArguments() {
try {
if (randomBoolean()) {
new RegexpQueryBuilder(null, "text");
} else {
new RegexpQueryBuilder("", "text");
}
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new RegexpQueryBuilder(null, "text"));
assertEquals("field name is null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new RegexpQueryBuilder("", "text"));
assertEquals("field name is null or empty", e.getMessage());
try {
new RegexpQueryBuilder("field", null);
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new RegexpQueryBuilder("field", null));
assertEquals("value cannot be null", e.getMessage());
}
public void testFromJson() throws IOException {
@ -107,9 +116,24 @@ public class RegexpQueryBuilderTests extends AbstractQueryTestCase<RegexpQueryBu
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
RegexpQueryBuilder query = new RegexpQueryBuilder(INT_FIELD_NAME, "12");
QueryShardContext context = createShardContext();
QueryShardException e = expectThrows(QueryShardException.class,
() -> query.toQuery(context));
QueryShardException e = expectThrows(QueryShardException.class, () -> query.toQuery(context));
assertEquals("Can only use regexp queries on keyword and text fields - not on [mapped_int] which is of type [integer]",
e.getMessage());
}
public void testParseFailsWithMultipleFields() throws IOException {
String json =
"{\n" +
" \"regexp\": {\n" +
" \"user1\": {\n" +
" \"value\": \"k.*y\"\n" +
" },\n" +
" \"user2\": {\n" +
" \"value\": \"k.*y\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[regexp] query doesn't support multiple fields, found [user1] and [user2]", e.getMessage());
}
}

View File

@ -179,42 +179,26 @@ public class SimpleQueryStringBuilderTests extends AbstractQueryTestCase<SimpleQ
public void testFieldCannotBeNull() {
SimpleQueryStringBuilder qb = createTestQueryBuilder();
try {
qb.field(null);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("supplied field is null or empty."));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field(null));
assertEquals("supplied field is null or empty", e.getMessage());
}
public void testFieldCannotBeNullAndWeighted() {
SimpleQueryStringBuilder qb = createTestQueryBuilder();
try {
qb.field(null, AbstractQueryBuilder.DEFAULT_BOOST);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("supplied field is null or empty."));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field(null, AbstractQueryBuilder.DEFAULT_BOOST));
assertEquals("supplied field is null or empty", e.getMessage());
}
public void testFieldCannotBeEmpty() {
SimpleQueryStringBuilder qb = createTestQueryBuilder();
try {
qb.field("");
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("supplied field is null or empty."));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field(""));
assertEquals("supplied field is null or empty", e.getMessage());
}
public void testFieldCannotBeEmptyAndWeighted() {
SimpleQueryStringBuilder qb = createTestQueryBuilder();
try {
qb.field("", AbstractQueryBuilder.DEFAULT_BOOST);
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("supplied field is null or empty."));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> qb.field("", AbstractQueryBuilder.DEFAULT_BOOST));
assertEquals("supplied field is null or empty", e.getMessage());
}
/**
@ -223,12 +207,8 @@ public class SimpleQueryStringBuilderTests extends AbstractQueryTestCase<SimpleQ
* */
public void testFieldsCannotBeSetToNull() {
SimpleQueryStringBuilder qb = createTestQueryBuilder();
try {
qb.fields(null);
fail("Expected NullPointerException");
} catch (NullPointerException e) {
assertThat(e.getMessage(), is("fields cannot be null"));
}
NullPointerException e = expectThrows(NullPointerException.class, () -> qb.fields(null));
assertEquals("fields cannot be null", e.getMessage());
}
public void testDefaultFieldParsing() throws IOException {

View File

@ -40,19 +40,9 @@ public class SpanContainingQueryBuilderTests extends AbstractQueryTestCase<SpanC
}
public void testIllegalArguments() {
try {
new SpanContainingQueryBuilder(null, new SpanTermQueryBuilder("field", "value"));
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
try {
new SpanContainingQueryBuilder(new SpanTermQueryBuilder("field", "value"), null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
SpanTermQueryBuilder spanTermQuery = new SpanTermQueryBuilder("field", "value");
expectThrows(IllegalArgumentException.class, () -> new SpanContainingQueryBuilder(null, spanTermQuery));
expectThrows(IllegalArgumentException.class, () -> new SpanContainingQueryBuilder(spanTermQuery, null));
}
public void testFromJson() throws IOException {

View File

@ -56,12 +56,8 @@ public class SpanFirstQueryBuilderTests extends AbstractQueryTestCase<SpanFirstQ
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("missing [end] parameter should raise exception");
} catch (ParsingException e) {
assertTrue(e.getMessage().contains("spanFirst must have [end] set"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(builder.string()));
assertTrue(e.getMessage().contains("spanFirst must have [end] set"));
}
{
XContentBuilder builder = XContentFactory.jsonBuilder();
@ -71,12 +67,8 @@ public class SpanFirstQueryBuilderTests extends AbstractQueryTestCase<SpanFirstQ
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("missing [match] parameter should raise exception");
} catch (ParsingException e) {
assertTrue(e.getMessage().contains("spanFirst must have [match] span query clause"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(builder.string()));
assertTrue(e.getMessage().contains("spanFirst must have [match] span query clause"));
}
}

View File

@ -29,6 +29,7 @@ import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
@ -72,15 +73,14 @@ public class SpanMultiTermQueryBuilderTests extends AbstractQueryTestCase<SpanMu
public void testUnsupportedInnerQueryType() throws IOException {
QueryShardContext context = createShardContext();
// test makes only sense if we have at least one type registered with date field mapping
if (getCurrentTypes().length > 0 && context.fieldMapper(DATE_FIELD_NAME) != null) {
try {
RangeQueryBuilder query = new RangeQueryBuilder(DATE_FIELD_NAME);
new SpanMultiTermQueryBuilder(query).toQuery(createShardContext());
fail("Exception expected, range query on date fields should not generate a lucene " + MultiTermQuery.class.getName());
} catch (UnsupportedOperationException e) {
assert(e.getMessage().contains("unsupported inner query, should be " + MultiTermQuery.class.getName()));
}
}
assumeTrue("test runs only if there is a registered type",
getCurrentTypes().length > 0 && context.fieldMapper(DATE_FIELD_NAME) != null);
RangeQueryBuilder query = new RangeQueryBuilder(DATE_FIELD_NAME);
SpanMultiTermQueryBuilder spamMultiTermQuery = new SpanMultiTermQueryBuilder(query);
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class,
() -> spamMultiTermQuery.toQuery(createShardContext()));
assertThat(e.getMessage(), containsString("unsupported inner query, should be " + MultiTermQuery.class.getName()));
}
public void testToQueryInnerSpanMultiTerm() throws IOException {

View File

@ -62,18 +62,9 @@ public class SpanNotQueryBuilderTests extends AbstractQueryTestCase<SpanNotQuery
}
public void testIllegalArgument() {
try {
new SpanNotQueryBuilder(null, new SpanTermQueryBuilder("field", "value"));
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
try {
new SpanNotQueryBuilder(new SpanTermQueryBuilder("field", "value"), null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
SpanTermQueryBuilder spanTermQuery = new SpanTermQueryBuilder("field", "value");
expectThrows(IllegalArgumentException.class, () -> new SpanNotQueryBuilder(null, spanTermQuery));
expectThrows(IllegalArgumentException.class, () -> new SpanNotQueryBuilder(spanTermQuery, null));
}
public void testDist() {
@ -136,12 +127,8 @@ public class SpanNotQueryBuilderTests extends AbstractQueryTestCase<SpanNotQuery
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("ParsingException should have been caught");
} catch (ParsingException e) {
assertThat("ParsingException should have been caught", e.getDetailedMessage(), containsString("spanNot must have [include]"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(builder.string()));
assertThat(e.getDetailedMessage(), containsString("spanNot must have [include]"));
}
{
XContentBuilder builder = XContentFactory.jsonBuilder();
@ -154,12 +141,8 @@ public class SpanNotQueryBuilderTests extends AbstractQueryTestCase<SpanNotQuery
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("ParsingException should have been caught");
} catch (ParsingException e) {
assertThat("ParsingException should have been caught", e.getDetailedMessage(), containsString("spanNot must have [exclude]"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(builder.string()));
assertThat(e.getDetailedMessage(), containsString("spanNot must have [exclude]"));
}
{
XContentBuilder builder = XContentFactory.jsonBuilder();
@ -175,12 +158,8 @@ public class SpanNotQueryBuilderTests extends AbstractQueryTestCase<SpanNotQuery
builder.endObject();
builder.endObject();
try {
parseQuery(builder.string());
fail("ParsingException should have been caught");
} catch (ParsingException e) {
assertThat("ParsingException should have been caught", e.getDetailedMessage(), containsString("spanNot can either use [dist] or [pre] & [post] (or none)"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(builder.string()));
assertThat(e.getDetailedMessage(), containsString("spanNot can either use [dist] or [pre] & [post] (or none)"));
}
}

View File

@ -23,6 +23,7 @@ import org.apache.lucene.index.Term;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.spans.SpanTermQuery;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.index.mapper.MappedFieldType;
@ -99,13 +100,26 @@ public class SpanTermQueryBuilderTests extends AbstractTermQueryTestCase<SpanTer
}
public void testFromJson() throws IOException {
String json =
"{ \"span_term\" : { \"user\" : { \"value\" : \"kimchy\", \"boost\" : 2.0 } }} ";
String json = "{ \"span_term\" : { \"user\" : { \"value\" : \"kimchy\", \"boost\" : 2.0 } }}";
SpanTermQueryBuilder parsed = (SpanTermQueryBuilder) parseQuery(json);
checkGeneratedJson(json, parsed);
assertEquals(json, "kimchy", parsed.value());
assertEquals(json, 2.0, parsed.boost(), 0.0001);
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"span_term\" : {\n" +
" \"message1\" : {\n" +
" \"term\" : \"this\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"term\" : \"this\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[span_term] query doesn't support multiple fields, found [message1] and [message2]", e.getMessage());
}
}

View File

@ -40,19 +40,9 @@ public class SpanWithinQueryBuilderTests extends AbstractQueryTestCase<SpanWithi
}
public void testIllegalArguments() {
try {
new SpanWithinQueryBuilder(null, new SpanTermQueryBuilder("field", "value"));
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
try {
new SpanWithinQueryBuilder(new SpanTermQueryBuilder("field", "value"), null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
SpanTermQueryBuilder spanTermQuery = new SpanTermQueryBuilder("field", "value");
expectThrows(IllegalArgumentException.class, () -> new SpanWithinQueryBuilder(null, spanTermQuery));
expectThrows(IllegalArgumentException.class, () -> new SpanWithinQueryBuilder(spanTermQuery, null));
}
public void testFromJson() throws IOException {

View File

@ -19,6 +19,7 @@
package org.elasticsearch.index.query;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.PointRangeQuery;
import org.apache.lucene.search.Query;
@ -27,14 +28,11 @@ import org.elasticsearch.common.ParsingException;
import org.elasticsearch.common.lucene.BytesRefs;
import org.elasticsearch.index.mapper.MappedFieldType;
import com.fasterxml.jackson.core.io.JsonStringEncoder;
import java.io.IOException;
import static org.hamcrest.Matchers.either;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.either;
public class TermQueryBuilderTests extends AbstractTermQueryTestCase<TermQueryBuilder> {
@ -115,12 +113,8 @@ public class TermQueryBuilderTests extends AbstractTermQueryTestCase<TermQueryBu
" \"age\": [34, 35]\n" +
" }\n" +
"}";
try {
parseQuery(queryAsString);
fail("Expected ParsingException");
} catch (ParsingException e) {
assertThat(e.getMessage(), is("[term] query does not support array of values"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryAsString));
assertEquals("[term] query does not support array of values", e.getMessage());
}
public void testFromJson() throws IOException {
@ -136,7 +130,6 @@ public class TermQueryBuilderTests extends AbstractTermQueryTestCase<TermQueryBu
TermQueryBuilder parsed = (TermQueryBuilder) parseQuery(json);
checkGeneratedJson(json, parsed);
assertEquals(json, "Quick Foxes!", parsed.value());
}
@ -144,9 +137,23 @@ public class TermQueryBuilderTests extends AbstractTermQueryTestCase<TermQueryBu
assumeTrue("test runs only when at least a type is registered", getCurrentTypes().length > 0);
TermQueryBuilder query = new TermQueryBuilder(GEO_POINT_FIELD_NAME, "2,3");
QueryShardContext context = createShardContext();
QueryShardException e = expectThrows(QueryShardException.class,
() -> query.toQuery(context));
QueryShardException e = expectThrows(QueryShardException.class, () -> query.toQuery(context));
assertEquals("Geo fields do not support exact searching, use dedicated geo queries instead: [mapped_geo_point]",
e.getMessage());
}
public void testParseFailsWithMultipleFields() throws IOException {
String json = "{\n" +
" \"term\" : {\n" +
" \"message1\" : {\n" +
" \"value\" : \"this\"\n" +
" },\n" +
" \"message2\" : {\n" +
" \"value\" : \"this\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[term] query does not support different field names, use [bool] query instead", e.getMessage());
}
}

View File

@ -37,7 +37,6 @@ import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.index.get.GetResult;
import org.elasticsearch.indices.TermsLookup;
import org.elasticsearch.test.AbstractQueryTestCase;
import org.hamcrest.Matchers;
import org.junit.Before;
import java.io.IOException;
@ -49,7 +48,6 @@ import java.util.stream.Collectors;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
import static org.hamcrest.Matchers.is;
public class TermsQueryBuilderTests extends AbstractQueryTestCase<TermsQueryBuilder> {
private List<Object> randomTerms;
@ -146,56 +144,32 @@ public class TermsQueryBuilderTests extends AbstractQueryTestCase<TermsQueryBuil
}
public void testEmtpyFieldName() {
try {
if (randomBoolean()) {
new TermsQueryBuilder(null, "term");
} else {
new TermsQueryBuilder("", "term");
}
fail("Expected IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), is("field name cannot be null."));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder(null, "term"));
assertEquals("field name cannot be null.", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("", "term"));
assertEquals("field name cannot be null.", e.getMessage());
}
public void testEmtpyTermsLookup() {
try {
new TermsQueryBuilder("field", (TermsLookup) null);
fail("Expected IllegalArgumentException");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), is("No value or termsLookup specified for terms query"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (TermsLookup) null));
assertEquals("No value or termsLookup specified for terms query", e.getMessage());
}
public void testNullValues() {
try {
switch (randomInt(6)) {
case 0:
new TermsQueryBuilder("field", (String[]) null);
break;
case 1:
new TermsQueryBuilder("field", (int[]) null);
break;
case 2:
new TermsQueryBuilder("field", (long[]) null);
break;
case 3:
new TermsQueryBuilder("field", (float[]) null);
break;
case 4:
new TermsQueryBuilder("field", (double[]) null);
break;
case 5:
new TermsQueryBuilder("field", (Object[]) null);
break;
default:
new TermsQueryBuilder("field", (Iterable<?>) null);
break;
}
fail("should have failed with IllegalArgumentException");
} catch (IllegalArgumentException e) {
assertThat(e.getMessage(), Matchers.containsString("No value specified for terms query"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (String[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (int[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (long[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (float[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (double[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (Object[]) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
e = expectThrows(IllegalArgumentException.class, () -> new TermsQueryBuilder("field", (Iterable<?>) null));
assertThat(e.getMessage(), containsString("No value specified for terms query"));
}
public void testBothValuesAndLookupSet() throws IOException {
@ -213,12 +187,9 @@ public class TermsQueryBuilderTests extends AbstractQueryTestCase<TermsQueryBuil
" }\n" +
" }\n" +
"}";
try {
parseQuery(query);
fail("Expected ParsingException");
} catch(ParsingException e) {
assertThat(e.getMessage(), containsString("[" + TermsQueryBuilder.NAME + "] query does not support more than one field."));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(query));
assertThat(e.getMessage(), containsString("[" + TermsQueryBuilder.NAME + "] query does not support more than one field."));
}
@Override
@ -267,12 +238,8 @@ public class TermsQueryBuilderTests extends AbstractQueryTestCase<TermsQueryBuil
String query = XContentFactory.jsonBuilder().startObject()
.startObject("terms").array("foo", 123).array("bar", 456).endObject()
.endObject().string();
try {
parseQuery(query);
fail("parsing should have failed");
} catch (ParsingException ex) {
assertThat(ex.getMessage(), equalTo("[" + TermsQueryBuilder.NAME + "] query does not support multiple fields"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(query));
assertEquals("[" + TermsQueryBuilder.NAME + "] query does not support multiple fields", e.getMessage());
}
public void testFromJson() throws IOException {
@ -288,7 +255,7 @@ public class TermsQueryBuilderTests extends AbstractQueryTestCase<TermsQueryBuil
checkGeneratedJson(json, parsed);
assertEquals(json, 2, parsed.values().size());
json =
String deprecatedJson =
"{\n" +
" \"in\" : {\n" +
" \"user\" : [ \"kimchy\", \"elasticsearch\" ],\n" +
@ -298,23 +265,16 @@ public class TermsQueryBuilderTests extends AbstractQueryTestCase<TermsQueryBuil
QueryBuilder inShortcutParsed = parseQuery(json, ParseFieldMatcher.EMPTY);
assertThat(inShortcutParsed, equalTo(parsed));
try {
parseQuery(json);
fail("parse query should have failed in strict mode");
} catch(IllegalArgumentException e) {
assertThat(e.getMessage(), equalTo("Deprecated field [in] used, expected [terms] instead"));
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> parseQuery(deprecatedJson));
assertEquals("Deprecated field [in] used, expected [terms] instead", e.getMessage());
}
@Override
public void testMustRewrite() throws IOException {
TermsQueryBuilder termsQueryBuilder = new TermsQueryBuilder(STRING_FIELD_NAME, randomTermsLookup());
try {
termsQueryBuilder.toQuery(createShardContext());
fail();
} catch (UnsupportedOperationException ex) {
assertEquals("query must be rewritten first", ex.getMessage());
}
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class,
() -> termsQueryBuilder.toQuery(createShardContext()));
assertEquals("query must be rewritten first", e.getMessage());
assertEquals(termsQueryBuilder.rewrite(createShardContext()), new TermsQueryBuilder(STRING_FIELD_NAME,
randomTerms.stream().filter(x -> x != null).collect(Collectors.toList()))); // terms lookup removes null values
}

View File

@ -44,12 +44,7 @@ public class TypeQueryBuilderTests extends AbstractQueryTestCase<TypeQueryBuilde
}
public void testIllegalArgument() {
try {
new TypeQueryBuilder((String) null);
fail("cannot be null");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> new TypeQueryBuilder((String) null));
}
public void testFromJson() throws IOException {

View File

@ -21,9 +21,12 @@ package org.elasticsearch.index.query;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.WildcardQuery;
import org.elasticsearch.common.ParsingException;
import org.elasticsearch.test.AbstractQueryTestCase;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.instanceOf;
@ -32,21 +35,36 @@ public class WildcardQueryBuilderTests extends AbstractQueryTestCase<WildcardQue
@Override
protected WildcardQueryBuilder doCreateTestQueryBuilder() {
WildcardQueryBuilder query;
// mapped or unmapped field
String text = randomAsciiOfLengthBetween(1, 10);
if (randomBoolean()) {
query = new WildcardQueryBuilder(STRING_FIELD_NAME, text);
} else {
query = new WildcardQueryBuilder(randomAsciiOfLengthBetween(1, 10), text);
}
WildcardQueryBuilder query = randomWildcardQuery();
if (randomBoolean()) {
query.rewrite(randomFrom(getRandomRewriteMethod()));
}
return query;
}
@Override
protected Map<String, WildcardQueryBuilder> getAlternateVersions() {
Map<String, WildcardQueryBuilder> alternateVersions = new HashMap<>();
WildcardQueryBuilder wildcardQuery = randomWildcardQuery();
String contentString = "{\n" +
" \"wildcard\" : {\n" +
" \"" + wildcardQuery.fieldName() + "\" : \"" + wildcardQuery.value() + "\"\n" +
" }\n" +
"}";
alternateVersions.put(contentString, wildcardQuery);
return alternateVersions;
}
private static WildcardQueryBuilder randomWildcardQuery() {
// mapped or unmapped field
String text = randomAsciiOfLengthBetween(1, 10);
if (randomBoolean()) {
return new WildcardQueryBuilder(STRING_FIELD_NAME, text);
} else {
return new WildcardQueryBuilder(randomAsciiOfLengthBetween(1, 10), text);
}
}
@Override
protected void doAssertLuceneQuery(WildcardQueryBuilder queryBuilder, Query query, QueryShardContext context) throws IOException {
assertThat(query, instanceOf(WildcardQuery.class));
@ -57,41 +75,43 @@ public class WildcardQueryBuilderTests extends AbstractQueryTestCase<WildcardQue
}
public void testIllegalArguments() {
try {
if (randomBoolean()) {
new WildcardQueryBuilder(null, "text");
} else {
new WildcardQueryBuilder("", "text");
}
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
IllegalArgumentException e = expectThrows(IllegalArgumentException.class, () -> new WildcardQueryBuilder(null, "text"));
assertEquals("field name is null or empty", e.getMessage());
e = expectThrows(IllegalArgumentException.class, () -> new WildcardQueryBuilder("", "text"));
assertEquals("field name is null or empty", e.getMessage());
try {
new WildcardQueryBuilder("field", null);
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
e = expectThrows(IllegalArgumentException.class, () -> new WildcardQueryBuilder("field", null));
assertEquals("value cannot be null", e.getMessage());
}
public void testEmptyValue() throws IOException {
QueryShardContext context = createShardContext();
context.setAllowUnmappedFields(true);
WildcardQueryBuilder wildcardQueryBuilder = new WildcardQueryBuilder(getRandomType(), "");
assertEquals(wildcardQueryBuilder.toQuery(context).getClass(), WildcardQuery.class);
}
public void testFromJson() throws IOException {
String json =
"{ \"wildcard\" : { \"user\" : { \"wildcard\" : \"ki*y\", \"boost\" : 2.0 } }}";
String json = "{ \"wildcard\" : { \"user\" : { \"wildcard\" : \"ki*y\", \"boost\" : 2.0 } }}";
WildcardQueryBuilder parsed = (WildcardQueryBuilder) parseQuery(json);
checkGeneratedJson(json, parsed);
assertEquals(json, "ki*y", parsed.value());
assertEquals(json, 2.0, parsed.boost(), 0.0001);
}
public void testParseFailsWithMultipleFields() throws IOException {
String json =
"{\n" +
" \"wildcard\": {\n" +
" \"user1\": {\n" +
" \"wildcard\": \"ki*y\"\n" +
" },\n" +
" \"user2\": {\n" +
" \"wildcard\": \"ki*y\"\n" +
" }\n" +
" }\n" +
"}";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertEquals("[wildcard] query doesn't support multiple fields, found [user1] and [user2]", e.getMessage());
}
}

View File

@ -61,38 +61,12 @@ public class WrapperQueryBuilderTests extends AbstractQueryTestCase<WrapperQuery
}
public void testIllegalArgument() {
try {
if (randomBoolean()) {
new WrapperQueryBuilder((byte[]) null);
} else {
new WrapperQueryBuilder(new byte[0]);
}
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
try {
if (randomBoolean()) {
new WrapperQueryBuilder((String) null);
} else {
new WrapperQueryBuilder("");
}
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
try {
if (randomBoolean()) {
new WrapperQueryBuilder((BytesReference) null);
} else {
new WrapperQueryBuilder(new BytesArray(new byte[0]));
}
fail("cannot be null or empty");
} catch (IllegalArgumentException e) {
// expected
}
expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder((byte[]) null));
expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder(new byte[0]));
expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder((String) null));
expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder(""));
expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder((BytesReference) null));
expectThrows(IllegalArgumentException.class, () -> new WrapperQueryBuilder(new BytesArray(new byte[0])));
}
/**
@ -102,12 +76,9 @@ public class WrapperQueryBuilderTests extends AbstractQueryTestCase<WrapperQuery
*/
@Override
public void testUnknownField() throws IOException {
try {
parseQuery("{ \"" + WrapperQueryBuilder.NAME + "\" : {\"bogusField\" : \"someValue\"} }");
fail("ParsingException expected.");
} catch (ParsingException e) {
assertTrue(e.getMessage().contains("bogusField"));
}
String json = "{ \"" + WrapperQueryBuilder.NAME + "\" : {\"bogusField\" : \"someValue\"} }";
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(json));
assertTrue(e.getMessage().contains("bogusField"));
}
public void testFromJson() throws IOException {
@ -133,12 +104,8 @@ public class WrapperQueryBuilderTests extends AbstractQueryTestCase<WrapperQuery
public void testMustRewrite() throws IOException {
TermQueryBuilder tqb = new TermQueryBuilder("foo", "bar");
WrapperQueryBuilder qb = new WrapperQueryBuilder(tqb.toString());
try {
qb.toQuery(createShardContext());
fail();
} catch (UnsupportedOperationException e) {
assertEquals("this query must be rewritten first", e.getMessage());
}
UnsupportedOperationException e = expectThrows(UnsupportedOperationException.class, () -> qb.toQuery(createShardContext()));
assertEquals("this query must be rewritten first", e.getMessage());
QueryBuilder rewrite = qb.rewrite(createShardContext());
assertEquals(tqb, rewrite);
}

View File

@ -414,12 +414,8 @@ public class FunctionScoreQueryBuilderTests extends AbstractQueryTestCase<Functi
" \"weight\": 2\n" +
" }\n" +
"}";
try {
parseQuery(functionScoreQuery);
fail("parsing should have failed");
} catch (ParsingException e) {
assertThat(e.getMessage(), containsString("use [functions] array if you want to define several functions."));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(functionScoreQuery));
assertThat(e.getMessage(), containsString("use [functions] array if you want to define several functions."));
}
public void testProperErrorMessageWhenTwoFunctionsDefinedInFunctionsArray() throws IOException {

View File

@ -281,13 +281,9 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
} while (testQuery.toString().contains(marker));
testQuery.queryName(marker); // to find root query to add additional bogus field there
String queryAsString = testQuery.toString().replace("\"" + marker + "\"", "\"" + marker + "\", \"bogusField\" : \"someValue\"");
try {
parseQuery(queryAsString);
fail("ParsingException expected.");
} catch (ParsingException e) {
// we'd like to see the offending field name here
assertThat(e.getMessage(), containsString("bogusField"));
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(queryAsString));
// we'd like to see the offending field name here
assertThat(e.getMessage(), containsString("bogusField"));
}
/**
@ -344,12 +340,8 @@ public abstract class AbstractQueryTestCase<QB extends AbstractQueryBuilder<QB>>
validQuery.substring(insertionPosition, endArrayPosition) + "]" +
validQuery.substring(endArrayPosition, validQuery.length());
try {
parseQuery(testQuery);
fail("some parsing exception expected for query: " + testQuery);
} catch (ParsingException e) {
assertEquals("[" + queryName + "] query malformed, no start_object after query name", e.getMessage());
}
ParsingException e = expectThrows(ParsingException.class, () -> parseQuery(testQuery));
assertEquals("[" + queryName + "] query malformed, no start_object after query name", e.getMessage());
}
/**