Search in sources :

Example 16 with MultiSearchResponse

use of org.elasticsearch.action.search.MultiSearchResponse in project graylog2-server by Graylog2.

the class ElasticsearchBackend method doRun.

@Override
public QueryResult doRun(SearchJob job, Query query, ESGeneratedQueryContext queryContext) {
    if (query.searchTypes().isEmpty()) {
        return QueryResult.builder().query(query).searchTypes(Collections.emptyMap()).errors(new HashSet<>(queryContext.errors())).build();
    }
    LOG.debug("Running query {} for job {}", query.id(), job.getId());
    final HashMap<String, SearchType.Result> resultsMap = Maps.newHashMap();
    final Set<String> affectedIndices = indexLookup.indexNamesForStreamsInTimeRange(query.usedStreamIds(), query.timerange());
    final Map<String, SearchSourceBuilder> searchTypeQueries = queryContext.searchTypeQueries();
    final List<String> searchTypeIds = new ArrayList<>(searchTypeQueries.keySet());
    final List<SearchRequest> searches = searchTypeIds.stream().map(searchTypeId -> {
        final Set<String> affectedIndicesForSearchType = query.searchTypes().stream().filter(s -> s.id().equalsIgnoreCase(searchTypeId)).findFirst().flatMap(searchType -> {
            if (searchType.effectiveStreams().isEmpty() && !query.globalOverride().flatMap(GlobalOverride::timerange).isPresent() && !searchType.timerange().isPresent()) {
                return Optional.empty();
            }
            final Set<String> usedStreamIds = searchType.effectiveStreams().isEmpty() ? query.usedStreamIds() : searchType.effectiveStreams();
            return Optional.of(indexLookup.indexNamesForStreamsInTimeRange(usedStreamIds, query.effectiveTimeRange(searchType)));
        }).orElse(affectedIndices);
        Set<String> indices = affectedIndicesForSearchType.isEmpty() ? Collections.singleton("") : affectedIndicesForSearchType;
        return new SearchRequest().source(searchTypeQueries.get(searchTypeId)).indices(indices.toArray(new String[0])).indicesOptions(IndicesOptions.fromOptions(false, false, true, false));
    }).collect(Collectors.toList());
    final List<MultiSearchResponse.Item> results = client.msearch(searches, "Unable to perform search query: ");
    for (SearchType searchType : query.searchTypes()) {
        final String searchTypeId = searchType.id();
        final Provider<ESSearchTypeHandler<? extends SearchType>> handlerProvider = elasticsearchSearchTypeHandlers.get(searchType.type());
        if (handlerProvider == null) {
            LOG.error("Unknown search type '{}', cannot convert query result.", searchType.type());
            // no need to add another error here, as the query generation code will have added the error about the missing handler already
            continue;
        }
        if (isSearchTypeWithError(queryContext, searchTypeId)) {
            LOG.error("Failed search type '{}', cannot convert query result, skipping.", searchType.type());
            // no need to add another error here, as the query generation code will have added the error about the missing handler already
            continue;
        }
        // we create a new instance because some search type handlers might need to track information between generating the query and
        // processing its result, such as aggregations, which depend on the name and type
        final ESSearchTypeHandler<? extends SearchType> handler = handlerProvider.get();
        final int searchTypeIndex = searchTypeIds.indexOf(searchTypeId);
        final MultiSearchResponse.Item multiSearchResponse = results.get(searchTypeIndex);
        if (multiSearchResponse.isFailure()) {
            ElasticsearchException e = new ElasticsearchException("Search type returned error: ", multiSearchResponse.getFailure());
            queryContext.addError(SearchTypeErrorParser.parse(query, searchTypeId, e));
        } else if (checkForFailedShards(multiSearchResponse).isPresent()) {
            ElasticsearchException e = checkForFailedShards(multiSearchResponse).get();
            queryContext.addError(SearchTypeErrorParser.parse(query, searchTypeId, e));
        } else {
            final SearchType.Result searchTypeResult = handler.extractResult(job, query, searchType, multiSearchResponse.getResponse(), queryContext);
            if (searchTypeResult != null) {
                resultsMap.put(searchTypeId, searchTypeResult);
            }
        }
    }
    LOG.debug("Query {} ran for job {}", query.id(), job.getId());
    return QueryResult.builder().query(query).searchTypes(resultsMap).errors(new HashSet<>(queryContext.errors())).build();
}
Also used : ESSearchTypeHandler(org.graylog.storage.elasticsearch7.views.searchtypes.ESSearchTypeHandler) AndFilter(org.graylog.plugins.views.search.filter.AndFilter) ElasticsearchClient(org.graylog.storage.elasticsearch7.ElasticsearchClient) Arrays(java.util.Arrays) BackendQuery(org.graylog.plugins.views.search.engine.BackendQuery) QueryBackend(org.graylog.plugins.views.search.engine.QueryBackend) Provider(javax.inject.Provider) LoggerFactory(org.slf4j.LoggerFactory) FieldTypeException(org.graylog2.indexer.FieldTypeException) MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) StreamFilter(org.graylog.plugins.views.search.filter.StreamFilter) Map(java.util.Map) IndicesOptions(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.support.IndicesOptions) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) Set(java.util.Set) Collectors(java.util.stream.Collectors) BoolQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.BoolQueryBuilder) Objects(java.util.Objects) List(java.util.List) Filter(org.graylog.plugins.views.search.Filter) Optional(java.util.Optional) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse) Query(org.graylog.plugins.views.search.Query) SearchTypeErrorParser(org.graylog.plugins.views.search.errors.SearchTypeErrorParser) HashMap(java.util.HashMap) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) ShardOperationFailedException(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.ShardOperationFailedException) ArrayList(java.util.ArrayList) GlobalOverride(org.graylog.plugins.views.search.GlobalOverride) Inject(javax.inject.Inject) HashSet(java.util.HashSet) OrFilter(org.graylog.plugins.views.search.filter.OrFilter) SearchType(org.graylog.plugins.views.search.SearchType) QueryStringFilter(org.graylog.plugins.views.search.filter.QueryStringFilter) SearchTypeError(org.graylog.plugins.views.search.errors.SearchTypeError) QueryResult(org.graylog.plugins.views.search.QueryResult) TimeRangeQueryFactory(org.graylog.storage.elasticsearch7.TimeRangeQueryFactory) SearchJob(org.graylog.plugins.views.search.SearchJob) QueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) Logger(org.slf4j.Logger) SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) Maps(com.google.common.collect.Maps) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) Named(com.google.inject.name.Named) IndexLookup(org.graylog.plugins.views.search.elasticsearch.IndexLookup) QueryBuilders(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilders) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) Set(java.util.Set) HashSet(java.util.HashSet) ArrayList(java.util.ArrayList) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) QueryResult(org.graylog.plugins.views.search.QueryResult) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) GlobalOverride(org.graylog.plugins.views.search.GlobalOverride) MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) ESSearchTypeHandler(org.graylog.storage.elasticsearch7.views.searchtypes.ESSearchTypeHandler) SearchType(org.graylog.plugins.views.search.SearchType) HashSet(java.util.HashSet) GlobalOverride(org.graylog.plugins.views.search.GlobalOverride)

