Java Code Examples for org.elasticsearch.rest.action.support.RestActions#hasBodyContent()

The following examples show how to use org.elasticsearch.rest.action.support.RestActions#hasBodyContent() . 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: RestClearScrollAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String scrollIds = request.param("scroll_id");
    ClearScrollRequest clearRequest = new ClearScrollRequest();
    clearRequest.setScrollIds(Arrays.asList(splitScrollIds(scrollIds)));
    if (RestActions.hasBodyContent(request)) {
        XContentType type = RestActions.guessBodyContentType(request);
       if (type == null) {
           scrollIds = RestActions.getRestContent(request).toUtf8();
           clearRequest.setScrollIds(Arrays.asList(splitScrollIds(scrollIds)));
       } else {
           // NOTE: if rest request with xcontent body has request parameters, these parameters does not override xcontent value
           clearRequest.setScrollIds(null);
           buildFromContent(RestActions.getRestContent(request), clearRequest);
       }
    }

    client.clearScroll(clearRequest, new RestStatusToXContentListener<ClearScrollResponse>(channel));
}
 
Example 2
Source File: RestSearchScrollAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) {
    String scrollId = request.param("scroll_id");
    SearchScrollRequest searchScrollRequest = new SearchScrollRequest();
    searchScrollRequest.scrollId(scrollId);
    String scroll = request.param("scroll");
    if (scroll != null) {
        searchScrollRequest.scroll(new Scroll(parseTimeValue(scroll, null, "scroll")));
    }

    if (RestActions.hasBodyContent(request)) {
        XContentType type = XContentFactory.xContentType(RestActions.getRestContent(request));
        if (type == null) {
            if (scrollId == null) {
                scrollId = RestActions.getRestContent(request).toUtf8();
                searchScrollRequest.scrollId(scrollId);
            }
        } else {
            // NOTE: if rest request with xcontent body has request parameters, these parameters override xcontent values
            buildFromContent(RestActions.getRestContent(request), searchScrollRequest);
        }
    }
    client.searchScroll(searchScrollRequest, new RestStatusToXContentListener<SearchResponse>(channel));
}
 
Example 3
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 4
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 5
Source File: RestAnalyzeAction.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) {

    String[] texts = request.paramAsStringArrayOrEmptyIfAll("text");

    AnalyzeRequest analyzeRequest = new AnalyzeRequest(request.param("index"));
    analyzeRequest.text(texts);
    analyzeRequest.analyzer(request.param("analyzer"));
    analyzeRequest.field(request.param("field"));
    analyzeRequest.tokenizer(request.param("tokenizer"));
    analyzeRequest.tokenFilters(request.paramAsStringArray("filter", request.paramAsStringArray("token_filter",
        request.paramAsStringArray("token_filters", request.paramAsStringArray("filters", analyzeRequest.tokenFilters())))));
    analyzeRequest.charFilters(request.paramAsStringArray("char_filter", request.paramAsStringArray("char_filters", analyzeRequest.charFilters())));
    analyzeRequest.explain(request.paramAsBoolean("explain", false));
    analyzeRequest.attributes(request.paramAsStringArray("attributes", analyzeRequest.attributes()));

    if (RestActions.hasBodyContent(request)) {
        XContentType type = RestActions.guessBodyContentType(request);
        if (type == null) {
            if (texts == null || texts.length == 0) {
                texts = new String[]{ RestActions.getRestContent(request).toUtf8() };
                analyzeRequest.text(texts);
            }
        } else {
            // NOTE: if rest request with xcontent body has request parameters, the parameters does not override xcontent values
            buildFromContent(RestActions.getRestContent(request), analyzeRequest, parseFieldMatcher);
        }
    }

    client.admin().indices().analyze(analyzeRequest, new RestToXContentListener<AnalyzeResponse>(channel));
}
 
