Search in sources :

Example 41 with SearchRequestBuilder

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

the class Indices method indexRangeStatsOfIndex.

/**
     * Calculate min and max message timestamps in the given index.
     *
     * @param index Name of the index to query.
     * @return the timestamp stats in the given index, or {@code null} if they couldn't be calculated.
     * @see org.elasticsearch.search.aggregations.metrics.stats.Stats
     */
public IndexRangeStats indexRangeStatsOfIndex(String index) {
    final FilterAggregationBuilder builder = AggregationBuilders.filter("agg").filter(QueryBuilders.existsQuery("timestamp")).subAggregation(AggregationBuilders.min("ts_min").field("timestamp")).subAggregation(AggregationBuilders.max("ts_max").field("timestamp")).subAggregation(AggregationBuilders.terms("streams").field("streams"));
    final SearchRequestBuilder srb = c.prepareSearch().setIndices(index).setSearchType(SearchType.QUERY_THEN_FETCH).setSize(0).addAggregation(builder);
    final SearchResponse response;
    try {
        final SearchRequest request = srb.request();
        if (LOG.isDebugEnabled()) {
            LOG.debug("Index range query: _search/{}: {}", index, XContentHelper.convertToJson(request.source(), false));
        }
        response = c.search(request).actionGet();
    } catch (IndexClosedException e) {
        throw e;
    } catch (org.elasticsearch.index.IndexNotFoundException e) {
        LOG.error("Error while calculating timestamp stats in index <" + index + ">", e);
        throw e;
    } catch (ElasticsearchException e) {
        LOG.error("Error while calculating timestamp stats in index <" + index + ">", e);
        throw new org.elasticsearch.index.IndexNotFoundException("Index " + index + " not found", e);
    } catch (IOException e) {
        // the index range aggregation query on DEBUG (via XContentHelper)
        throw new RuntimeException(e);
    }
    final Filter f = response.getAggregations().get("agg");
    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 DateTime min = new DateTime((long) minAgg.getValue(), DateTimeZone.UTC);
    final Max maxAgg = f.getAggregations().get("ts_max");
    final DateTime max = new DateTime((long) maxAgg.getValue(), 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.
    ImmutableList.Builder<String> streamIds = ImmutableList.builder();
    final Terms streams = f.getAggregations().get("streams");
    if (!streams.getBuckets().isEmpty()) {
        streamIds.addAll(streams.getBuckets().stream().map(Terms.Bucket::getKeyAsString).collect(toSet()));
    }
    return IndexRangeStats.create(min, max, streamIds.build());
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) FilterAggregationBuilder(org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) Max(org.elasticsearch.search.aggregations.metrics.max.Max) ImmutableList(com.google.common.collect.ImmutableList) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) ElasticsearchException(org.elasticsearch.ElasticsearchException) IOException(java.io.IOException) DateTime(org.joda.time.DateTime) SearchResponse(org.elasticsearch.action.search.SearchResponse) Min(org.elasticsearch.search.aggregations.metrics.min.Min) IndexClosedException(org.elasticsearch.indices.IndexClosedException) Filter(org.elasticsearch.search.aggregations.bucket.filter.Filter)

Example 42 with SearchRequestBuilder

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

the class Searches method fieldHistogram.

