Search in sources :

Example 1 with QueryBuilders.matchAllQuery

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.matchAllQuery 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 2 with QueryBuilders.matchAllQuery

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.matchAllQuery in project graylog2-server by Graylog2.

the class IndicesAdapterES6 method move.

@Override
public void move(String source, String target, Consumer<IndexMoveResult> resultCallback) {
    // TODO: This method should use the Re-index API: https://www.elastic.co/guide/en/elasticsearch/reference/5.3/docs-reindex.html
    final String query = SearchSourceBuilder.searchSource().query(QueryBuilders.matchAllQuery()).size(350).sort(SortBuilders.fieldSort(FieldSortBuilder.DOC_FIELD_NAME)).toString();
    final Search request = new Search.Builder(query).setParameter(Parameters.SCROLL, "10s").addIndex(source).build();
    final SearchResult searchResult = JestUtils.execute(jestClient, request, () -> "Couldn't process search query response");
    final String scrollId = searchResult.getJsonObject().path("_scroll_id").asText(null);
    if (scrollId == null) {
        throw new ElasticsearchException("Couldn't find scroll ID in search query response");
    }
    while (true) {
        final SearchScroll scrollRequest = new SearchScroll.Builder(scrollId, "1m").build();
        final JestResult scrollResult = JestUtils.execute(jestClient, scrollRequest, () -> "Couldn't process result of scroll query");
        final JsonNode scrollHits = scrollResult.getJsonObject().path("hits").path("hits");
        // No more hits.
        if (scrollHits.size() == 0) {
            break;
        }
        final Bulk.Builder bulkRequestBuilder = new Bulk.Builder();
        for (JsonNode jsonElement : scrollHits) {
            Optional.ofNullable(jsonElement.path("_source")).map(sourceJson -> objectMapper.<Map<String, Object>>convertValue(sourceJson, TypeReferences.MAP_STRING_OBJECT)).ifPresent(doc -> {
                final String id = (String) doc.remove("_id");
                if (!Strings.isNullOrEmpty(id)) {
                    bulkRequestBuilder.addAction(indexingHelper.prepareIndexRequest(target, doc, id));
                }
            });
        }
        final BulkResult bulkResult = JestUtils.execute(jestClient, bulkRequestBuilder.build(), () -> "Couldn't bulk index messages into index " + target);
        final boolean hasFailedItems = !bulkResult.getFailedItems().isEmpty();
        final IndexMoveResult result = IndexMoveResult.create(bulkResult.getItems().size(), bulkResult.getJsonObject().path("took").asLong(), hasFailedItems);
        resultCallback.accept(result);
    }
}
Also used : TermsAggregation(io.searchbox.core.search.aggregation.TermsAggregation) DateTimeZone(org.joda.time.DateTimeZone) Arrays(java.util.Arrays) PutTemplate(io.searchbox.indices.template.PutTemplate) LoggerFactory(org.slf4j.LoggerFactory) ModifyAliases(io.searchbox.indices.aliases.ModifyAliases) RequestConfig(org.apache.http.client.config.RequestConfig) TypeReferences(org.graylog2.jackson.TypeReferences) UpdateSettings(io.searchbox.indices.settings.UpdateSettings) FieldSortBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.FieldSortBuilder) MaxAggregation(io.searchbox.core.search.aggregation.MaxAggregation) IndicesAdapter(org.graylog2.indexer.indices.IndicesAdapter) HealthStatus(org.graylog2.indexer.indices.HealthStatus) JestUtils(org.graylog.storage.elasticsearch6.jest.JestUtils) Indices(org.graylog2.indexer.indices.Indices) Locale(java.util.Locale) Map(java.util.Map) JsonNode(com.fasterxml.jackson.databind.JsonNode) IndexRangeStats(org.graylog2.indexer.searches.IndexRangeStats) Bulk(io.searchbox.core.Bulk) Cat(io.searchbox.core.Cat) IndexMapping(org.graylog2.indexer.IndexMapping) FilterAggregation(io.searchbox.core.search.aggregation.FilterAggregation) QueryBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders) SearchSourceBuilder.searchSource(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder.searchSource) ImmutableSet(com.google.common.collect.ImmutableSet) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) Set(java.util.Set) Health(io.searchbox.cluster.Health) AddAliasMapping(io.searchbox.indices.aliases.AddAliasMapping) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) GetAliases(io.searchbox.indices.aliases.GetAliases) RemoveAliasMapping(io.searchbox.indices.aliases.RemoveAliasMapping) PutMapping(io.searchbox.indices.mapping.PutMapping) DeleteIndex(io.searchbox.indices.DeleteIndex) Stats(io.searchbox.indices.Stats) List(java.util.List) Parameters(io.searchbox.params.Parameters) OpenIndex(io.searchbox.indices.OpenIndex) AggregationBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.AggregationBuilders) IndexMoveResult(org.graylog2.indexer.indices.IndexMoveResult) Optional(java.util.Optional) UnsupportedEncodingException(java.io.UnsupportedEncodingException) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) SearchResult(io.searchbox.core.SearchResult) FilterAggregationBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder) HashMap(java.util.HashMap) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) SearchType(io.searchbox.params.SearchType) Iterators(com.google.common.collect.Iterators) JestClient(io.searchbox.client.JestClient) Inject(javax.inject.Inject) Strings(com.google.common.base.Strings) SortBuilders(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.sort.SortBuilders) ImmutableList(com.google.common.collect.ImmutableList) Flush(io.searchbox.indices.Flush) DeleteTemplate(io.searchbox.indices.template.DeleteTemplate) IndexStatistics(org.graylog2.indexer.indices.stats.IndexStatistics) Duration(com.github.joschi.jadconfig.util.Duration) StreamSupport(java.util.stream.StreamSupport) Nonnull(javax.annotation.Nonnull) GetSettings(io.searchbox.indices.settings.GetSettings) Logger(org.slf4j.Logger) MinAggregation(io.searchbox.core.search.aggregation.MinAggregation) Iterator(java.util.Iterator) IndexSettings(org.graylog2.indexer.indices.IndexSettings) IndexNotFoundException(org.graylog2.indexer.IndexNotFoundException) SearchScroll(io.searchbox.core.SearchScroll) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Search(io.searchbox.core.Search) AliasMapping(io.searchbox.indices.aliases.AliasMapping) DateTime(org.joda.time.DateTime) ForceMerge(io.searchbox.indices.ForceMerge) GetSingleAlias(org.graylog.storage.elasticsearch6.indices.GetSingleAlias) IOException(java.io.IOException) JestResult(io.searchbox.client.JestResult) Ints(com.google.common.primitives.Ints) CreateIndex(io.searchbox.indices.CreateIndex) BulkResult(io.searchbox.core.BulkResult) Consumer(java.util.function.Consumer) URLEncoder(java.net.URLEncoder) Collectors.toList(java.util.stream.Collectors.toList) CatResult(io.searchbox.core.CatResult) SerializationFeature(com.fasterxml.jackson.databind.SerializationFeature) CloseIndex(io.searchbox.indices.CloseIndex) GetTemplate(io.searchbox.indices.template.GetTemplate) Message(org.graylog2.plugin.Message) Collections(java.util.Collections) State(io.searchbox.cluster.State) 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) JsonNode(com.fasterxml.jackson.databind.JsonNode) ElasticsearchException(org.graylog2.indexer.ElasticsearchException) IndexMoveResult(org.graylog2.indexer.indices.IndexMoveResult) Bulk(io.searchbox.core.Bulk) BulkResult(io.searchbox.core.BulkResult) SearchScroll(io.searchbox.core.SearchScroll) Search(io.searchbox.core.Search) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) HashMap(java.util.HashMap) JestResult(io.searchbox.client.JestResult)

