org.elasticsearch.rest.action.support.RestActions Java Examples

The following examples show how to use org.elasticsearch.rest.action.support.RestActions. 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: 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 #2
Source File: RestMultiGetAction.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) throws Exception {
    MultiGetRequest multiGetRequest = new MultiGetRequest();
    multiGetRequest.refresh(request.paramAsBoolean("refresh", multiGetRequest.refresh()));
    multiGetRequest.preference(request.param("preference"));
    multiGetRequest.realtime(request.paramAsBoolean("realtime", null));
    multiGetRequest.ignoreErrorsOnGeneratedFields(request.paramAsBoolean("ignore_errors_on_generated_fields", false));

    String[] sFields = null;
    String sField = request.param("fields");
    if (sField != null) {
        sFields = Strings.splitStringByCommaToArray(sField);
    }

    FetchSourceContext defaultFetchSource = FetchSourceContext.parseFromRestRequest(request);
    multiGetRequest.add(request.param("index"), request.param("type"), sFields, defaultFetchSource, request.param("routing"), RestActions.getRestContent(request), allowExplicitIndex);

    client.multiGet(multiGetRequest, new RestToXContentListener<MultiGetResponse>(channel));
}
 
Example #3
Source File: RestTermVectorsAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
static public void readURIParameters(TermVectorsRequest termVectorsRequest, RestRequest request) {
    String fields = request.param("fields");
    addFieldStringsFromParameter(termVectorsRequest, fields);
    termVectorsRequest.offsets(request.paramAsBoolean("offsets", termVectorsRequest.offsets()));
    termVectorsRequest.positions(request.paramAsBoolean("positions", termVectorsRequest.positions()));
    termVectorsRequest.payloads(request.paramAsBoolean("payloads", termVectorsRequest.payloads()));
    termVectorsRequest.routing(request.param("routing"));
    termVectorsRequest.realtime(request.paramAsBoolean("realtime", null));
    termVectorsRequest.version(RestActions.parseVersion(request, termVectorsRequest.version()));
    termVectorsRequest.versionType(VersionType.fromString(request.param("version_type"), termVectorsRequest.versionType()));
    termVectorsRequest.parent(request.param("parent"));
    termVectorsRequest.preference(request.param("preference"));
    termVectorsRequest.termStatistics(request.paramAsBoolean("termStatistics", termVectorsRequest.termStatistics()));
    termVectorsRequest.termStatistics(request.paramAsBoolean("term_statistics", termVectorsRequest.termStatistics()));
    termVectorsRequest.fieldStatistics(request.paramAsBoolean("fieldStatistics", termVectorsRequest.fieldStatistics()));
    termVectorsRequest.fieldStatistics(request.paramAsBoolean("field_statistics", termVectorsRequest.fieldStatistics()));
    termVectorsRequest.dfs(request.paramAsBoolean("dfs", termVectorsRequest.dfs()));
}
 
Example #4
Source File: RestPercolateAction.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
void parseExistingDocPercolate(PercolateRequest percolateRequest, RestRequest restRequest, RestChannel restChannel, final Client client) {
    String index = restRequest.param("index");
    String type = restRequest.param("type");
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("percolate_index", index)));
    percolateRequest.documentType(restRequest.param("percolate_type", type));

    GetRequest getRequest = new GetRequest(index, type,
            restRequest.param("id"));
    getRequest.routing(restRequest.param("routing"));
    getRequest.preference(restRequest.param("preference"));
    getRequest.refresh(restRequest.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.realtime(restRequest.paramAsBoolean("realtime", null));
    getRequest.version(RestActions.parseVersion(restRequest));
    getRequest.versionType(VersionType.fromString(restRequest.param("version_type"), getRequest.versionType()));

    percolateRequest.getRequest(getRequest);
    percolateRequest.routing(restRequest.param("percolate_routing"));
    percolateRequest.preference(restRequest.param("percolate_preference"));
    percolateRequest.source(RestActions.getRestContent(restRequest));

    percolateRequest.indicesOptions(IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    executePercolate(percolateRequest, restChannel, client);
}
 
Example #5
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 #6
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 #7
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 #8
Source File: RestExtendedAnalyzeAction.java    From elasticsearch-extended-analyze with Apache License 2.0 5 votes vote down vote up
public static XContentType guessBodyContentType(final RestRequest request) {
    final BytesReference restContent = RestActions.getRestContent(request);
    if (restContent == null) {
        return null;
    }
    return XContentFactory.xContentType(restContent);
}
 
Example #9
Source File: RestExtendedAnalyzeAction.java    From elasticsearch-extended-analyze 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[] text = request.paramAsStringArrayOrEmptyIfAll("text");

    ExtendedAnalyzeRequest analyzeRequest = new ExtendedAnalyzeRequest(request.param("index"));
    analyzeRequest.text(text);
    analyzeRequest.analyzer(request.param("analyzer"));
    analyzeRequest.field(request.param("field"));
    analyzeRequest.tokenizer(request.param("tokenizer"));
    analyzeRequest.tokenFilters(request.paramAsStringArray("token_filters", request.paramAsStringArray("filters", analyzeRequest.tokenFilters())));
    analyzeRequest.charFilters(request.paramAsStringArray("char_filters", analyzeRequest.charFilters()));
    analyzeRequest.attributes(request.paramAsStringArray("attributes", null));
    analyzeRequest.shortAttributeName(request.paramAsBoolean("use_short_attr", false));

    if (request.hasContent() || request.hasParam("source")) {
        XContentType type = guessBodyContentType(request);
        if (type == null) {
            if (text == null || text.length == 0) {
                text = new String[]{ RestActions.getRestContent(request).toUtf8()};
                analyzeRequest.text(text);
            }
        } else {
            buildFromContent(RestActions.getRestContent(request), analyzeRequest);
        }
    }

    client.admin().indices().execute(ExtendedAnalyzeAction.INSTANCE, analyzeRequest, new RestToXContentListener<ExtendedAnalyzeResponse>(channel));
}
 
