use of org.opensearch.rest.action.RestBuilderListener in project OpenSearch by opensearch-project.
the class RestCountAction method prepareRequest.
@Override
public RestChannelConsumer prepareRequest(final RestRequest request, final NodeClient client) throws IOException {
SearchRequest countRequest = new SearchRequest(Strings.splitStringByCommaToArray(request.param("index")));
countRequest.indicesOptions(IndicesOptions.fromRequest(request, countRequest.indicesOptions()));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().size(0).trackTotalHits(true);
countRequest.source(searchSourceBuilder);
request.withContentOrSourceParamParserOrNull(parser -> {
if (parser == null) {
QueryBuilder queryBuilder = RestActions.urlParamsToQueryBuilder(request);
if (queryBuilder != null) {
searchSourceBuilder.query(queryBuilder);
}
} else {
searchSourceBuilder.query(RestActions.getQueryContent(parser));
}
});
countRequest.routing(request.param("routing"));
float minScore = request.paramAsFloat("min_score", -1f);
if (minScore != -1f) {
searchSourceBuilder.minScore(minScore);
}
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) {
searchSourceBuilder.terminateAfter(terminateAfter);
}
return channel -> client.search(countRequest, 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().getTotalHits().value);
buildBroadcastShardsHeader(builder, request, response.getTotalShards(), response.getSuccessfulShards(), 0, response.getFailedShards(), response.getShardFailures());
builder.endObject();
return new BytesRestResponse(response.status(), builder);
}
});
}
Aggregations