Example 3 with QueryBuilders.matchAllQuery

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.matchAllQuery in project sonarqube by SonarSource.

the class EsTester method after.

@Override
protected void after() {
    if (isCustom) {
        // delete non-core indices
        String[] existingIndices = getIndicesNames();
        Stream.of(existingIndices).filter(i -> !CORE_INDICES_NAMES.contains(i)).forEach(EsTester::deleteIndexIfExists);
    }
    BulkIndexer.delete(ES_REST_CLIENT, IndexType.main(ALL_INDICES, "dummy"), EsClient.prepareSearch(ALL_INDICES.getName()).source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())));
}
Also used : IndexRelationType(org.sonar.server.es.IndexType.IndexRelationType) BuiltIndex(org.sonar.server.es.newindex.BuiltIndex) ComponentIndexDefinition(org.sonar.server.component.index.ComponentIndexDefinition) Environment(org.elasticsearch.env.Environment) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) ALL_INDICES(org.sonar.server.es.Index.ALL_INDICES) Random(java.util.Random) Collections2(com.google.common.collect.Collections2) BindHttpException(org.elasticsearch.http.BindHttpException) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) ParentJoinPlugin(org.elasticsearch.join.ParentJoinPlugin) NodeValidationException(org.elasticsearch.node.NodeValidationException) ServerSocket(java.net.ServerSocket) RecoverySettings(org.elasticsearch.indices.recovery.RecoverySettings) Loggers(org.sonar.api.utils.log.Loggers) IndexRequest(org.elasticsearch.action.index.IndexRequest) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) Settings(org.elasticsearch.common.settings.Settings) Map(java.util.Map) SearchResponse(org.elasticsearch.action.search.SearchResponse) RequestOptions(org.elasticsearch.client.RequestOptions) HttpTransportSettings(org.elasticsearch.http.HttpTransportSettings) ElasticsearchStatusException(org.elasticsearch.ElasticsearchStatusException) Path(java.nio.file.Path) TimeValue(org.elasticsearch.core.TimeValue) SearchHit(org.elasticsearch.search.SearchHit) ImmutableMap(com.google.common.collect.ImmutableMap) ConstructorUtils(org.apache.commons.lang.reflect.ConstructorUtils) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) REFRESH_IMMEDIATE(org.sonar.server.es.newindex.DefaultIndexSettings.REFRESH_IMMEDIATE) Set(java.util.Set) ProjectMeasuresIndexDefinition(org.sonar.server.measure.index.ProjectMeasuresIndexDefinition) Netty4Plugin(org.elasticsearch.transport.Netty4Plugin) IndexDefinitionContext(org.sonar.server.es.IndexDefinition.IndexDefinitionContext) Collectors(java.util.stream.Collectors) String.format(java.lang.String.format) Preconditions.checkState(com.google.common.base.Preconditions.checkState) List(java.util.List) Stream(java.util.stream.Stream) ExternalResource(org.junit.rules.ExternalResource) Lists.newArrayList(com.google.common.collect.Lists.newArrayList) ClusterHealthRequest(org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest) CreateIndexResponse(org.elasticsearch.client.indices.CreateIndexResponse) SortOrder(org.elasticsearch.search.sort.SortOrder) RuleIndexDefinition(org.sonar.server.rule.index.RuleIndexDefinition) IssueIndexDefinition(org.sonar.server.issue.index.IssueIndexDefinition) ViewIndexDefinition(org.sonar.server.view.index.ViewIndexDefinition) GetIndexRequest(org.elasticsearch.client.indices.GetIndexRequest) Iterables(com.google.common.collect.Iterables) ClearScrollRequest(org.elasticsearch.action.search.ClearScrollRequest) DiskThresholdSettings(org.elasticsearch.cluster.routing.allocation.DiskThresholdSettings) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) InternalSettingsPreparer(org.elasticsearch.node.InternalSettingsPreparer) SearchRequest(org.elasticsearch.action.search.SearchRequest) ArrayList(java.util.ArrayList) UpdateSettingsRequest(org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest) Strings(org.elasticsearch.common.Strings) DatagramSocket(java.net.DatagramSocket) HashSet(java.util.HashSet) ImmutableList(com.google.common.collect.ImmutableList) DiscoveryModule(org.elasticsearch.discovery.DiscoveryModule) CommonAnalysisPlugin(org.elasticsearch.analysis.common.CommonAnalysisPlugin) Node(org.elasticsearch.node.Node) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) FIELD_INDEX_TYPE(org.sonar.server.es.IndexType.FIELD_INDEX_TYPE) NoSuchElementException(java.util.NoSuchElementException) Logger(org.sonar.api.utils.log.Logger) QueryBuilder(org.elasticsearch.index.query.QueryBuilder) DeleteIndexRequest(org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest) QueryBuilders.matchAllQuery(org.elasticsearch.index.query.QueryBuilders.matchAllQuery) CreateIndexRequest(org.elasticsearch.client.indices.CreateIndexRequest) Files(java.nio.file.Files) Throwables(com.google.common.base.Throwables) UserIndexDefinition(org.sonar.server.user.index.UserIndexDefinition) IOException(java.io.IOException) AcknowledgedResponse(org.elasticsearch.action.support.master.AcknowledgedResponse) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) TermQueryBuilder(org.elasticsearch.index.query.TermQueryBuilder) NodeEnvironment(org.elasticsearch.env.NodeEnvironment) NewIndex(org.sonar.server.es.newindex.NewIndex) PutMappingRequest(org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest) SearchScrollRequest(org.elasticsearch.action.search.SearchScrollRequest) ClusterHealthStatus(org.elasticsearch.cluster.health.ClusterHealthStatus) Collections(java.util.Collections) HttpHost(org.apache.http.HttpHost) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder)