Example 17 with MultiSearchResponse

use of org.elasticsearch.action.search.MultiSearchResponse in project graylog2-server by Graylog2.

the class ElasticsearchBackendUsingCorrectIndicesTest method setupSUT.

@Before
public void setupSUT() throws Exception {
    final MultiSearchResponse response = TestMultisearchResponse.fromFixture("successfulResponseWithSingleQuery.json");
    final List<MultiSearchResponse.Item> items = Arrays.stream(response.getResponses()).collect(Collectors.toList());
    when(client.msearch(any(), any())).thenReturn(items);
    final FieldTypesLookup fieldTypesLookup = mock(FieldTypesLookup.class);
    this.backend = new ElasticsearchBackend(handlers, client, indexLookup, new QueryStringDecorators.Fake(), (elasticsearchBackend, ssb, job, query) -> new ESGeneratedQueryContext(elasticsearchBackend, ssb, job, query, fieldTypesLookup), false);
}
Also used : ESSearchTypeHandler(org.graylog.storage.elasticsearch7.views.searchtypes.ESSearchTypeHandler) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) AndFilter(org.graylog.plugins.views.search.filter.AndFilter) ElasticsearchClient(org.graylog.storage.elasticsearch7.ElasticsearchClient) Arrays(java.util.Arrays) Provider(javax.inject.Provider) Query(org.graylog.plugins.views.search.Query) DateTimeUtils(org.joda.time.DateTimeUtils) Mock(org.mockito.Mock) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) RelativeRange(org.graylog2.plugin.indexer.searches.timeranges.RelativeRange) Captor(org.mockito.Captor) ViewsUtils.indicesOf(org.graylog.storage.elasticsearch7.views.ViewsUtils.indicesOf) ElasticsearchQueryString(org.graylog.plugins.views.search.elasticsearch.ElasticsearchQueryString) MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) ArgumentCaptor(org.mockito.ArgumentCaptor) StreamFilter(org.graylog.plugins.views.search.filter.StreamFilter) SearchType(org.graylog.plugins.views.search.SearchType) After(org.junit.After) Map(java.util.Map) FieldTypesLookup(org.graylog.plugins.views.search.elasticsearch.FieldTypesLookup) MockitoJUnit(org.mockito.junit.MockitoJUnit) Search(org.graylog.plugins.views.search.Search) MessageList(org.graylog.plugins.views.search.searchtypes.MessageList) TimeRange(org.graylog2.plugin.indexer.searches.timeranges.TimeRange) Before(org.junit.Before) Period(org.joda.time.Period) SearchJob(org.graylog.plugins.views.search.SearchJob) ImmutableSet(com.google.common.collect.ImmutableSet) TestMultisearchResponse(org.graylog.storage.elasticsearch7.testing.TestMultisearchResponse) ImmutableMap(com.google.common.collect.ImmutableMap) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) Test(org.junit.Test) Mockito.times(org.mockito.Mockito.times) Mockito.when(org.mockito.Mockito.when) Collectors(java.util.stream.Collectors) Mockito.verify(org.mockito.Mockito.verify) List(java.util.List) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) Rule(org.junit.Rule) ESMessageList(org.graylog.storage.elasticsearch7.views.searchtypes.ESMessageList) MockitoRule(org.mockito.junit.MockitoRule) IndexLookup(org.graylog.plugins.views.search.elasticsearch.IndexLookup) Mockito.mock(org.mockito.Mockito.mock) MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) FieldTypesLookup(org.graylog.plugins.views.search.elasticsearch.FieldTypesLookup) Before(org.junit.Before)

