Search in sources :

Example 1 with QueryBuilder

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;
}
Also used : GeoValidationMethod(org.elasticsearch.index.query.GeoValidationMethod) ArrayList(java.util.ArrayList) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) GeoPoint(org.elasticsearch.common.geo.GeoPoint) Token(org.elasticsearch.common.xcontent.XContentParser.Token) ParsingException(org.elasticsearch.common.ParsingException) GeoDistance(org.elasticsearch.common.geo.GeoDistance) DistanceUnit(org.elasticsearch.common.unit.DistanceUnit) XContentParser(org.elasticsearch.common.xcontent.XContentParser)

Example 2 with QueryBuilder

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;
    }
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) SearchType(org.elasticsearch.action.search.SearchType) ImmutableOpenMap(org.elasticsearch.common.collect.ImmutableOpenMap) QueryShardContext(org.elasticsearch.index.query.QueryShardContext) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) Scroll(org.elasticsearch.search.Scroll) IOException(java.io.IOException) Index(org.elasticsearch.index.Index) BytesReference(org.elasticsearch.common.bytes.BytesReference) Function(java.util.function.Function) CheckedFunction(org.elasticsearch.common.CheckedFunction) IndexMetaData(org.elasticsearch.cluster.metadata.IndexMetaData) AliasFilterParsingException(org.elasticsearch.indices.AliasFilterParsingException) InvalidAliasNameException(org.elasticsearch.indices.InvalidAliasNameException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) AliasMetaData(org.elasticsearch.cluster.metadata.AliasMetaData) AliasFilterParsingException(org.elasticsearch.indices.AliasFilterParsingException) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) Index(org.elasticsearch.index.Index) IOException(java.io.IOException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) InvalidAliasNameException(org.elasticsearch.indices.InvalidAliasNameException)

Example 3 with QueryBuilder

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;
}
Also used : ParsingException(org.elasticsearch.common.ParsingException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) AbstractQueryBuilder(org.elasticsearch.index.query.AbstractQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder) XContentParser(org.elasticsearch.common.xcontent.XContentParser) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 4 with QueryBuilder

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;
}
Also used : QueryBuilder(org.elasticsearch.index.query.QueryBuilder) AbstractQueryBuilder(org.elasticsearch.index.query.AbstractQueryBuilder) MatchAllQueryBuilder(org.elasticsearch.index.query.MatchAllQueryBuilder)

Example 5 with QueryBuilder

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);
        }
    });
}
Also used : ElasticsearchException(org.elasticsearch.ElasticsearchException) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestResponse(org.elasticsearch.rest.RestResponse) Table(org.elasticsearch.common.Table) IOException(java.io.IOException) SearchRequest(org.elasticsearch.action.search.SearchRequest) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) Settings(org.elasticsearch.common.settings.Settings) SearchResponse(org.elasticsearch.action.search.SearchResponse) RestRequest(org.elasticsearch.rest.RestRequest) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) NodeClient(org.elasticsearch.client.node.NodeClient) RestResponseListener(org.elasticsearch.rest.action.RestResponseListener) SearchRequest(org.elasticsearch.action.search.SearchRequest) RestResponse(org.elasticsearch.rest.RestResponse) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) ElasticsearchException(org.elasticsearch.ElasticsearchException) ElasticsearchException(org.elasticsearch.ElasticsearchException) IOException(java.io.IOException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Aggregations

QueryBuilder (org.elasticsearch.index.query.QueryBuilder)366 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)245 Test (org.testng.annotations.Test)156 DynamicEntity (org.molgenis.data.support.DynamicEntity)137 SearchResponse (org.elasticsearch.action.search.SearchResponse)57 QueryImpl (org.molgenis.data.support.QueryImpl)36 Map (java.util.Map)31 ArrayList (java.util.ArrayList)30 Test (org.junit.Test)30 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)28 MatchAllQueryBuilder (org.elasticsearch.index.query.MatchAllQueryBuilder)27 RangeQueryBuilder (org.elasticsearch.index.query.RangeQueryBuilder)27 HashMap (java.util.HashMap)26 IOException (java.io.IOException)22 SearchHit (org.elasticsearch.search.SearchHit)22 AbstractQueryBuilder (org.elasticsearch.index.query.AbstractQueryBuilder)19 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)17 List (java.util.List)16 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)15 MatchQueryBuilder (org.elasticsearch.index.query.MatchQueryBuilder)14