Example 4 with QueryBuilders.matchAllQuery

use of org.graylog.shaded.elasticsearch6.org.elasticsearch.index.query.QueryBuilders.matchAllQuery in project graylog2-server by Graylog2.

the class CountsAdapterES6 method totalCount.

@Override
public long totalCount(List<String> indices) {
    final String query = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery()).size(0).toString();
    final Search request = new Search.Builder(query).addIndex(indices).build();
    final MultiSearch multiSearch = new MultiSearch.Builder(request).build();
    final MultiSearchResult searchResult = JestUtils.execute(jestClient, multiSearch, () -> "Fetching message count failed for indices " + indices);
    final List<MultiSearchResult.MultiSearchResponse> responses = searchResult.getResponses();
    long total = 0L;
    for (MultiSearchResult.MultiSearchResponse response : responses) {
        if (response.isError) {
            throw JestUtils.specificException(() -> "Fetching message count failed for indices " + indices, response.error);
        }
        total += response.searchResult.getTotal();
    }
    return total;
}
Also used : MultiSearchResult(io.searchbox.core.MultiSearchResult) MultiSearch(io.searchbox.core.MultiSearch) Search(io.searchbox.core.Search) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder) MultiSearch(io.searchbox.core.MultiSearch) SearchSourceBuilder(org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)

Aggregations

ImmutableMap (com.google.common.collect.ImmutableMap)3 Search (io.searchbox.core.Search)3 Map (java.util.Map)3 SearchSourceBuilder (org.graylog.shaded.elasticsearch6.org.elasticsearch.search.builder.SearchSourceBuilder)3 ImmutableList (com.google.common.collect.ImmutableList)2 SearchResult (io.searchbox.core.SearchResult)2 FilterAggregation (io.searchbox.core.search.aggregation.FilterAggregation)2 TermsAggregation (io.searchbox.core.search.aggregation.TermsAggregation)2 IOException (java.io.IOException)2 Collections (java.util.Collections)2 HashMap (java.util.HashMap)2 List (java.util.List)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 FilterAggregationBuilder (org.graylog.shaded.elasticsearch6.org.elasticsearch.search.aggregations.bucket.filter.FilterAggregationBuilder)2 DateTime (org.joda.time.DateTime)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 SerializationFeature (com.fasterxml.jackson.databind.SerializationFeature)1 Duration (com.github.joschi.jadconfig.util.Duration)1