Example #10
Source File: RestCoordinateMultiSearchAction.java    From siren-join with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception {
  MultiSearchRequest multiSearchRequest = new MultiSearchRequest();

  String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
  String[] types = Strings.splitStringByCommaToArray(request.param("type"));
  String path = request.path();
  boolean isTemplateRequest = isTemplateRequest(path);
  IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions());
  multiSearchRequest.add(RestActions.getRestContent(request), isTemplateRequest, indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex);

  client.execute(CoordinateMultiSearchAction.INSTANCE, multiSearchRequest, new RestToXContentListener<MultiSearchResponse>(channel));
}
 
Example #11
Source File: SearchResponse.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
    if (scrollId != null) {
        builder.field(Fields._SCROLL_ID, scrollId);
    }
    builder.field(Fields.TOOK, tookInMillis);
    builder.field(Fields.TIMED_OUT, isTimedOut());
    if (isTerminatedEarly() != null) {
        builder.field(Fields.TERMINATED_EARLY, isTerminatedEarly());
    }
    RestActions.buildBroadcastShardsHeader(builder, params, getTotalShards(), getSuccessfulShards(), getFailedShards(), getShardFailures());
    internalResponse.toXContent(builder, params);
    return builder;
}
 
Example #12
Source File: RestMultiTermVectorsAction.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 {
    MultiTermVectorsRequest multiTermVectorsRequest = new MultiTermVectorsRequest();
    TermVectorsRequest template = new TermVectorsRequest();
    template.index(request.param("index"));
    template.type(request.param("type"));
    RestTermVectorsAction.readURIParameters(template, request);
    multiTermVectorsRequest.ids(Strings.commaDelimitedListToStringArray(request.param("ids")));
    multiTermVectorsRequest.add(template, RestActions.getRestContent(request));

    client.multiTermVectors(multiTermVectorsRequest, new RestToXContentListener<MultiTermVectorsResponse>(channel));
}
 
Example #13
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 #14
Source File: RestMultiSearchAction.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 {
    MultiSearchRequest multiSearchRequest = new MultiSearchRequest();

    String[] indices = Strings.splitStringByCommaToArray(request.param("index"));
    String[] types = Strings.splitStringByCommaToArray(request.param("type"));
    String path = request.path();
    boolean isTemplateRequest = isTemplateRequest(path);
    IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions());
    multiSearchRequest.add(RestActions.getRestContent(request), isTemplateRequest, indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex);

    client.multiSearch(multiSearchRequest, new RestToXContentListener<MultiSearchResponse>(channel));
}
 
