Search in sources :

Example 11 with SearchResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse in project elasticsearch by elastic.

the class IndexLookupIT method testCallWithDifferentFlagsFails.

public void testCallWithDifferentFlagsFails() throws Exception {
    initTestData();
    final int numPrimaries = getNumShards("test").numPrimaries;
    final String expectedError = "You must call get with all required flags! " + "Instead of  _index['int_payload_field'].get('b', _FREQUENCIES) and _index['int_payload_field'].get('b', _POSITIONS)" + " call  _index['int_payload_field'].get('b', _FREQUENCIES | _POSITIONS)  once]";
    // should throw an exception, we cannot call with different flags twice
    // if the flags of the second call were not included in the first call.
    Script script = createScript("Call with different flags twice");
    try {
        SearchResponse response = client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()).addScriptField("tvtest", script).get();
        // (partial) success when at least one shard succeeds
        assertThat(numPrimaries, greaterThan(response.getShardFailures().length));
        assertThat(response.getFailedShards(), greaterThanOrEqualTo(1));
        for (ShardSearchFailure failure : response.getShardFailures()) {
            assertThat(failure.reason(), containsString(expectedError));
        }
    } catch (SearchPhaseExecutionException e) {
        // Exception thrown when *all* shards fail
        assertThat(numPrimaries, equalTo(e.shardFailures().length));
        for (ShardSearchFailure failure : e.shardFailures()) {
            assertThat(failure.reason(), containsString(expectedError));
        }
    }
    // Should not throw an exception this way round
    script = createScript("Call with same flags twice");
    assertThat(client().prepareSearch("test").setQuery(QueryBuilders.matchAllQuery()).addScriptField("tvtest", script).get().getHits().getTotalHits(), greaterThan(0L));
}
Also used : SearchPhaseExecutionException(org.elasticsearch.action.search.SearchPhaseExecutionException) Matchers.containsString(org.hamcrest.Matchers.containsString) ShardSearchFailure(org.elasticsearch.action.search.ShardSearchFailure) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 12 with SearchResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse 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)

Example 13 with SearchResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse in project elasticsearch by elastic.

the class ClientScrollableHitSource method wrap.

private Response wrap(SearchResponse response) {
    List<SearchFailure> failures;
    if (response.getShardFailures() == null) {
        failures = emptyList();
    } else {
        failures = new ArrayList<>(response.getShardFailures().length);
        for (ShardSearchFailure failure : response.getShardFailures()) {
            String nodeId = failure.shard() == null ? null : failure.shard().getNodeId();
            failures.add(new SearchFailure(failure.getCause(), failure.index(), failure.shardId(), nodeId));
        }
    }
    List<Hit> hits;
    if (response.getHits().getHits() == null || response.getHits().getHits().length == 0) {
        hits = emptyList();
    } else {
        hits = new ArrayList<>(response.getHits().getHits().length);
        for (SearchHit hit : response.getHits().getHits()) {
            hits.add(new ClientHit(hit));
        }
        hits = unmodifiableList(hits);
    }
    return new Response(response.isTimedOut(), failures, response.getHits().getTotalHits(), hits, response.getScrollId());
}
Also used : ClearScrollResponse(org.elasticsearch.action.search.ClearScrollResponse) SearchResponse(org.elasticsearch.action.search.SearchResponse) ShardSearchFailure(org.elasticsearch.action.search.ShardSearchFailure) SearchHit(org.elasticsearch.search.SearchHit) SearchHit(org.elasticsearch.search.SearchHit) ShardSearchFailure(org.elasticsearch.action.search.ShardSearchFailure)

