Search in sources :

Example 16 with SearchResult

use of org.graylog2.indexer.results.SearchResult in project graylog2-server by Graylog2.

the class Searches method search.

public SearchResult search(SearchesConfig config) {
    final Set<IndexRange> indexRanges = determineAffectedIndicesWithRanges(config.range(), config.filter());
    final Set<String> indices = extractIndexNamesFromIndexRanges(indexRanges);
    final SearchResult result = searchesAdapter.search(indices, indexRanges, config);
    recordEsMetrics(result.tookMs(), config.range());
    return result;
}
Also used : IndexRange(org.graylog2.indexer.ranges.IndexRange) SearchResult(org.graylog2.indexer.results.SearchResult)

Example 17 with SearchResult

use of org.graylog2.indexer.results.SearchResult in project graylog2-server by Graylog2.

the class IndicesAdapterES6 method indexRangeStatsOfIndex.

@Override
public IndexRangeStats indexRangeStatsOfIndex(String index) {
    final FilterAggregationBuilder builder = AggregationBuilders.filter("agg", QueryBuilders.existsQuery(Message.FIELD_TIMESTAMP)).subAggregation(AggregationBuilders.min("ts_min").field(Message.FIELD_TIMESTAMP)).subAggregation(AggregationBuilders.max("ts_max").field(Message.FIELD_TIMESTAMP)).subAggregation(AggregationBuilders.terms("streams").size(Integer.MAX_VALUE).field(Message.FIELD_STREAMS));
    final String query = searchSource().aggregation(builder).size(0).toString();
    final Search request = new Search.Builder(query).addIndex(index).setSearchType(SearchType.DFS_QUERY_THEN_FETCH).ignoreUnavailable(true).build();
    if (LOG.isDebugEnabled()) {
        String data = "{}";
        try {
            data = request.getData(objectMapper.copy().enable(SerializationFeature.INDENT_OUTPUT));
        } catch (IOException e) {
            LOG.debug("Couldn't pretty print request payload", e);
        }
        LOG.debug("Index range query: _search/{}: {}", index, data);
    }
    final SearchResult result = JestUtils.execute(jestClient, request, () -> "Couldn't build index range of index " + index);
    final FilterAggregation f = result.getAggregations().getFilterAggregation("agg");
    if (f == null) {
        throw new IndexNotFoundException("Couldn't build index range of index " + index + " because it doesn't exist.");
    } else if (f.getCount() == 0L) {
        LOG.debug("No documents with attribute \"timestamp\" found in index <{}>", index);
        return IndexRangeStats.EMPTY;
    }
    final MinAggregation minAgg = f.getMinAggregation("ts_min");
    final DateTime min = new DateTime(minAgg.getMin().longValue(), DateTimeZone.UTC);
    final MaxAggregation maxAgg = f.getMaxAggregation("ts_max");
    final DateTime max = new DateTime(maxAgg.getMax().longValue(), DateTimeZone.UTC);
    // make sure we return an empty list, so we can differentiate between old indices that don't have this information
    // and newer ones that simply have no streams.
    final TermsAggregation streams = f.getTermsAggregation("streams");
    final List<String> streamIds = streams.getBuckets().stream().map(TermsAggregation.Entry::getKeyAsString).collect(toList());
    return IndexRangeStats.create(min, max, streamIds);
}
Also used : TermsAggregation(io.searchbox.core.search.aggregation.TermsAggregation) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) SearchResult(io.searchbox.core.SearchResult) MinAggregation(io.searchbox.core.search.aggregation.MinAggregation) IOException(java.io.IOException) MaxAggregation(io.searchbox.core.search.aggregation.MaxAggregation) DateTime(org.joda.time.DateTime) Search(io.searchbox.core.Search) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) FilterAggregation(io.searchbox.core.search.aggregation.FilterAggregation)

Example 18 with SearchResult

use of org.graylog2.indexer.results.SearchResult in project graylog2-server by Graylog2.

the class MoreSearchAdapterES6 method eventSearch.