public HistogramResult fieldHistogram(String query, String field, DateHistogramInterval interval, String filter, TimeRange range, boolean includeCardinality) throws FieldTypeException {
    final DateHistogramBuilder dateHistogramBuilder = AggregationBuilders.dateHistogram(AGG_HISTOGRAM).field("timestamp").subAggregation(AggregationBuilders.stats(AGG_STATS).field(field)).interval(interval.toESInterval());
    if (includeCardinality) {
        dateHistogramBuilder.subAggregation(AggregationBuilders.cardinality(AGG_CARDINALITY).field(field));
    }
    FilterAggregationBuilder builder = AggregationBuilders.filter(AGG_FILTER).subAggregation(dateHistogramBuilder).filter(standardAggregationFilters(range, filter));
    QueryStringQueryBuilder qs = queryStringQuery(query);
    qs.allowLeadingWildcard(configuration.isAllowLeadingWildcardSearches());
    SearchRequestBuilder srb = c.prepareSearch();
    final Set<String> affectedIndices = determineAffectedIndices(range, filter);
    srb.setIndices(affectedIndices.toArray(new String[affectedIndices.size()]));
    srb.setQuery(qs);
    srb.addAggregation(builder);
    SearchResponse r;
    final SearchRequest request = srb.request();
    try {
        r = c.search(request).actionGet();
    } catch (org.elasticsearch.action.search.SearchPhaseExecutionException e) {
        throw new FieldTypeException(e);
    }
    checkForFailedShards(r);
    recordEsMetrics(r, range);
    final Filter f = r.getAggregations().get(AGG_FILTER);
    return new FieldHistogramResult(f.getAggregations().get(AGG_HISTOGRAM), query, request.source(), interval, r.getTook());
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) FilterAggregationBuilder(org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) Filter(org.elasticsearch.search.aggregations.bucket.filter.Filter) QueryStringQueryBuilder(org.elasticsearch.index.query.QueryStringQueryBuilder) FieldHistogramResult(org.graylog2.indexer.results.FieldHistogramResult) DateHistogramBuilder(org.elasticsearch.search.aggregations.bucket.histogram.DateHistogramBuilder)

Example 43 with SearchRequestBuilder

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

the class Searches method termsStats.

public TermsStatsResult termsStats(String keyField, String valueField, TermsStatsOrder order, int size, String query, String filter, TimeRange range) {
    if (size == 0) {
        size = 50;
    }
    SearchRequestBuilder srb;
    if (filter == null) {
        srb = standardSearchRequest(query, determineAffectedIndices(range, filter), range);
    } else {
        srb = filteredSearchRequest(query, filter, determineAffectedIndices(range, filter), range);
    }
    Terms.Order termsOrder;
    switch(order) {
        case COUNT:
            termsOrder = Terms.Order.count(true);
            break;
        case REVERSE_COUNT:
            termsOrder = Terms.Order.count(false);
            break;
        case TERM:
            termsOrder = Terms.Order.term(true);
            break;
        case REVERSE_TERM:
            termsOrder = Terms.Order.term(false);
            break;
        case MIN:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "min", true);
            break;
        case REVERSE_MIN:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "min", false);
            break;
        case MAX:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "max", true);
            break;
        case REVERSE_MAX:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "max", false);
            break;
        case MEAN:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "avg", true);
            break;
        case REVERSE_MEAN:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "avg", false);
            break;
        case TOTAL:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "sum", true);
            break;
        case REVERSE_TOTAL:
            termsOrder = Terms.Order.aggregation(AGG_STATS, "sum", false);
            break;
        default:
            termsOrder = Terms.Order.count(true);
    }
    FilterAggregationBuilder builder = AggregationBuilders.filter(AGG_FILTER).subAggregation(AggregationBuilders.terms(AGG_TERMS_STATS).field(keyField).subAggregation(AggregationBuilders.stats(AGG_STATS).field(valueField)).order(termsOrder).size(size)).filter(standardAggregationFilters(range, filter));
    srb.addAggregation(builder);
    final SearchRequest request = srb.request();
    SearchResponse r = c.search(request).actionGet();
    recordEsMetrics(r, range);
    final Filter f = r.getAggregations().get(AGG_FILTER);
    return new TermsStatsResult(f.getAggregations().get(AGG_TERMS_STATS), query, request.source(), r.getTook());
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) FilterAggregationBuilder(org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) Filter(org.elasticsearch.search.aggregations.bucket.filter.Filter) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) TermsStatsResult(org.graylog2.indexer.results.TermsStatsResult) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 44 with SearchRequestBuilder

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

the class Searches method fieldStats.

