org.elasticsearch.action.support.QuerySourceBuilder Java Examples

The following examples show how to use org.elasticsearch.action.support.QuerySourceBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RestActions.java    From Elasticsearch with Apache License 2.0 8 votes vote down vote up
public static QuerySourceBuilder parseQuerySource(RestRequest request) {
    String queryString = request.param("q");
    if (queryString == null) {
        return null;
    }
    QueryStringQueryBuilder queryBuilder = QueryBuilders.queryStringQuery(queryString);
    queryBuilder.defaultField(request.param("df"));
    queryBuilder.analyzer(request.param("analyzer"));
    queryBuilder.analyzeWildcard(request.paramAsBoolean("analyze_wildcard", false));
    queryBuilder.lowercaseExpandedTerms(request.paramAsBoolean("lowercase_expanded_terms", true));
    queryBuilder.lenient(request.paramAsBoolean("lenient", null));
    String defaultOperator = request.param("default_operator");
    if (defaultOperator != null) {
        if ("OR".equals(defaultOperator)) {
            queryBuilder.defaultOperator(QueryStringQueryBuilder.Operator.OR);
        } else if ("AND".equals(defaultOperator)) {
            queryBuilder.defaultOperator(QueryStringQueryBuilder.Operator.AND);
        } else {
            throw new IllegalArgumentException("Unsupported defaultOperator [" + defaultOperator + "], can either be [OR] or [AND]");
        }
    }
    return new QuerySourceBuilder().setQuery(queryBuilder);
}
 
Example #2
Source File: RestCountAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void doRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    CountRequest countRequest = new CountRequest(indices);
    String source = request.param("source");
    if (source != null) {
        countRequest.source(source);
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            countRequest.source(querySourceBuilder);
        }
    }

    client.search(countRequest.toSearchRequest(), new RestResponseListener<SearchResponse>(channel) {
        @Override
        public RestResponse buildResponse(SearchResponse countResponse) throws Exception {
            return RestTable.buildResponse(buildTable(request, countResponse), channel);
        }
    });
}
 
Example #3
Source File: SearchSourceBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a new search source builder with a raw search query.
 */
public SearchSourceBuilder query(BytesReference queryBinary) {
    if (this.querySourceBuilder == null) {
        this.querySourceBuilder = new QuerySourceBuilder();
    }
    this.querySourceBuilder.setQuery(queryBinary);
    return this;
}
 
