Search in sources :

Example 36 with FilterAggregationBuilder

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder in project graylog2-server by Graylog2.

the class SearchesAdapterES6 method fieldStats.

@Override
public FieldStatsResult fieldStats(String query, String filter, TimeRange range, Set<String> indices, String field, boolean includeCardinality, boolean includeStats, boolean includeCount) {
    final SearchSourceBuilder searchSourceBuilder;
    if (filter == null) {
        searchSourceBuilder = standardSearchRequest(query, range);
    } else {
        searchSourceBuilder = filteredSearchRequest(query, filter, range);
    }
    final FilterAggregationBuilder filterBuilder = AggregationBuilders.filter(AGG_FILTER, standardAggregationFilters(range, filter));
    if (includeCount) {
        searchSourceBuilder.aggregation(AggregationBuilders.count(AGG_VALUE_COUNT).field(field));
    }
    if (includeStats) {
        searchSourceBuilder.aggregation(AggregationBuilders.extendedStats(AGG_EXTENDED_STATS).field(field));
    }
    if (includeCardinality) {
        searchSourceBuilder.aggregation(AggregationBuilders.cardinality(AGG_CARDINALITY).field(field));
    }
    searchSourceBuilder.aggregation(filterBuilder);
    if (indices.isEmpty()) {
        return FieldStatsResult.empty(query, searchSourceBuilder.toString());
    }
    final Search searchRequest = new Search.Builder(searchSourceBuilder.toString()).addType(IndexMapping.TYPE_MESSAGE).addIndex(indices).build();
    final io.searchbox.core.SearchResult searchResponse = multiSearch.wrap(searchRequest, () -> "Unable to retrieve fields stats");
    final List<ResultMessage> hits = searchResponse.getHits(Map.class, false).stream().map(hit -> ResultMessage.parseFromSource(hit.id, hit.index, (Map<String, Object>) hit.source)).collect(Collectors.toList());
    final ExtendedStatsAggregation extendedStatsAggregation = searchResponse.getAggregations().getExtendedStatsAggregation(AGG_EXTENDED_STATS);
    final ValueCountAggregation valueCountAggregation = searchResponse.getAggregations().getValueCountAggregation(AGG_VALUE_COUNT);
    final CardinalityAggregation cardinalityAggregation = searchResponse.getAggregations().getCardinalityAggregation(AGG_CARDINALITY);
    return createFieldStatsResult(valueCountAggregation, extendedStatsAggregation, cardinalityAggregation, hits, query, searchSourceBuilder.toString(), multiSearch.tookMsFromSearchResult(searchResponse));
}
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) ExtendedStatsAggregation(io.searchbox.core.search.aggregation.ExtendedStatsAggregation) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) CardinalityAggregation(io.searchbox.core.search.aggregation.CardinalityAggregation) ResultMessage(org.graylog2.indexer.results.ResultMessage) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) ValueCountAggregation(io.searchbox.core.search.aggregation.ValueCountAggregation) Search(io.searchbox.core.Search) Map(java.util.Map)

Example 37 with FilterAggregationBuilder

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder in project graylog2-server by Graylog2.

the class IndicesAdapterES7 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 SearchSourceBuilder query = SearchSourceBuilder.searchSource().aggregation(builder).size(0);
    final SearchRequest request = new SearchRequest().source(query).indices(index).searchType(SearchType.DFS_QUERY_THEN_FETCH).indicesOptions(IndicesOptions.lenientExpandOpen());
    final SearchResponse result = client.execute((c, requestOptions) -> c.search(request, requestOptions), "Couldn't build index range of index " + index);
    if (result.getTotalShards() == 0 || result.getAggregations() == null) {
        throw new IndexNotFoundException("Couldn't build index range of index " + index + " because it doesn't exist.");
    }
    final Filter f = result.getAggregations().get("agg");
    if (f == null) {
        throw new IndexNotFoundException("Couldn't build index range of index " + index + " because it doesn't exist.");
    } else if (f.getDocCount() == 0L) {
        LOG.debug("No documents with attribute \"timestamp\" found in index <{}>", index);
        return IndexRangeStats.EMPTY;
    }
    final Min minAgg = f.getAggregations().get("ts_min");
    final long minUnixTime = new Double(minAgg.getValue()).longValue();
    final DateTime min = new DateTime(minUnixTime, DateTimeZone.UTC);
    final Max maxAgg = f.getAggregations().get("ts_max");
    final long maxUnixTime = new Double(maxAgg.getValue()).longValue();
    final DateTime max = new DateTime(maxUnixTime, 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 Terms streams = f.getAggregations().get("streams");
    final List<String> streamIds = streams.getBuckets().stream().map(MultiBucketsAggregation.Bucket::getKeyAsString).collect(toList());
    return IndexRangeStats.create(min, max, streamIds);
}
Also used : SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) FilterAggregationBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) Max(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.metrics.Max) Terms(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.terms.Terms) DateTime(org.joda.time.DateTime) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse) Min(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.metrics.Min) Filter(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.Filter) MultiBucketsAggregation(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.MultiBucketsAggregation) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException)

