Search in sources :

Example 36 with SearchJob

use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.

the class ElasticsearchBackendQueryStringDecoratorsTest method basicSearchJob.

@Nonnull
private SearchJob basicSearchJob(Query query, SearchType searchType) throws InvalidRangeParametersException {
    final SearchJob searchJob = mock(SearchJob.class);
    final Search search = mock(Search.class);
    when(searchJob.getSearch()).thenReturn(search);
    when(search.queries()).thenReturn(ImmutableSet.of(query));
    when(query.effectiveTimeRange(any())).thenReturn(RelativeRange.create(300));
    when(query.searchTypes()).thenReturn(ImmutableSet.of(searchType));
    return searchJob;
}
Also used : Search(org.graylog.plugins.views.search.Search) SearchJob(org.graylog.plugins.views.search.SearchJob) Nonnull(javax.annotation.Nonnull)

Example 37 with SearchJob

use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.

the class ESMessageList method doExtractResult.

@Override
public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse result, Aggregations aggregations, ESGeneratedQueryContext queryContext) {
    final List<ResultMessageSummary> messages = StreamSupport.stream(result.getHits().spliterator(), false).map(ESMessageList::resultMessageFromSearchHit).map((resultMessage) -> ResultMessageSummary.create(resultMessage.highlightRanges, resultMessage.getMessage().getFields(), resultMessage.getIndex())).collect(Collectors.toList());
    final String undecoratedQueryString = query.query().queryString();
    final String queryString = this.esQueryDecorators.decorate(undecoratedQueryString, job, query);
    final DateTime from = query.effectiveTimeRange(searchType).getFrom();
    final DateTime to = query.effectiveTimeRange(searchType).getTo();
    final SearchResponse searchResponse = SearchResponse.create(undecoratedQueryString, queryString, Collections.emptySet(), messages, Collections.emptySet(), 0, result.getHits().getTotalHits().value, from, to);
    final SearchResponse decoratedSearchResponse = decoratorProcessor.decorateSearchResponse(searchResponse, searchType.decorators());
    final MessageList.Result.Builder resultBuilder = MessageList.Result.result(searchType.id()).messages(decoratedSearchResponse.messages()).effectiveTimerange(AbsoluteRange.create(from, to)).totalResults(decoratedSearchResponse.totalResults());
    return searchType.name().map(resultBuilder::name).orElse(resultBuilder).build();
}
Also used : Arrays(java.util.Arrays) Query(org.graylog.plugins.views.search.Query) Text(org.graylog.shaded.elasticsearch7.org.elasticsearch.common.text.Text) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) Inject(javax.inject.Inject) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchType(org.graylog.plugins.views.search.SearchType) Sort(org.graylog.plugins.views.search.searchtypes.Sort) Map(java.util.Map) ESGeneratedQueryContext(org.graylog.storage.elasticsearch7.views.ESGeneratedQueryContext) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) StreamSupport(java.util.stream.StreamSupport) MessageList(org.graylog.plugins.views.search.searchtypes.MessageList) QueryStringQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryStringQueryBuilder) LegacyDecoratorProcessor(org.graylog.plugins.views.search.LegacyDecoratorProcessor) SortBuilders(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.sort.SortBuilders) FieldSortBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.sort.FieldSortBuilder) SearchJob(org.graylog.plugins.views.search.SearchJob) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) DateTime(org.joda.time.DateTime) Set(java.util.Set) Collectors(java.util.stream.Collectors) SortOrder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.sort.SortOrder) Aggregations(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.Aggregations) HighlightBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) List(java.util.List) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) SearchHit(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.SearchHit) Optional(java.util.Optional) Named(com.google.inject.name.Named) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) VisibleForTesting(com.google.common.annotations.VisibleForTesting) HighlightField(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.fetch.subphase.highlight.HighlightField) QueryBuilders(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilders) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) DateTime(org.joda.time.DateTime) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse)

Example 38 with SearchJob

use of org.graylog.plugins.views.search.SearchJob 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 39 with SearchJob

use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.

the class ElasticsearchBackendTest method generatesSearchForEmptySearchTypes.

@Test
public void generatesSearchForEmptySearchTypes() throws Exception {
    final Query query = Query.builder().id("query1").query(ElasticsearchQueryString.of("")).timerange(RelativeRange.create(300)).build();
    final Search search = Search.builder().queries(ImmutableSet.of(query)).build();
    final SearchJob job = new SearchJob("deadbeef", search, "admin");
    backend.generate(job, query, new SearchConfig(Period.ZERO));
}
Also used : Query(org.graylog.plugins.views.search.Query) Search(org.graylog.plugins.views.search.Search) SearchJob(org.graylog.plugins.views.search.SearchJob) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) Test(org.junit.Test)

Example 40 with SearchJob

use of org.graylog.plugins.views.search.SearchJob in project graylog2-server by Graylog2.

the class ElasticsearchBackendUsingCorrectIndicesTest method queryUsesOnlyIndicesIncludingTimerangeAndStream.

@Test
public void queryUsesOnlyIndicesIncludingTimerangeAndStream() throws Exception {
    final String streamId = "streamId";
    final Query query = dummyQuery(RelativeRange.create(600)).toBuilder().filter(StreamFilter.ofId(streamId)).build();
    final Search search = dummySearch(query);
    final SearchJob job = new SearchJob("job1", search, "admin");
    final ESGeneratedQueryContext context = backend.generate(job, query, new SearchConfig(Period.ZERO));
    when(indexLookup.indexNamesForStreamsInTimeRange(ImmutableSet.of("streamId"), RelativeRange.create(600))).thenReturn(ImmutableSet.of("index1", "index2"));
    backend.doRun(job, query, context);
    verify(jestClient, times(1)).execute(clientRequestCaptor.capture(), any());
    final MultiSearch clientRequest = clientRequestCaptor.getValue();
    assertThat(clientRequest).isNotNull();
    assertThat(indicesOf(clientRequest).get(0)).isEqualTo("index1,index2");
}
Also used : Query(org.graylog.plugins.views.search.Query) Search(org.graylog.plugins.views.search.Search) MultiSearch(io.searchbox.core.MultiSearch) SearchJob(org.graylog.plugins.views.search.SearchJob) ElasticsearchQueryString(org.graylog.plugins.views.search.elasticsearch.ElasticsearchQueryString) SearchConfig(org.graylog.plugins.views.search.engine.SearchConfig) MultiSearch(io.searchbox.core.MultiSearch) Test(org.junit.Test)

Aggregations

SearchJob (org.graylog.plugins.views.search.SearchJob)49 Query (org.graylog.plugins.views.search.Query)24 Search (org.graylog.plugins.views.search.Search)24 Test (org.junit.Test)16 SearchType (org.graylog.plugins.views.search.SearchType)13 SearchConfig (org.graylog.plugins.views.search.engine.SearchConfig)12 QueryResult (org.graylog.plugins.views.search.QueryResult)10 Collections (java.util.Collections)9 Set (java.util.Set)9 Collectors (java.util.stream.Collectors)9 List (java.util.List)8 QueryStringDecorators (org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators)8 Optional (java.util.Optional)7 ElasticsearchQueryString (org.graylog.plugins.views.search.elasticsearch.ElasticsearchQueryString)7 Message (org.graylog2.plugin.Message)7 IndexLookup (org.graylog.plugins.views.search.elasticsearch.IndexLookup)6 Named (com.google.inject.name.Named)5 MultiSearch (io.searchbox.core.MultiSearch)5 ArrayList (java.util.ArrayList)5 Map (java.util.Map)5