Search in sources :

Example 66 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project graylog2-server by Graylog2.

the class ElasticsearchExportBackend method searchSourceBuilderFrom.

private SearchSourceBuilder searchSourceBuilderFrom(ExportMessagesCommand command) {
    QueryBuilder query = queryFrom(command);
    SearchSourceBuilder ssb = new SearchSourceBuilder().query(query).size(command.chunkSize()).sort(Message.FIELD_TIMESTAMP, SortOrder.ASC);
    return requestStrategy.configure(ssb);
}
Also used : QueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.QueryBuilder) TermsQueryBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.index.query.TermsQueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder)

Example 67 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project graylog2-server by Graylog2.

the class QuerySuggestionsES6 method suggest.

@Override
public SuggestionResponse suggest(SuggestionRequest req) {
    final Set<String> affectedIndices = indexLookup.indexNamesForStreamsInTimeRange(req.streams(), req.timerange());
    final SearchSourceBuilder search = new SearchSourceBuilder().query(QueryBuilders.prefixQuery(req.field(), req.input())).size(0).aggregation(AggregationBuilders.terms("fieldvalues").field(req.field()).size(req.size())).suggest(new SuggestBuilder().addSuggestion("corrections", SuggestBuilders.termSuggestion(req.field()).text(req.input()).size(req.size())));
    final Search.Builder searchBuilder = new Search.Builder(search.toString()).addType(IndexMapping.TYPE_MESSAGE).addIndex(affectedIndices.isEmpty() ? Collections.singleton("") : affectedIndices).allowNoIndices(false).ignoreUnavailable(false);
    try {
        final SearchResult result = JestUtils.execute(jestClient, searchBuilder.build(), () -> "Unable to perform aggregation: ");
        final TermsAggregation aggregation = result.getAggregations().getTermsAggregation("fieldvalues");
        final List<SuggestionEntry> entries = aggregation.getBuckets().stream().map(b -> new SuggestionEntry(b.getKeyAsString(), b.getCount())).collect(Collectors.toList());
        if (!entries.isEmpty()) {
            return SuggestionResponse.forSuggestions(req.field(), req.input(), entries, aggregation.getSumOtherDocCount());
        } else {
            final List<SuggestionEntry> corrections = Optional.of(result.getJsonObject()).map(o -> o.get("suggest")).map(o -> o.get("corrections")).map(o -> o.get(0)).map(o -> o.get("options")).map(options -> StreamSupport.stream(Spliterators.spliteratorUnknownSize(options.elements(), Spliterator.ORDERED), false).map(option -> new SuggestionEntry(option.get("text").textValue(), option.get("freq").longValue())).collect(Collectors.toList())).orElseGet(Collections::emptyList);
            return SuggestionResponse.forSuggestions(req.field(), req.input(), corrections, null);
        }
    } catch (Exception e) {
        final SuggestionError err = SuggestionError.create(e.getClass().getSimpleName(), e.getMessage());
        return SuggestionResponse.forError(req.field(), req.input(), err);
    }
}
Also used : TermsAggregation(io.searchbox.core.search.aggregation.TermsAggregation) SuggestBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.suggest.SuggestBuilder) SuggestionEntry(org.graylog.plugins.views.search.engine.suggestions.SuggestionEntry) Spliterators(java.util.Spliterators) JestClient(io.searchbox.client.JestClient) Inject(javax.inject.Inject) JestUtils(org.graylog.storage.elasticsearch6.jest.JestUtils) StreamSupport(java.util.stream.StreamSupport) SuggestionResponse(org.graylog.plugins.views.search.engine.suggestions.SuggestionResponse) IndexMapping(org.graylog2.indexer.IndexMapping) SuggestionError(org.graylog.plugins.views.search.engine.suggestions.SuggestionError) QueryBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders) Search(io.searchbox.core.Search) Set(java.util.Set) SuggestBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.suggest.SuggestBuilders) SuggestionRequest(org.graylog.plugins.views.search.engine.suggestions.SuggestionRequest) Collectors(java.util.stream.Collectors) List(java.util.List) QuerySuggestionsService(org.graylog.plugins.views.search.engine.QuerySuggestionsService) AggregationBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.AggregationBuilders) Optional(java.util.Optional) IndexLookup(org.graylog.plugins.views.search.elasticsearch.IndexLookup) Collections(java.util.Collections) Spliterator(java.util.Spliterator) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) TermsAggregation(io.searchbox.core.search.aggregation.TermsAggregation) SuggestBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.suggest.SuggestBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SuggestBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.suggest.SuggestBuilder) SuggestionError(org.graylog.plugins.views.search.engine.suggestions.SuggestionError) Search(io.searchbox.core.Search) Collections(java.util.Collections) SuggestionEntry(org.graylog.plugins.views.search.engine.suggestions.SuggestionEntry)

Example 68 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project graylog2-server by Graylog2.

the class IndexToolsAdapterES6 method count.

@Override
public long count(Set<String> indices, Optional<Set<String>> includedStreams) {
    final SearchSourceBuilder queryBuilder = new SearchSourceBuilder().query(buildStreamIdFilter(includedStreams));
    final Count.Builder builder = new Count.Builder().query(queryBuilder.toString()).addIndex(indices).addType(IndexMapping.TYPE_MESSAGE).setParameter(Parameters.IGNORE_UNAVAILABLE, true);
    final CountResult result = JestUtils.execute(jestClient, builder.build(), () -> "Unable to count documents of index.");
    return result.getCount().longValue();
}
Also used : FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) Count(io.searchbox.core.Count) CountResult(io.searchbox.core.CountResult) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)