Example #15
Source File: RestDeleteAction.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) {
    DeleteRequest deleteRequest = new DeleteRequest(request.param("index"), request.param("type"), request.param("id"));
    deleteRequest.routing(request.param("routing"));
    deleteRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
    deleteRequest.timeout(request.paramAsTime("timeout", DeleteRequest.DEFAULT_TIMEOUT));
    deleteRequest.refresh(request.paramAsBoolean("refresh", deleteRequest.refresh()));
    deleteRequest.version(RestActions.parseVersion(request));
    deleteRequest.versionType(VersionType.fromString(request.param("version_type"), deleteRequest.versionType()));

    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        deleteRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }

    client.delete(deleteRequest, new RestBuilderListener<DeleteResponse>(channel) {
        @Override
        public RestResponse buildResponse(DeleteResponse result, XContentBuilder builder) throws Exception {
            ActionWriteResponse.ShardInfo shardInfo = result.getShardInfo();
            builder.startObject().field(Fields.FOUND, result.isFound())
                    .field(Fields._INDEX, result.getIndex())
                    .field(Fields._TYPE, result.getType())
                    .field(Fields._ID, result.getId())
                    .field(Fields._VERSION, result.getVersion())
                    .value(shardInfo)
                    .endObject();
            RestStatus status = shardInfo.status();
            if (!result.isFound()) {
                status = NOT_FOUND;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example #16
Source File: RestPercolateAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
void parseDocPercolate(PercolateRequest percolateRequest, RestRequest restRequest, RestChannel restChannel, final Client client) {
    percolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    percolateRequest.documentType(restRequest.param("type"));
    percolateRequest.routing(restRequest.param("routing"));
    percolateRequest.preference(restRequest.param("preference"));
    percolateRequest.source(RestActions.getRestContent(restRequest));

    percolateRequest.indicesOptions(IndicesOptions.fromRequest(restRequest, percolateRequest.indicesOptions()));
    executePercolate(percolateRequest, restChannel, client);
}
 
Example #17
Source File: RestMultiPercolateAction.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
@Override
public void handleRequest(final RestRequest restRequest, final RestChannel restChannel, final Client client) throws Exception {
    MultiPercolateRequest multiPercolateRequest = new MultiPercolateRequest();
    multiPercolateRequest.indicesOptions(IndicesOptions.fromRequest(restRequest, multiPercolateRequest.indicesOptions()));
    multiPercolateRequest.indices(Strings.splitStringByCommaToArray(restRequest.param("index")));
    multiPercolateRequest.documentType(restRequest.param("type"));
    multiPercolateRequest.add(RestActions.getRestContent(restRequest), allowExplicitIndex);

    client.multiPercolate(multiPercolateRequest, new RestToXContentListener<MultiPercolateResponse>(restChannel));
}
 
Example #18
Source File: RestGetAction.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 GetRequest getRequest = new GetRequest(request.param("index"), request.param("type"), request.param("id"));
    getRequest.operationThreaded(true);
    getRequest.refresh(request.paramAsBoolean("refresh", getRequest.refresh()));
    getRequest.routing(request.param("routing"));  // order is important, set it after routing, so it will set the routing
    getRequest.parent(request.param("parent"));
    getRequest.preference(request.param("preference"));
    getRequest.realtime(request.paramAsBoolean("realtime", null));
    getRequest.ignoreErrorsOnGeneratedFields(request.paramAsBoolean("ignore_errors_on_generated_fields", false));

    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            getRequest.fields(sFields);
        }
    }

    getRequest.version(RestActions.parseVersion(request));
    getRequest.versionType(VersionType.fromString(request.param("version_type"), getRequest.versionType()));

    getRequest.fetchSourceContext(FetchSourceContext.parseFromRestRequest(request));

    client.get(getRequest, new RestBuilderListener<GetResponse>(channel) {
        @Override
        public RestResponse buildResponse(GetResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            response.toXContent(builder, request);
            builder.endObject();
            if (!response.isExists()) {
                return new BytesRestResponse(NOT_FOUND, builder);
            } else {
                return new BytesRestResponse(OK, builder);
            }
        }
    });
}
 
Example #19
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 #20
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 #21
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 #22
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()));
}
 