Example #4
Source File: RestExistsAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    final ExistsRequest existsRequest = new ExistsRequest(Strings.splitStringByCommaToArray(request.param("index")));
    existsRequest.indicesOptions(IndicesOptions.fromRequest(request, existsRequest.indicesOptions()));
    if (RestActions.hasBodyContent(request)) {
        existsRequest.source(RestActions.getRestContent(request));
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            existsRequest.source(querySourceBuilder);
        }
    }
    existsRequest.routing(request.param("routing"));
    existsRequest.minScore(request.paramAsFloat("min_score", DEFAULT_MIN_SCORE));
    existsRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    existsRequest.preference(request.param("preference"));

    client.exists(existsRequest, new RestBuilderListener<ExistsResponse>(channel) {
        @Override
        public RestResponse buildResponse(ExistsResponse response, XContentBuilder builder) throws Exception {
            RestStatus status = response.exists() ? OK : NOT_FOUND;
            builder.startObject();
            builder.field("exists", response.exists());
            builder.endObject();
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example #5
Source File: RestCountAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    CountRequest countRequest = new CountRequest(Strings.splitStringByCommaToArray(request.param("index")));
    countRequest.indicesOptions(IndicesOptions.fromRequest(request, countRequest.indicesOptions()));
    if (RestActions.hasBodyContent(request)) {
        countRequest.source(RestActions.getRestContent(request));
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            countRequest.source(querySourceBuilder);
        }
    }
    countRequest.routing(request.param("routing"));
    countRequest.minScore(request.paramAsFloat("min_score", DEFAULT_MIN_SCORE));
    countRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    countRequest.preference(request.param("preference"));

    final int terminateAfter = request.paramAsInt("terminate_after", DEFAULT_TERMINATE_AFTER);
    if (terminateAfter < 0) {
        throw new IllegalArgumentException("terminateAfter must be > 0");
    } else if (terminateAfter > 0) {
        countRequest.terminateAfter(terminateAfter);
    }
    client.search(countRequest.toSearchRequest(), new RestBuilderListener<SearchResponse>(channel) {
        @Override
        public RestResponse buildResponse(SearchResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            if (terminateAfter != DEFAULT_TERMINATE_AFTER) {
                builder.field("terminated_early", response.isTerminatedEarly());
            }
            builder.field("count", response.getHits().totalHits());
            buildBroadcastShardsHeader(builder, request, response.getTotalShards(), response.getSuccessfulShards(),
                    response.getFailedShards(), response.getShardFailures());

            builder.endObject();
            return new BytesRestResponse(response.status(), builder);
        }
    });
}
 
Example #6
Source File: CountRequestBuilder.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public String toString() {
    if (sourceBuilder != null) {
        return sourceBuilder.toString();
    }
    if (request.source() != null) {
        try {
            return XContentHelper.convertToJson(request.source().toBytesArray(), false, true);
        } catch (Exception e) {
            return "{ \"error\" : \"" + ExceptionsHelper.detailedMessage(e) + "\"}";
        }
    }
    return new QuerySourceBuilder().toString();
}
 
Example #7
Source File: QuestionElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This is a new search that accepts additionalSearchInformation. We need it for our complex question searches.
 * We have duplicated the methods that need this parameter, like prepareSearchRequest
 */
public SearchResponse search(String searchTerms, List<String> references, List<String> siteIds, int start, int end, Map<String,String> additionalSearchInformation) {
    final Pair<SearchRequestBuilder,QueryBuilder> searchBuilders = prepareSearchRequest(searchTerms, references, siteIds, start, end, additionalSearchInformation);
    final SearchRequestBuilder searchRequestBuilder = searchBuilders.getLeft();
    final QueryBuilder queryBuilder = searchBuilders.getRight();

    getLog().debug("Search request from index builder [" + getName() + "]: " + searchRequestBuilder.toString());

    ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(indexName);
    QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder().setQuery(queryBuilder);
    validateQueryRequest.source(querySourceBuilder);
    validateQueryRequest.explain(true);


    try {
        ActionFuture<ValidateQueryResponse> future = client.admin().indices().validateQuery(validateQueryRequest); // the client is org.elasticsearch.client.Client
        ValidateQueryResponse responseV = future.get(); // typical java future as response

        if (responseV.isValid()) {
            SearchResponse response = searchRequestBuilder.execute().actionGet();
            getLog().debug("Search request from index builder [" + getName() + "] took: " + response.getTook().format());
            eventTrackingService.post(eventTrackingService.newEvent(SearchService.EVENT_SEARCH,
                    SearchService.EVENT_SEARCH_REF + queryBuilder.toString(), true,
                    NotificationService.PREF_IMMEDIATE));

            return response;
        }else{
            return null;
        }
    }catch(Exception ex){
        return null;
    }

}
 
Example #8
Source File: QuestionElasticSearchIndexBuilder.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
/**
 * This is a new search that accepts additionalSearchInformation. We need it for our complex question searches.
 * We have duplicated the methods that need this parameter, like prepareSearchRequest
 */
public SearchResponse search(String searchTerms, List<String> references, List<String> siteIds, int start, int end, Map<String,String> additionalSearchInformation) {
    final Pair<SearchRequestBuilder,QueryBuilder> searchBuilders = prepareSearchRequest(searchTerms, references, siteIds, start, end, additionalSearchInformation);
    final SearchRequestBuilder searchRequestBuilder = searchBuilders.getLeft();
    final QueryBuilder queryBuilder = searchBuilders.getRight();

    getLog().debug("Search request from index builder [" + getName() + "]: " + searchRequestBuilder.toString());

    ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(indexName);
    QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder().setQuery(queryBuilder);
    validateQueryRequest.source(querySourceBuilder);
    validateQueryRequest.explain(true);


    try {
        ActionFuture<ValidateQueryResponse> future = client.admin().indices().validateQuery(validateQueryRequest); // the client is org.elasticsearch.client.Client
        ValidateQueryResponse responseV = future.get(); // typical java future as response

        if (responseV.isValid()) {
            SearchResponse response = searchRequestBuilder.execute().actionGet();
            getLog().debug("Search request from index builder [" + getName() + "] took: " + response.getTook().format());
            eventTrackingService.post(eventTrackingService.newEvent(SearchService.EVENT_SEARCH,
                    SearchService.EVENT_SEARCH_REF + queryBuilder.toString(), true,
                    NotificationService.PREF_IMMEDIATE));

            return response;
        }else{
            return null;
        }
    }catch(Exception ex){
        return null;
    }

}
 
Example #9
Source File: SearchSourceBuilder.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * Sets the query provided as a {@link QuerySourceBuilder}
 */
public SearchSourceBuilder query(QuerySourceBuilder querySourceBuilder) {
    this.querySourceBuilder = querySourceBuilder;
    return this;
}
 
Example #10
Source File: RestValidateQueryAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    ValidateQueryRequest validateQueryRequest = new ValidateQueryRequest(Strings.splitStringByCommaToArray(request.param("index")));
    validateQueryRequest.indicesOptions(IndicesOptions.fromRequest(request, validateQueryRequest.indicesOptions()));
    if (RestActions.hasBodyContent(request)) {
        validateQueryRequest.source(RestActions.getRestContent(request));
    } else {
        QuerySourceBuilder querySourceBuilder = RestActions.parseQuerySource(request);
        if (querySourceBuilder != null) {
            validateQueryRequest.source(querySourceBuilder);
        }
    }
    validateQueryRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    if (request.paramAsBoolean("explain", false)) {
        validateQueryRequest.explain(true);
    } else {
        validateQueryRequest.explain(false);
    }
    if (request.paramAsBoolean("rewrite", false)) {
        validateQueryRequest.rewrite(true);
    } else {
        validateQueryRequest.rewrite(false);
    }

    client.admin().indices().validateQuery(validateQueryRequest, new RestBuilderListener<ValidateQueryResponse>(channel) {
        @Override
        public RestResponse buildResponse(ValidateQueryResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            builder.field("valid", response.isValid());

            buildBroadcastShardsHeader(builder, request, response);

            if (response.getQueryExplanation() != null && !response.getQueryExplanation().isEmpty()) {
                builder.startArray("explanations");
                for (QueryExplanation explanation : response.getQueryExplanation()) {
                    builder.startObject();
                    if (explanation.getIndex() != null) {
                        builder.field("index", explanation.getIndex(), XContentBuilder.FieldCaseConversion.NONE);
                    }
                    builder.field("valid", explanation.isValid());
                    if (explanation.getError() != null) {
                        builder.field("error", explanation.getError());
                    }
                    if (explanation.getExplanation() != null) {
                        builder.field("explanation", explanation.getExplanation());
                    }
                    builder.endObject();
                }
                builder.endArray();
            }
            builder.endObject();
            return new BytesRestResponse(OK, builder);
        }
    });
}
 
Example #11
Source File: ExistsRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * The source to execute.
 */
public ExistsRequest source(QuerySourceBuilder sourceBuilder) {
    this.source = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
    return this;
}
 
Example #12
Source File: CountRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
/**
 * The source to execute.
 */
public CountRequest source(QuerySourceBuilder sourceBuilder) {
    this.source = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
    return this;
}
 
Example #13
Source File: ValidateQueryRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ValidateQueryRequest source(QuerySourceBuilder sourceBuilder) {
    this.source = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
    return this;
}
 
Example #14
Source File: ExplainRequest.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public ExplainRequest source(QuerySourceBuilder sourceBuilder) {
    this.source = sourceBuilder.buildAsBytes(Requests.CONTENT_TYPE);
    return this;
}
 
Example #15
Source File: SimpleDeletingStrategy.java    From elasticsearch-river-neo4j with Apache License 2.0 4 votes vote down vote up
@Override
public DeleteByQueryRequest build(String index, String type, long currentVersion) {
    QuerySourceBuilder querySourceBuilder = new QuerySourceBuilder().setQuery(QueryBuilders.rangeQuery("version").to(currentVersion - 1));
    return new DeleteByQueryRequest(index).types(type).source(querySourceBuilder);
}