Example 18 with MultiSearchResponse

use of org.elasticsearch.action.search.MultiSearchResponse in project graylog2-server by Graylog2.

the class ElasticsearchBackendErrorHandlingTest method deduplicateNumericShardErrorsOnSearchTypeLevel.

@Test
public void deduplicateNumericShardErrorsOnSearchTypeLevel() throws IOException {
    final MultiSearchResponse multiSearchResult = TestMultisearchResponse.fromFixture("errorhandling/numericFailureOnSearchTypeLevel.json");
    final List<MultiSearchResponse.Item> items = Arrays.stream(multiSearchResult.getResponses()).collect(Collectors.toList());
    when(client.msearch(any(), any())).thenReturn(items);
    final QueryResult queryResult = this.backend.doRun(searchJob, query, queryContext);
    final Set<SearchError> errors = queryResult.errors();
    assertThat(errors).isNotNull();
    assertThat(errors).hasSize(1);
    assertThat(errors.stream().map(SearchError::description).collect(Collectors.toList())).containsExactly("Unable to perform search query: " + "\n\nElasticsearch exception [type=illegal_argument_exception, reason=Expected numeric type on field [facility], but got [keyword]].");
}
Also used : MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) QueryResult(org.graylog.plugins.views.search.QueryResult) SearchError(org.graylog.plugins.views.search.errors.SearchError) Test(org.junit.Test)

Example 19 with MultiSearchResponse

use of org.elasticsearch.action.search.MultiSearchResponse in project graylog2-server by Graylog2.

the class ElasticsearchBackendMultiSearchTest method oneFailingSearchTypeReturnsPartialResults.