Example 14 with SearchResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse in project elasticsearch by elastic.

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);
    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.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) {
        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());
            buildBroadcastShardsHeader(builder, request, response.getTotalShards(), response.getSuccessfulShards(), response.getFailedShards(), response.getShardFailures());
            builder.endObject();
            return new BytesRestResponse(response.status(), builder);
        }
    });
}
Also used : BaseRestHandler(org.elasticsearch.rest.BaseRestHandler) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) GET(org.elasticsearch.rest.RestRequest.Method.GET) RestResponse(org.elasticsearch.rest.RestResponse) RestBuilderListener(org.elasticsearch.rest.action.RestBuilderListener) IOException(java.io.IOException) SearchRequest(org.elasticsearch.action.search.SearchRequest) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder) RestController(org.elasticsearch.rest.RestController) Strings(org.elasticsearch.common.Strings) RestActions(org.elasticsearch.rest.action.RestActions) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) DEFAULT_TERMINATE_AFTER(org.elasticsearch.search.internal.SearchContext.DEFAULT_TERMINATE_AFTER) POST(org.elasticsearch.rest.RestRequest.Method.POST) Settings(org.elasticsearch.common.settings.Settings) RestActions.buildBroadcastShardsHeader(org.elasticsearch.rest.action.RestActions.buildBroadcastShardsHeader) SearchResponse(org.elasticsearch.action.search.SearchResponse) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) RestRequest(org.elasticsearch.rest.RestRequest) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) NodeClient(org.elasticsearch.client.node.NodeClient) SearchRequest(org.elasticsearch.action.search.SearchRequest) RestResponse(org.elasticsearch.rest.RestResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) IOException(java.io.IOException) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) BytesRestResponse(org.elasticsearch.rest.BytesRestResponse) XContentBuilder(org.elasticsearch.common.xcontent.XContentBuilder)

Example 15 with SearchResponse

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse in project elasticsearch by elastic.

the class IndicesRequestIT method testSearchDfsQueryThenFetch.

public void testSearchDfsQueryThenFetch() throws Exception {
    interceptTransportActions(SearchTransportService.DFS_ACTION_NAME, SearchTransportService.QUERY_ID_ACTION_NAME, SearchTransportService.FETCH_ID_ACTION_NAME, SearchTransportService.FREE_CONTEXT_ACTION_NAME);
    String[] randomIndicesOrAliases = randomIndicesOrAliases();
    for (int i = 0; i < randomIndicesOrAliases.length; i++) {
        client().prepareIndex(randomIndicesOrAliases[i], "type", "id-" + i).setSource("field", "value").get();
    }
    refresh();
    SearchRequest searchRequest = new SearchRequest(randomIndicesOrAliases).searchType(SearchType.DFS_QUERY_THEN_FETCH);
    SearchResponse searchResponse = internalCluster().coordOnlyNodeClient().search(searchRequest).actionGet();
    assertNoFailures(searchResponse);
    assertThat(searchResponse.getHits().getTotalHits(), greaterThan(0L));
    clearInterceptedActions();
    assertSameIndices(searchRequest, SearchTransportService.DFS_ACTION_NAME, SearchTransportService.QUERY_ID_ACTION_NAME, SearchTransportService.FETCH_ID_ACTION_NAME);
    //free context messages are not necessarily sent, but if they are, check their indices
    assertSameIndicesOptionalRequests(searchRequest, SearchTransportService.FREE_CONTEXT_ACTION_NAME);
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Aggregations

SearchResponse (org.elasticsearch.action.search.SearchResponse)1693 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)976 Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)272 SearchHit (org.elasticsearch.search.SearchHit)225 Script (org.elasticsearch.script.Script)223 ArrayList (java.util.ArrayList)212 Histogram (org.elasticsearch.search.aggregations.bucket.histogram.Histogram)210 Matchers.containsString (org.hamcrest.Matchers.containsString)156 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)143 HashMap (java.util.HashMap)134 Bucket (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket)133 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)132 Bucket (org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket)94 SearchHits (org.elasticsearch.search.SearchHits)89 Sum (org.elasticsearch.search.aggregations.metrics.sum.Sum)83 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)76 Test (org.junit.Test)73 SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)72 GeoPoint (org.elasticsearch.common.geo.GeoPoint)70 Map (java.util.Map)67