Example 6
Source File: RestFieldStatsAction.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) throws Exception {
    if (RestActions.hasBodyContent(request) && request.hasParam("fields")) {
        throw new IllegalArgumentException("can't specify a request body and [fields] request parameter, either specify a request body or the [fields] request parameter");
    }

    final FieldStatsRequest fieldStatsRequest = new FieldStatsRequest();
    fieldStatsRequest.indices(Strings.splitStringByCommaToArray(request.param("index")));
    fieldStatsRequest.indicesOptions(IndicesOptions.fromRequest(request, fieldStatsRequest.indicesOptions()));
    fieldStatsRequest.level(request.param("level", FieldStatsRequest.DEFAULT_LEVEL));
    if (RestActions.hasBodyContent(request)) {
        fieldStatsRequest.source(RestActions.getRestContent(request));
    } else {
        fieldStatsRequest.setFields(Strings.splitStringByCommaToArray(request.param("fields")));
    }

    client.fieldStats(fieldStatsRequest, new RestBuilderListener<FieldStatsResponse>(channel) {
        @Override
        public RestResponse buildResponse(FieldStatsResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            buildBroadcastShardsHeader(builder, request, response);

            builder.startObject("indices");
            for (Map.Entry<String, Map<String, FieldStats>> entry1 : response.getIndicesMergedFieldStats().entrySet()) {
                builder.startObject(entry1.getKey());
                builder.startObject("fields");
                for (Map.Entry<String, FieldStats> entry2 : entry1.getValue().entrySet()) {
                    builder.field(entry2.getKey());
                    entry2.getValue().toXContent(builder, request);
                }
                builder.endObject();
                builder.endObject();
            }
            builder.endObject();
            return new BytesRestResponse(RestStatus.OK, builder);
        }
    });
}
 
Example 7
Source File: RestTermVectorsAction.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) throws Exception {
    TermVectorsRequest termVectorsRequest = new TermVectorsRequest(request.param("index"), request.param("type"), request.param("id"));
    if (RestActions.hasBodyContent(request)) {
        try (XContentParser parser = XContentFactory.xContent(RestActions.guessBodyContentType(request)).createParser(RestActions.getRestContent(request))){
            TermVectorsRequest.parseRequest(termVectorsRequest, parser);
        }
    }
    readURIParameters(termVectorsRequest, request);

    client.termVectors(termVectorsRequest, new RestToXContentListener<TermVectorsResponse>(channel));
}
 
Example 8
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 9
Source File: RestSearchAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
public static void parseSearchRequest(SearchRequest searchRequest, RestRequest request, ParseFieldMatcher parseFieldMatcher,
        BytesReference bodyContent) {
    searchRequest.indices(Strings.splitStringByCommaToArray(request.param("index")));
    // get the content, and put it in the body
    // add content/source as template if template flag is set
    boolean isTemplateRequest = request.path().endsWith("/template");
    if (bodyContent == null) {
        if (RestActions.hasBodyContent(request)) {
            bodyContent = RestActions.getRestContent(request);
        }
    }
    if (bodyContent != null) {
        if (isTemplateRequest) {
            searchRequest.templateSource(bodyContent);
        } else {
            searchRequest.source(bodyContent);
        }
    }

    // do not allow 'query_and_fetch' or 'dfs_query_and_fetch' search types
    // from the REST layer. these modes are an internal optimization and should
    // not be specified explicitly by the user.
    String searchType = request.param("search_type");
    if (SearchType.fromString(searchType, parseFieldMatcher).equals(SearchType.QUERY_AND_FETCH) ||
            SearchType.fromString(searchType, parseFieldMatcher).equals(SearchType.DFS_QUERY_AND_FETCH)) {
        throw new IllegalArgumentException("Unsupported search type [" + searchType + "]");
    } else {
        searchRequest.searchType(searchType);
    }

    searchRequest.extraSource(parseSearchSource(request));
    searchRequest.requestCache(request.paramAsBoolean("request_cache", null));

    String scroll = request.param("scroll");
    if (scroll != null) {
        searchRequest.scroll(new Scroll(parseTimeValue(scroll, null, "scroll")));
    }

    searchRequest.types(Strings.splitStringByCommaToArray(request.param("type")));
    searchRequest.routing(request.param("routing"));
    searchRequest.preference(request.param("preference"));
    searchRequest.indicesOptions(IndicesOptions.fromRequest(request, searchRequest.indicesOptions()));
}