@Test
public void oneFailingSearchTypeReturnsPartialResults() throws Exception {
    final ESGeneratedQueryContext queryContext = this.elasticsearchBackend.generate(searchJob, query, new SearchConfig(Period.ZERO));
    final MultiSearchResponse response = TestMultisearchResponse.fromFixture("partiallySuccessfulMultiSearchResponse.json");
    final List<MultiSearchResponse.Item> items = Arrays.stream(response.getResponses()).collect(Collectors.toList());
    when(client.msearch(any(), any())).thenReturn(items);
    final QueryResult queryResult = this.elasticsearchBackend.doRun(searchJob, query, queryContext);
    assertThat(queryResult.errors()).hasSize(1);
    final SearchTypeError searchTypeError = (SearchTypeError) new ArrayList<>(queryResult.errors()).get(0);
    assertThat(searchTypeError.description()).isEqualTo("Unable to perform search query: \n" + "\n" + "Elasticsearch exception [type=illegal_argument_exception, reason=Expected numeric type on field [field1], but got [keyword]].");
    assertThat(searchTypeError.searchTypeId()).isEqualTo("pivot1");
    assertThat(queryResult.searchTypes()).containsOnlyKeys("pivot2");
    final PivotResult pivot2Result = (PivotResult) queryResult.searchTypes().get("pivot2");
    assertThat(pivot2Result.rows().get(0)).isEqualTo(PivotResult.Row.builder().key(ImmutableList.of()).source("leaf").addValue(PivotResult.Value.create(Collections.singletonList("max(field2)"), 42.0, true, "row-leaf")).build());
}
Also used : MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) QueryResult(org.graylog.plugins.views.search.QueryResult) SearchTypeError(org.graylog.plugins.views.search.errors.SearchTypeError) PivotResult(org.graylog.plugins.views.search.searchtypes.pivot.PivotResult) ArrayList(java.util.ArrayList) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) Test(org.junit.Test)

Example 20 with MultiSearchResponse

use of org.elasticsearch.action.search.MultiSearchResponse in project graylog2-server by Graylog2.

the class ElasticsearchBackendSearchTypeOverridesTest method overridesInSearchTypeAreIncorporatedIntoGeneratedQueries.

@Test
public void overridesInSearchTypeAreIncorporatedIntoGeneratedQueries() throws IOException {
    final ESGeneratedQueryContext queryContext = this.elasticsearchBackend.generate(searchJob, query, new SearchConfig(Period.ZERO));
    final MultiSearchResponse response = TestMultisearchResponse.fromFixture("successfulMultiSearchResponse.json");
    final List<MultiSearchResponse.Item> items = Arrays.stream(response.getResponses()).collect(Collectors.toList());
    when(client.msearch(any(), any())).thenReturn(items);
    final List<SearchRequest> generatedRequest = run(searchJob, query, queryContext, Collections.emptySet());
    final DocumentContext pivot1 = parse(generatedRequest.get(0).source().toString());
    final DocumentContext pivot2 = parse(generatedRequest.get(1).source().toString());
    assertThat(queryStrings(pivot1)).containsExactly("production:true");
    assertThat(timerangeFrom(pivot1)).containsExactly("2019-09-11 10:31:52.819");
    assertThat(timerangeTo(pivot1)).containsExactly("2019-09-11 10:36:52.823");
    assertThat(streams(pivot1)).containsExactly(Collections.singletonList("stream1"));
    assertThat(queryStrings(pivot2)).containsExactly("production:true", "source:babbage");
    assertThat(timerangeFrom(pivot2)).containsExactly("2018-08-23 08:02:00.247");
    assertThat(timerangeTo(pivot2)).containsExactly("2018-08-23 08:07:00.252");
    assertThat(streams(pivot2)).containsExactly(Collections.singletonList("stream1"));
}
Also used : MultiSearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse) SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) DocumentContext(com.jayway.jsonpath.DocumentContext) Test(org.junit.Test)

Aggregations

MultiSearchResponse (org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.MultiSearchResponse)13 Test (org.junit.Test)10 MultiSearchResponse (org.elasticsearch.action.search.MultiSearchResponse)8 SearchConfig (org.graylog.plugins.views.search.engine.SearchConfig)8 QueryResult (org.graylog.plugins.views.search.QueryResult)6 SearchRequest (org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest)6 ArrayList (java.util.ArrayList)5 HashMap (java.util.HashMap)4 Arrays (java.util.Arrays)3 List (java.util.List)3 Map (java.util.Map)3 Collectors (java.util.stream.Collectors)3 Provider (javax.inject.Provider)3 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)3 Query (org.graylog.plugins.views.search.Query)3 SearchJob (org.graylog.plugins.views.search.SearchJob)3 SearchType (org.graylog.plugins.views.search.SearchType)3 IndexLookup (org.graylog.plugins.views.search.elasticsearch.IndexLookup)3 QueryStringDecorators (org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators)3 SearchTypeError (org.graylog.plugins.views.search.errors.SearchTypeError)3