@Override
public MoreSearch.Result eventSearch(String queryString, TimeRange timerange, Set<String> affectedIndices, Sorting sorting, int page, int perPage, Set<String> eventStreams, String filterString, Set<String> forbiddenSourceStreams) {
    final QueryBuilder query = (queryString.isEmpty() || queryString.equals("*")) ? matchAllQuery() : queryStringQuery(queryString).allowLeadingWildcard(allowLeadingWildcard);
    final BoolQueryBuilder filter = boolQuery().filter(query).filter(termsQuery(EventDto.FIELD_STREAMS, eventStreams)).filter(requireNonNull(TimeRangeQueryFactory.create(timerange)));
    if (!isNullOrEmpty(filterString)) {
        filter.filter(queryStringQuery(filterString));
    }
    if (!forbiddenSourceStreams.isEmpty()) {
        // If an event has any stream in "source_streams" that the calling search user is not allowed to access,
        // the event must not be in the search result.
        filter.filter(boolQuery().mustNot(termsQuery(EventDto.FIELD_SOURCE_STREAMS, forbiddenSourceStreams)));
    }
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(filter).from((page - 1) * perPage).size(perPage).sort(sorting.getField(), sortOrderMapper.fromSorting(sorting));
    final Search.Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).addType(IndexMapping.TYPE_MESSAGE).addIndex(affectedIndices.isEmpty() ? Collections.singleton("") : affectedIndices).allowNoIndices(false).ignoreUnavailable(false);
    if (LOG.isDebugEnabled()) {
        LOG.debug("Query:\n{}", searchSourceBuilder.toString(new ToXContent.MapParams(Collections.singletonMap("pretty", "true"))));
        LOG.debug("Execute search: {}", searchBuilder.build().toString());
    }
    final io.searchbox.core.SearchResult searchResult = multiSearch.wrap(searchBuilder.build(), () -> "Unable to perform search query");
    @SuppressWarnings("unchecked") final List<ResultMessage> hits = searchResult.getHits(Map.class, false).stream().map(hit -> ResultMessage.parseFromSource(hit.id, hit.index, (Map<String, Object>) hit.source, hit.highlight)).collect(Collectors.toList());
    return MoreSearch.Result.builder().results(hits).resultsCount(searchResult.getTotal()).duration(multiSearch.tookMsFromSearchResult(searchResult)).usedIndexNames(affectedIndices).executedQuery(searchSourceBuilder.toString()).build();
}
Also used : MoreSearchAdapter(org.graylog.events.search.MoreSearchAdapter) Stopwatch(com.google.common.base.Stopwatch) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) ScrollResult(org.graylog2.indexer.results.ScrollResult) Inject(javax.inject.Inject) Sort(io.searchbox.core.search.sort.Sort) ResultMessage(org.graylog2.indexer.results.ResultMessage) Map(java.util.Map) Objects.requireNonNull(java.util.Objects.requireNonNull) Named(javax.inject.Named) EventProcessorException(org.graylog.events.processor.EventProcessorException) IndexMapping(org.graylog2.indexer.IndexMapping) TimeRange(org.graylog2.plugin.indexer.searches.timeranges.TimeRange) QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) Sorting(org.graylog2.indexer.searches.Sorting) Logger(org.slf4j.Logger) EventDto(org.graylog.events.event.EventDto) Search(io.searchbox.core.Search) Set(java.util.Set) QueryBuilders.matchAllQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.matchAllQuery) IOException(java.io.IOException) QueryBuilders.termsQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.termsQuery) Collectors(java.util.stream.Collectors) MoreSearch(org.graylog.events.search.MoreSearch) UncheckedIOException(java.io.UncheckedIOException) TimeUnit(java.util.concurrent.TimeUnit) QueryBuilders.queryStringQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.queryStringQuery) List(java.util.List) Parameters(io.searchbox.params.Parameters) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) ToXContent(org.graylog.shaded.elasticsearch6.org.elasticsearch.common.xcontent.ToXContent) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) QueryBuilders.boolQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.boolQuery) QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) Search(io.searchbox.core.Search) MoreSearch(org.graylog.events.search.MoreSearch) Map(java.util.Map)

Example 19 with SearchResult

use of org.graylog2.indexer.results.SearchResult in project graylog2-server by Graylog2.

the class SearchesAdapterES6 method search.