Example 38 with FilterAggregationBuilder

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder in project graylog2-server by Graylog2.

the class IndexToolsAdapterES7 method fieldHistogram.

@Override
public Map<DateTime, Map<String, Long>> fieldHistogram(String fieldName, Set<String> indices, Optional<Set<String>> includedStreams, long interval) {
    final BoolQueryBuilder queryBuilder = buildStreamIdFilter(includedStreams);
    final FilterAggregationBuilder the_filter = AggregationBuilders.filter(AGG_FILTER, queryBuilder).subAggregation(AggregationBuilders.dateHistogram(AGG_DATE_HISTOGRAM).field("timestamp").subAggregation(AggregationBuilders.terms(AGG_MESSAGE_FIELD).field(fieldName)).fixedInterval(new DateHistogramInterval(interval + "ms")).minDocCount(1L));
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).aggregation(the_filter);
    final SearchRequest searchRequest = new SearchRequest().source(searchSourceBuilder).indices(indices.toArray(new String[0]));
    final SearchResponse searchResult = client.search(searchRequest, "Unable to retrieve field histogram.");
    final Filter filterAggregation = searchResult.getAggregations().get(AGG_FILTER);
    final ParsedDateHistogram dateHistogram = filterAggregation.getAggregations().get(AGG_DATE_HISTOGRAM);
    final List<ParsedDateHistogram.ParsedBucket> histogramBuckets = (List<ParsedDateHistogram.ParsedBucket>) dateHistogram.getBuckets();
    final Map<DateTime, Map<String, Long>> result = Maps.newHashMapWithExpectedSize(histogramBuckets.size());
    for (ParsedDateHistogram.ParsedBucket bucket : histogramBuckets) {
        final ZonedDateTime zonedDateTime = (ZonedDateTime) bucket.getKey();
        final DateTime date = new DateTime(zonedDateTime.toInstant().toEpochMilli()).toDateTime(DateTimeZone.UTC);
        final Terms sourceFieldAgg = bucket.getAggregations().get(AGG_MESSAGE_FIELD);
        final List<? extends Terms.Bucket> termBuckets = sourceFieldAgg.getBuckets();
        final HashMap<String, Long> termCounts = Maps.newHashMapWithExpectedSize(termBuckets.size());
        for (Terms.Bucket termBucket : termBuckets) {
            termCounts.put(termBucket.getKeyAsString(), termBucket.getDocCount());
        }
        result.put(date, termCounts);
    }
    return ImmutableMap.copyOf(result);
}
Also used : SearchRequest(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchRequest) FilterAggregationBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) ParsedDateHistogram(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.histogram.ParsedDateHistogram) Terms(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.terms.Terms) DateHistogramInterval(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramInterval) ZonedDateTime(java.time.ZonedDateTime) DateTime(org.joda.time.DateTime) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.graylog.shaded.elasticsearch7.org.elasticsearch.action.search.SearchResponse) BoolQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.BoolQueryBuilder) Filter(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.aggregations.bucket.filter.Filter) ZonedDateTime(java.time.ZonedDateTime) List(java.util.List) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Aggregations

FilterAggregationBuilder (org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder)33 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)15 TermsAggregationBuilder (org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder)8 Map (java.util.Map)6 SearchRequest (org.elasticsearch.action.search.SearchRequest)6 SearchResponse (org.elasticsearch.action.search.SearchResponse)6 Test (org.junit.Test)6 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)5 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)5 AggregationBuilder (org.elasticsearch.search.aggregations.AggregationBuilder)5 Filter (org.elasticsearch.search.aggregations.bucket.filter.Filter)5 Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)5 DateTime (org.joda.time.DateTime)5 Search (io.searchbox.core.Search)3 Arrays (java.util.Arrays)3 List (java.util.List)3 Objects (java.util.Objects)3 Collectors (java.util.stream.Collectors)3 Nullable (javax.annotation.Nullable)3 ImmutableMap (com.google.common.collect.ImmutableMap)2