Example 69 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project graylog2-server by Graylog2.

the class IndexToolsAdapterES6 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)).interval(interval).minDocCount(1L));
    final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).aggregation(the_filter);
    final Search.Builder searchBuilder = new Search.Builder(searchSourceBuilder.toString()).addIndex(indices).addType(IndexMapping.TYPE_MESSAGE);
    final SearchResult searchResult = JestUtils.execute(this.jestClient, searchBuilder.build(), () -> "Unable to retrieve field histogram.");
    final FilterAggregation filterAggregation = searchResult.getAggregations().getFilterAggregation(AGG_FILTER);
    final DateHistogramAggregation dateHistogram = filterAggregation.getDateHistogramAggregation(AGG_DATE_HISTOGRAM);
    final List<DateHistogramAggregation.DateHistogram> histogramBuckets = dateHistogram.getBuckets();
    final Map<DateTime, Map<String, Long>> result = Maps.newHashMapWithExpectedSize(histogramBuckets.size());
    for (HistogramAggregation.Histogram bucket : histogramBuckets) {
        final DateTime date = new DateTime(bucket.getKey()).toDateTime(DateTimeZone.UTC);
        final TermsAggregation sourceFieldAgg = bucket.getTermsAggregation(AGG_MESSAGE_FIELD);
        final List<TermsAggregation.Entry> termBuckets = sourceFieldAgg.getBuckets();
        final HashMap<String, Long> termCounts = Maps.newHashMapWithExpectedSize(termBuckets.size());
        for (TermsAggregation.Entry termBucket : termBuckets) {
            termCounts.put(termBucket.getKeyAsString(), termBucket.getCount());
        }
        result.put(date, termCounts);
    }
    return ImmutableMap.copyOf(result);
}
Also used : TermsAggregation(io.searchbox.core.search.aggregation.TermsAggregation) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) DateTime(org.joda.time.DateTime) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) HistogramAggregation(io.searchbox.core.search.aggregation.HistogramAggregation) DateHistogramAggregation(io.searchbox.core.search.aggregation.DateHistogramAggregation) BoolQueryBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.BoolQueryBuilder) Search(io.searchbox.core.Search) FilterAggregation(io.searchbox.core.search.aggregation.FilterAggregation) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) DateHistogramAggregation(io.searchbox.core.search.aggregation.DateHistogramAggregation)

Example 70 with SearchSourceBuilder

use of org.elasticsearch.search.builder.SearchSourceBuilder in project graylog2-server by Graylog2.

the class ESMessageList method doGenerateQueryPart.

@Override
public void doGenerateQueryPart(SearchJob job, Query query, MessageList messageList, ESGeneratedQueryContext queryContext) {
    final SearchSourceBuilder searchSourceBuilder = queryContext.searchSourceBuilder(messageList).size(messageList.limit()).from(messageList.offset());
    applyHighlightingIfActivated(searchSourceBuilder, job, query);
    final Set<String> effectiveStreamIds = messageList.effectiveStreams().isEmpty() ? query.usedStreamIds() : messageList.effectiveStreams();
    if (!messageList.fields().isEmpty()) {
        searchSourceBuilder.fetchSource(messageList.fields().toArray(new String[0]), new String[0]);
    }
    final List<Sort> sorts = firstNonNull(messageList.sort(), Collections.singletonList(Sort.create(Message.FIELD_TIMESTAMP, Sort.Order.DESC)));
    sorts.forEach(sort -> {
        final FieldSortBuilder fieldSort = SortBuilders.fieldSort(sort.field()).order(toSortOrder(sort.order()));
        final Optional<String> fieldType = queryContext.fieldType(effectiveStreamIds, sort.field());
        searchSourceBuilder.sort(fieldType.map(fieldSort::unmappedType).orElse(fieldSort));
    });
}
Also used : Sort(org.graylog.plugins.views.search.searchtypes.Sort) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)

Aggregations

SearchSourceBuilder (org.elasticsearch.search.builder.SearchSourceBuilder)152 SearchResponse (org.elasticsearch.action.search.SearchResponse)77 SearchRequest (org.elasticsearch.action.search.SearchRequest)52 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)37 Matchers.containsString (org.hamcrest.Matchers.containsString)32 IOException (java.io.IOException)31 QueryBuilder (org.elasticsearch.index.query.QueryBuilder)28 BoolQueryBuilder (org.elasticsearch.index.query.BoolQueryBuilder)26 List (java.util.List)25 SearchSourceBuilder (org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)24 SearchSourceBuilder (org.graylog.shaded.elasticsearch7.org.elasticsearch.search.builder.SearchSourceBuilder)24 Search (io.searchbox.core.Search)23 Map (java.util.Map)23 Set (java.util.Set)19 ArrayList (java.util.ArrayList)18 Collectors (java.util.stream.Collectors)18 Test (org.junit.Test)18 Collections (java.util.Collections)15 SearchHit (org.elasticsearch.search.SearchHit)15 TermsAggregationBuilder (org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder)15