@Override
public SearchResult search(Set<String> indices, Set<IndexRange> indexRanges, SearchesConfig config) {
    final SearchSourceBuilder requestBuilder = searchRequest(config);
    if (indexRanges.isEmpty()) {
        return SearchResult.empty(config.query(), requestBuilder.toString());
    }
    final Search.Builder searchBuilder = new Search.Builder(requestBuilder.toString()).addType(IndexMapping.TYPE_MESSAGE).addIndex(indices);
    final io.searchbox.core.SearchResult searchResult = multiSearch.wrap(searchBuilder.build(), () -> "Unable to perform search query");
    final List<ResultMessage> hits = searchResult.getHits(Map.class, false).stream().map(hit -> ResultMessage.parseFromSource(hit.id, hit.index, (Map<String, Object>) hit.source, hit.highlight)).collect(Collectors.toList());
    return new SearchResult(hits, searchResult.getTotal(), indexRanges, config.query(), requestBuilder.toString(), multiSearch.tookMsFromSearchResult(searchResult));
}
Also used : FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) NO_LIMIT(org.graylog2.indexer.searches.ScrollCommand.NO_LIMIT) FieldStatsResult(org.graylog2.indexer.results.FieldStatsResult) SearchesConfig(org.graylog2.indexer.searches.SearchesConfig) Strings.isNullOrEmpty(com.google.common.base.Strings.isNullOrEmpty) ScrollResult(org.graylog2.indexer.results.ScrollResult) SearchesAdapter(org.graylog2.indexer.searches.SearchesAdapter) QueryBuilders.existsQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.existsQuery) Inject(javax.inject.Inject) ScrollCommand(org.graylog2.indexer.searches.ScrollCommand) ResultMessage(org.graylog2.indexer.results.ResultMessage) Map(java.util.Map) CardinalityAggregation(io.searchbox.core.search.aggregation.CardinalityAggregation) IndexMapping(org.graylog2.indexer.IndexMapping) SearchResult(org.graylog2.indexer.results.SearchResult) TimeRange(org.graylog2.plugin.indexer.searches.timeranges.TimeRange) QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) Nullable(javax.annotation.Nullable) QueryBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders) HighlightBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) Sorting(org.graylog2.indexer.searches.Sorting) NO_BATCHSIZE(org.graylog2.indexer.searches.ScrollCommand.NO_BATCHSIZE) Search(io.searchbox.core.Search) Set(java.util.Set) QueryBuilders.matchAllQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.matchAllQuery) QueryBuilders.termsQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.termsQuery) ValueCountAggregation(io.searchbox.core.search.aggregation.ValueCountAggregation) Collectors(java.util.stream.Collectors) ExtendedStatsAggregation(io.searchbox.core.search.aggregation.ExtendedStatsAggregation) Strings(org.graylog.shaded.elasticsearch6.org.elasticsearch.common.Strings) IndexRange(org.graylog2.indexer.ranges.IndexRange) CountResult(org.graylog2.indexer.results.CountResult) QueryBuilders.queryStringQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.queryStringQuery) List(java.util.List) Parameters(io.searchbox.params.Parameters) Configuration(org.graylog2.Configuration) Stream(org.graylog2.plugin.streams.Stream) AggregationBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.AggregationBuilders) Optional(java.util.Optional) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(org.graylog2.plugin.Message) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) QueryBuilders.boolQuery(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.boolQuery) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) QueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilder) HighlightBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(org.graylog2.indexer.results.SearchResult) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) Search(io.searchbox.core.Search) Map(java.util.Map)

Example 20 with SearchResult

use of org.graylog2.indexer.results.SearchResult in project graylog2-server by Graylog2.

the class ESMessageList method doExtractResult.

@Override
public SearchType.Result doExtractResult(SearchJob job, Query query, MessageList searchType, SearchResult result, MetricAggregation aggregations, ESGeneratedQueryContext queryContext) {
    // noinspection unchecked
    final List<ResultMessageSummary> messages = result.getHits(Map.class, false).stream().map(hit -> ResultMessage.parseFromSource(hit.id, hit.index, (Map<String, Object>) hit.source, hit.highlight)).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.getTotal(), 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 : ESGeneratedQueryContext(org.graylog.storage.elasticsearch6.views.ESGeneratedQueryContext) Query(org.graylog.plugins.views.search.Query) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) SortOrder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.SortOrder) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) Inject(javax.inject.Inject) SortBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.SortBuilders) 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) AbsoluteRange(org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange) MessageList(org.graylog.plugins.views.search.searchtypes.MessageList) LegacyDecoratorProcessor(org.graylog.plugins.views.search.LegacyDecoratorProcessor) QueryBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders) HighlightBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder) SearchJob(org.graylog.plugins.views.search.SearchJob) DateTime(org.joda.time.DateTime) QueryStringQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryStringQueryBuilder) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) QueryStringDecorators(org.graylog.plugins.views.search.elasticsearch.QueryStringDecorators) MetricAggregation(io.searchbox.core.search.aggregation.MetricAggregation) Optional(java.util.Optional) Named(com.google.inject.name.Named) MoreObjects.firstNonNull(com.google.common.base.MoreObjects.firstNonNull) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) Map(java.util.Map) DateTime(org.joda.time.DateTime) ResultMessageSummary(org.graylog2.rest.models.messages.responses.ResultMessageSummary) SearchResponse(org.graylog2.rest.resources.search.responses.SearchResponse) SearchResult(io.searchbox.core.SearchResult)

Aggregations

SearchResult (org.graylog2.indexer.results.SearchResult)11 DateTime (org.joda.time.DateTime)11 ResultMessage (org.graylog2.indexer.results.ResultMessage)10 Inject (javax.inject.Inject)8 AbsoluteRange (org.graylog2.plugin.indexer.searches.timeranges.AbsoluteRange)8 List (java.util.List)7 Optional (java.util.Optional)7 SearchSourceBuilder (org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)7 Sorting (org.graylog2.indexer.searches.Sorting)7 Message (org.graylog2.plugin.Message)7 Test (org.junit.Test)7 Search (io.searchbox.core.Search)6 SearchResult (io.searchbox.core.SearchResult)6 Map (java.util.Map)6 Set (java.util.Set)6 RelativeRange (org.graylog2.plugin.indexer.searches.timeranges.RelativeRange)6 Collectors (java.util.stream.Collectors)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 ImmutableList (com.google.common.collect.ImmutableList)4