use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.
the class GeoDistanceSortBuilder method fromXContent.
/**
* Creates a new {@link GeoDistanceSortBuilder} from the query held by the {@link QueryParseContext} in
* {@link org.elasticsearch.common.xcontent.XContent} format.
*
* @param context the input parse context. The state on the parser contained in this context will be changed as a
* side effect of this method call
* @param elementName in some sort syntax variations the field name precedes the xContent object that specifies
* further parameters, e.g. in '{ "foo": { "order" : "asc"} }'. When parsing the inner object,
* the field name can be passed in via this argument
*/
public static GeoDistanceSortBuilder fromXContent(QueryParseContext context, String elementName) throws IOException {
XContentParser parser = context.parser();
String fieldName = null;
List<GeoPoint> geoPoints = new ArrayList<>();
DistanceUnit unit = DistanceUnit.DEFAULT;
GeoDistance geoDistance = GeoDistance.ARC;
SortOrder order = SortOrder.ASC;
SortMode sortMode = null;
QueryBuilder nestedFilter = null;
String nestedPath = null;
GeoValidationMethod validation = null;
XContentParser.Token token;
String currentName = parser.currentName();
while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
if (token == XContentParser.Token.FIELD_NAME) {
currentName = parser.currentName();
} else if (token == XContentParser.Token.START_ARRAY) {
parseGeoPoints(parser, geoPoints);
fieldName = currentName;
} else if (token == XContentParser.Token.START_OBJECT) {
if (NESTED_FILTER_FIELD.match(currentName)) {
nestedFilter = context.parseInnerQueryBuilder();
} else {
// the json in the format of -> field : { lat : 30, lon : 12 }
if (fieldName != null && fieldName.equals(currentName) == false) {
throw new ParsingException(parser.getTokenLocation(), "Trying to reset fieldName to [{}], already set to [{}].", currentName, fieldName);
}
fieldName = currentName;
GeoPoint point = new GeoPoint();
GeoUtils.parseGeoPoint(parser, point);
geoPoints.add(point);
}
} else if (token.isValue()) {
if (ORDER_FIELD.match(currentName)) {
order = SortOrder.fromString(parser.text());
} else if (UNIT_FIELD.match(currentName)) {
unit = DistanceUnit.fromString(parser.text());
} else if (DISTANCE_TYPE_FIELD.match(currentName)) {
geoDistance = GeoDistance.fromString(parser.text());
} else if (VALIDATION_METHOD_FIELD.match(currentName)) {
validation = GeoValidationMethod.fromString(parser.text());
} else if (SORTMODE_FIELD.match(currentName)) {
sortMode = SortMode.fromString(parser.text());
} else if (NESTED_PATH_FIELD.match(currentName)) {
nestedPath = parser.text();
} else if (token == Token.VALUE_STRING) {
if (fieldName != null && fieldName.equals(currentName) == false) {
throw new ParsingException(parser.getTokenLocation(), "Trying to reset fieldName to [{}], already set to [{}].", currentName, fieldName);
}
GeoPoint point = new GeoPoint();
point.resetFromString(parser.text());
geoPoints.add(point);
fieldName = currentName;
} else if (fieldName.equals(currentName)) {
throw new ParsingException(parser.getTokenLocation(), "Only geohashes of type string supported for field [{}]", currentName);
} else {
throw new ParsingException(parser.getTokenLocation(), "[{}] does not support [{}]", NAME, currentName);
}
}
}
GeoDistanceSortBuilder result = new GeoDistanceSortBuilder(fieldName, geoPoints.toArray(new GeoPoint[geoPoints.size()]));
result.geoDistance(geoDistance);
result.unit(unit);
result.order(order);
if (sortMode != null) {
result.sortMode(sortMode);
}
if (nestedFilter != null) {
result.setNestedFilter(nestedFilter);
}
result.setNestedPath(nestedPath);
if (validation != null) {
result.validation(validation);
}
return result;
}
use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.
the class ShardSearchRequest method parseAliasFilter.
/**
* Returns the filter associated with listed filtering aliases.
* <p>
* The list of filtering aliases should be obtained by calling MetaData.filteringAliases.
* Returns <tt>null</tt> if no filtering is required.</p>
*/
static QueryBuilder parseAliasFilter(CheckedFunction<byte[], QueryBuilder, IOException> filterParser, IndexMetaData metaData, String... aliasNames) {
if (aliasNames == null || aliasNames.length == 0) {
return null;
}
Index index = metaData.getIndex();
ImmutableOpenMap<String, AliasMetaData> aliases = metaData.getAliases();
Function<AliasMetaData, QueryBuilder> parserFunction = (alias) -> {
if (alias.filter() == null) {
return null;
}
try {
return filterParser.apply(alias.filter().uncompressed());
} catch (IOException ex) {
throw new AliasFilterParsingException(index, alias.getAlias(), "Invalid alias filter", ex);
}
};
if (aliasNames.length == 1) {
AliasMetaData alias = aliases.get(aliasNames[0]);
if (alias == null) {
// This shouldn't happen unless alias disappeared after filteringAliases was called.
throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter");
}
return parserFunction.apply(alias);
} else {
// we need to bench here a bit, to see maybe it makes sense to use OrFilter
BoolQueryBuilder combined = new BoolQueryBuilder();
for (String aliasName : aliasNames) {
AliasMetaData alias = aliases.get(aliasName);
if (alias == null) {
// This shouldn't happen unless alias disappeared after filteringAliases was called.
throw new InvalidAliasNameException(index, aliasNames[0], "Unknown alias name was passed to alias Filter");
}
QueryBuilder parsedFilter = parserFunction.apply(alias);
if (parsedFilter != null) {
combined.should(parsedFilter);
} else {
// The filter might be null only if filter was removed after filteringAliases was called
return null;
}
}
return combined;
}
}
use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.
the class FunctionScoreQueryBuilder method parseFiltersAndFunctions.
private static String parseFiltersAndFunctions(QueryParseContext parseContext, List<FunctionScoreQueryBuilder.FilterFunctionBuilder> filterFunctionBuilders) throws IOException {
String currentFieldName = null;
XContentParser.Token token;
XContentParser parser = parseContext.parser();
while ((token = parser.nextToken()) != XContentParser.Token.END_ARRAY) {
QueryBuilder filter = null;
ScoreFunctionBuilder<?> scoreFunction = null;
Float functionWeight = null;
if (token != XContentParser.Token.START_OBJECT) {
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}]. malformed query, expected a [{}] while parsing functions but got a [{}] instead", XContentParser.Token.START_OBJECT, token, NAME);
} else {
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 (FILTER_FIELD.match(currentFieldName)) {
filter = parseContext.parseInnerQueryBuilder();
} else {
if (scoreFunction != null) {
throw new ParsingException(parser.getTokenLocation(), "failed to parse function_score functions. already found [{}], now encountering [{}].", scoreFunction.getName(), currentFieldName);
}
scoreFunction = parser.namedObject(ScoreFunctionBuilder.class, currentFieldName, parseContext);
}
} else if (token.isValue()) {
if (WEIGHT_FIELD.match(currentFieldName)) {
functionWeight = parser.floatValue();
} else {
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. field [{}] is not supported", NAME, currentFieldName);
}
}
}
if (functionWeight != null) {
if (scoreFunction == null) {
scoreFunction = new WeightBuilder().setWeight(functionWeight);
} else {
scoreFunction.setWeight(functionWeight);
}
}
}
if (filter == null) {
filter = new MatchAllQueryBuilder();
}
if (scoreFunction == null) {
throw new ParsingException(parser.getTokenLocation(), "failed to parse [{}] query. an entry in functions list is missing a function.", NAME);
}
filterFunctionBuilders.add(new FunctionScoreQueryBuilder.FilterFunctionBuilder(filter, scoreFunction));
}
return currentFieldName;
}
use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.
the class FunctionScoreQueryBuilder method doRewrite.
@Override
protected QueryBuilder doRewrite(QueryRewriteContext queryRewriteContext) throws IOException {
QueryBuilder queryBuilder = this.query.rewrite(queryRewriteContext);
FilterFunctionBuilder[] rewrittenBuilders = new FilterFunctionBuilder[this.filterFunctionBuilders.length];
boolean rewritten = false;
for (int i = 0; i < rewrittenBuilders.length; i++) {
FilterFunctionBuilder rewrite = filterFunctionBuilders[i].rewrite(queryRewriteContext);
rewritten |= rewrite != filterFunctionBuilders[i];
rewrittenBuilders[i] = rewrite;
}
if (queryBuilder != query || rewritten) {
FunctionScoreQueryBuilder newQueryBuilder = new FunctionScoreQueryBuilder(queryBuilder, rewrittenBuilders);
newQueryBuilder.scoreMode = scoreMode;
newQueryBuilder.minScore = minScore;
newQueryBuilder.maxBoost = maxBoost;
newQueryBuilder.boostMode = boostMode;
return newQueryBuilder;
}
return this;
}
use of org.elasticsearch.index.query.QueryBuilder in project elasticsearch by elastic.
the class RestCountAction method doCatRequest.
@Override
public RestChannelConsumer doCatRequest(final RestRequest request, final NodeClient client) {
String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
SearchRequest countRequest = new SearchRequest(indices);
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0);
countRequest.source(searchSourceBuilder);
try {
request.withContentOrSourceParamParserOrNull(parser -> {
if (parser == null) {
QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request);
if (queryBuilder != null) {
searchSourceBuilder.query(queryBuilder);
}
} else {
searchSourceBuilder.query(RestActions.getQueryContent(parser));
}
});
} catch (IOException e) {
throw new ElasticsearchException("Couldn't parse query", e);
}
return channel -> client.search(countRequest, new RestResponseListener<SearchResponse>(channel) {
@Override
public RestResponse buildResponse(SearchResponse countResponse) throws Exception {
return RestTable.buildResponse(buildTable(request, countResponse), channel);
}
});
}
Aggregations