public FieldStatsResult fieldStats(String field, String query, String filter, TimeRange range, boolean includeCardinality, boolean includeStats, boolean includeCount) throws FieldTypeException {
    SearchRequestBuilder srb;
    final Set<String> indices = indicesContainingField(determineAffectedIndices(range, filter), field);
    if (filter == null) {
        srb = standardSearchRequest(query, indices, range);
    } else {
        srb = filteredSearchRequest(query, filter, indices, range);
    }
    FilterAggregationBuilder builder = AggregationBuilders.filter(AGG_FILTER).filter(standardAggregationFilters(range, filter));
    if (includeCount) {
        builder.subAggregation(AggregationBuilders.count(AGG_VALUE_COUNT).field(field));
    }
    if (includeStats) {
        builder.subAggregation(AggregationBuilders.extendedStats(AGG_EXTENDED_STATS).field(field));
    }
    if (includeCardinality) {
        builder.subAggregation(AggregationBuilders.cardinality(AGG_CARDINALITY).field(field));
    }
    srb.addAggregation(builder);
    SearchResponse r;
    final SearchRequest request;
    try {
        request = srb.request();
        r = c.search(request).actionGet();
    } catch (org.elasticsearch.action.search.SearchPhaseExecutionException e) {
        throw new FieldTypeException(e);
    }
    checkForFailedShards(r);
    recordEsMetrics(r, range);
    final Filter f = r.getAggregations().get(AGG_FILTER);
    return new FieldStatsResult(f.getAggregations().get(AGG_VALUE_COUNT), f.getAggregations().get(AGG_EXTENDED_STATS), f.getAggregations().get(AGG_CARDINALITY), r.getHits(), query, request.source(), r.getTook());
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) FieldStatsResult(org.graylog2.indexer.results.FieldStatsResult) FilterAggregationBuilder(org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) Filter(org.elasticsearch.search.aggregations.bucket.filter.Filter) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 45 with SearchRequestBuilder

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

the class Searches method standardSearchRequest.

private SearchRequestBuilder standardSearchRequest(String query, Set<String> indices, int limit, int offset, TimeRange range, String filter, Sorting sort, boolean highlight) {
    if (query == null || query.trim().isEmpty()) {
        query = "*";
    }
    final QueryBuilder queryBuilder;
    if ("*".equals(query.trim())) {
        queryBuilder = matchAllQuery();
    } else {
        queryBuilder = queryStringQuery(query).allowLeadingWildcard(configuration.isAllowLeadingWildcardSearches());
    }
    final SearchRequestBuilder srb = c.prepareSearch(indices.toArray(new String[indices.size()])).setIndicesOptions(IndicesOptions.lenientExpandOpen()).setQuery(QueryBuilders.boolQuery().must(queryBuilder).filter(standardFilters(range, filter))).setFrom(offset);
    if (limit > 0) {
        srb.setSize(limit);
    }
    if (sort != null) {
        srb.addSort(sort.getField(), sort.asElastic());
    }
    if (highlight && configuration.isAllowHighlighting()) {
        srb.setHighlighterRequireFieldMatch(false);
        srb.addHighlightedField("*", 0, 0);
    }
    return srb;
}
Also used : SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) BoolQueryBuilder(org.elasticsearch.index.query.BoolQueryBuilder) QueryStringQueryBuilder(org.elasticsearch.index.query.QueryStringQueryBuilder) QueryBuilder(org.elasticsearch.index.query.QueryBuilder)

Aggregations

SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)110 SearchResponse (org.elasticsearch.action.search.SearchResponse)66 SearchHit (org.elasticsearch.search.SearchHit)23 SearchHits (org.elasticsearch.search.SearchHits)18 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)17 ArrayList (java.util.ArrayList)14 Client (org.elasticsearch.client.Client)13 HashMap (java.util.HashMap)12 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)12 Test (org.junit.Test)12 SearchRequest (org.elasticsearch.action.search.SearchRequest)11 IndexRequestBuilder (org.elasticsearch.action.index.IndexRequestBuilder)10 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)9 FilterAggregationBuilder (org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder)9 Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)9 SearchPhaseExecutionException (org.elasticsearch.action.search.SearchPhaseExecutionException)8 Filter (org.elasticsearch.search.aggregations.bucket.filter.Filter)8 Map (java.util.Map)7 BulkRequestBuilder (org.elasticsearch.action.bulk.BulkRequestBuilder)7 MultiSearchResponse (org.elasticsearch.action.search.MultiSearchResponse)7