Example #23
Source File: RestUpdateAction.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) throws Exception {
    UpdateRequest updateRequest = new UpdateRequest(request.param("index"), request.param("type"), request.param("id"));
    updateRequest.routing(request.param("routing"));
    updateRequest.parent(request.param("parent"));
    updateRequest.timeout(request.paramAsTime("timeout", updateRequest.timeout()));
    updateRequest.refresh(request.paramAsBoolean("refresh", updateRequest.refresh()));
    String consistencyLevel = request.param("consistency");
    if (consistencyLevel != null) {
        updateRequest.consistencyLevel(WriteConsistencyLevel.fromString(consistencyLevel));
    }
    updateRequest.docAsUpsert(request.paramAsBoolean("doc_as_upsert", updateRequest.docAsUpsert()));
    ScriptParameterParser scriptParameterParser = new ScriptParameterParser();
    scriptParameterParser.parseParams(request);
    ScriptParameterValue scriptValue = scriptParameterParser.getDefaultScriptParameterValue();
    if (scriptValue != null) {
        Map<String, Object> scriptParams = new HashMap<>();
        for (Map.Entry<String, String> entry : request.params().entrySet()) {
            if (entry.getKey().startsWith("sp_")) {
                scriptParams.put(entry.getKey().substring(3), entry.getValue());
            }
        }
        updateRequest.script(new Script(scriptValue.script(), scriptValue.scriptType(), scriptParameterParser.lang(), scriptParams));
    }
    String sField = request.param("fields");
    if (sField != null) {
        String[] sFields = Strings.splitStringByCommaToArray(sField);
        if (sFields != null) {
            updateRequest.fields(sFields);
        }
    }
    updateRequest.retryOnConflict(request.paramAsInt("retry_on_conflict", updateRequest.retryOnConflict()));
    updateRequest.version(RestActions.parseVersion(request));
    updateRequest.versionType(VersionType.fromString(request.param("version_type"), updateRequest.versionType()));


    // see if we have it in the body
    if (request.hasContent()) {
        updateRequest.source(request.content());
        IndexRequest upsertRequest = updateRequest.upsertRequest();
        if (upsertRequest != null) {
            upsertRequest.routing(request.param("routing"));
            upsertRequest.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            upsertRequest.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                upsertRequest.ttl(request.param("ttl"));
            }
            upsertRequest.version(RestActions.parseVersion(request));
            upsertRequest.versionType(VersionType.fromString(request.param("version_type"), upsertRequest.versionType()));
        }
        IndexRequest doc = updateRequest.doc();
        if (doc != null) {
            doc.routing(request.param("routing"));
            doc.parent(request.param("parent")); // order is important, set it after routing, so it will set the routing
            doc.timestamp(request.param("timestamp"));
            if (request.hasParam("ttl")) {
                doc.ttl(request.param("ttl"));
            }
            doc.version(RestActions.parseVersion(request));
            doc.versionType(VersionType.fromString(request.param("version_type"), doc.versionType()));
        }
    }

    client.update(updateRequest, new RestBuilderListener<UpdateResponse>(channel) {
        @Override
        public RestResponse buildResponse(UpdateResponse response, XContentBuilder builder) throws Exception {
            builder.startObject();
            ActionWriteResponse.ShardInfo shardInfo = response.getShardInfo();
            builder.field(Fields._INDEX, response.getIndex())
                    .field(Fields._TYPE, response.getType())
                    .field(Fields._ID, response.getId())
                    .field(Fields._VERSION, response.getVersion());

            shardInfo.toXContent(builder, request);
            if (response.getGetResult() != null) {
                builder.startObject(Fields.GET);
                response.getGetResult().toXContentEmbedded(builder, request);
                builder.endObject();
            }

            builder.endObject();
            RestStatus status = shardInfo.status();
            if (response.isCreated()) {
                status = CREATED;
            }
            return new BytesRestResponse(status, builder);
        }
    });
}
 
Example #24
Source File: RestRenderSearchTemplateAction.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Override
protected void handleRequest(RestRequest request, RestChannel channel, Client client) throws Exception {
    RenderSearchTemplateRequest renderSearchTemplateRequest;
    BytesReference source = RestActions.getRestContent(request);
    XContentParser parser = XContentFactory.xContent(source).createParser(source);
    String templateId = request.param("id");
    final Template template;
    if (templateId == null) {
        template = Template.parse(parser, parseFieldMatcher);
    } else {
        Map<String, Object> params = null;
        String currentFieldName = null;
        XContentParser.Token token = parser.nextToken();
        if (token != XContentParser.Token.START_OBJECT) {
            throw new ElasticsearchParseException("failed to parse request. request body must be an object but found [{}] instead", token);
        }
        while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) {
            if (token == XContentParser.Token.FIELD_NAME) {
                currentFieldName = parser.currentName();
            } else if (parseFieldMatcher.match(currentFieldName, ScriptField.PARAMS)) {
                if (token == XContentParser.Token.START_OBJECT) {
                    params = parser.map();
                } else {
                    throw new ElasticsearchParseException("failed to parse request. field [{}] is expected to be an object, but found [{}] instead", currentFieldName, token);
                }
            } else {
                throw new ElasticsearchParseException("failed to parse request. unknown field [{}] of type [{}]", currentFieldName, token);
            }
        }
        template = new Template(templateId, ScriptType.INDEXED, MustacheScriptEngineService.NAME, null, params);
    }
    renderSearchTemplateRequest = new RenderSearchTemplateRequest();
    renderSearchTemplateRequest.template(template);
    client.admin().cluster().renderSearchTemplate(renderSearchTemplateRequest, new RestBuilderListener<RenderSearchTemplateResponse>(channel) {

        @Override
        public RestResponse buildResponse(RenderSearchTemplateResponse response, XContentBuilder builder) throws Exception {
            builder.prettyPrint();
            response.toXContent(builder, ToXContent.EMPTY_PARAMS);
            return new BytesRestResponse(OK, builder);
        }});
}
 
Example #25
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);
        }
    });
}