Search in sources :

Example 6 with Terms

use of org.elasticsearch.search.aggregations.bucket.terms.Terms in project sonarqube by SonarSource.

the class IssueIndex method listTags.

public List<String> listTags(IssueQuery query, @Nullable String textQuery, int maxNumberOfTags) {
    SearchRequestBuilder requestBuilder = getClient().prepareSearch(IssueIndexDefinition.INDEX_TYPE_ISSUE, RuleIndexDefinition.INDEX_TYPE_RULE);
    requestBuilder.setQuery(boolQuery().must(matchAllQuery()).filter(createBoolFilter(query)));
    GlobalBuilder topAggreg = AggregationBuilders.global("tags");
    String tagsOnIssuesSubAggregation = "tags__issues";
    String tagsOnRulesSubAggregation = "tags__rules";
    TermsBuilder issueTags = AggregationBuilders.terms(tagsOnIssuesSubAggregation).field(IssueIndexDefinition.FIELD_ISSUE_TAGS).size(maxNumberOfTags).order(Terms.Order.term(true)).minDocCount(1L);
    TermsBuilder ruleTags = AggregationBuilders.terms(tagsOnRulesSubAggregation).field(RuleIndexDefinition.FIELD_RULE_ALL_TAGS).size(maxNumberOfTags).order(Terms.Order.term(true)).minDocCount(1L);
    if (textQuery != null) {
        String escapedTextQuery = escapeSpecialRegexChars(textQuery);
        issueTags.include(format(SUBSTRING_MATCH_REGEXP, escapedTextQuery));
        ruleTags.include(format(SUBSTRING_MATCH_REGEXP, escapedTextQuery));
    }
    SearchResponse searchResponse = requestBuilder.addAggregation(topAggreg.subAggregation(issueTags).subAggregation(ruleTags)).get();
    Global allTags = searchResponse.getAggregations().get("tags");
    SortedSet<String> result = Sets.newTreeSet();
    Terms issuesResult = allTags.getAggregations().get(tagsOnIssuesSubAggregation);
    Terms rulesResult = allTags.getAggregations().get(tagsOnRulesSubAggregation);
    result.addAll(EsUtils.termsKeys(issuesResult));
    result.addAll(EsUtils.termsKeys(rulesResult));
    List<String> resultAsList = Lists.newArrayList(result);
    return resultAsList.size() > maxNumberOfTags && maxNumberOfTags > 0 ? resultAsList.subList(0, maxNumberOfTags) : resultAsList;
}
Also used : GlobalBuilder(org.elasticsearch.search.aggregations.bucket.global.GlobalBuilder) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) TermsBuilder(org.elasticsearch.search.aggregations.bucket.terms.TermsBuilder) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) Global(org.elasticsearch.search.aggregations.bucket.global.Global) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 7 with Terms

use of org.elasticsearch.search.aggregations.bucket.terms.Terms in project sonarqube by SonarSource.

the class ActiveRuleIndex method processAggregations.

private static Multimap<String, FacetValue> processAggregations(@Nullable Aggregations aggregations) {
    Multimap<String, FacetValue> stats = ArrayListMultimap.create();
    if (aggregations == null) {
        return stats;
    }
    for (Aggregation aggregation : aggregations.asList()) {
        if (aggregation instanceof StringTerms) {
            for (Terms.Bucket value : ((Terms) aggregation).getBuckets()) {
                FacetValue facetValue = new FacetValue(value.getKeyAsString(), value.getDocCount());
                stats.put(aggregation.getName(), facetValue);
            }
        } else if (aggregation instanceof InternalValueCount) {
            InternalValueCount count = (InternalValueCount) aggregation;
            FacetValue facetValue = new FacetValue(count.getName(), count.getValue());
            stats.put(count.getName(), facetValue);
        }
    }
    return stats;
}
Also used : Aggregation(org.elasticsearch.search.aggregations.Aggregation) InternalValueCount(org.elasticsearch.search.aggregations.metrics.valuecount.InternalValueCount) FacetValue(org.sonar.server.search.FacetValue) StringTerms(org.elasticsearch.search.aggregations.bucket.terms.StringTerms) StringTerms(org.elasticsearch.search.aggregations.bucket.terms.StringTerms) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms)

Example 8 with Terms

use of org.elasticsearch.search.aggregations.bucket.terms.Terms in project sonarqube by SonarSource.

the class ActiveRuleIndex method getStatsByProfileKeys.

public Map<String, Multimap<String, FacetValue>> getStatsByProfileKeys(List<String> keys) {
    SearchRequestBuilder request = getClient().prepareSearch(INDEX_TYPE_RULE.getIndex()).setQuery(QueryBuilders.boolQuery().must(QueryBuilders.termsQuery(FIELD_ACTIVE_RULE_PROFILE_KEY, keys)).filter(QueryBuilders.boolQuery().mustNot(QueryBuilders.hasParentQuery(INDEX_TYPE_RULE.getType(), QueryBuilders.termQuery(FIELD_RULE_STATUS, RuleStatus.REMOVED.name()))))).addAggregation(AggregationBuilders.terms(FIELD_ACTIVE_RULE_PROFILE_KEY).field(RuleIndexDefinition.FIELD_ACTIVE_RULE_PROFILE_KEY).size(0).subAggregation(AggregationBuilders.terms(FIELD_ACTIVE_RULE_INHERITANCE).field(RuleIndexDefinition.FIELD_ACTIVE_RULE_INHERITANCE)).subAggregation(AggregationBuilders.terms(FIELD_ACTIVE_RULE_SEVERITY).field(RuleIndexDefinition.FIELD_ACTIVE_RULE_SEVERITY)).subAggregation(AggregationBuilders.count(COUNT_ACTIVE_RULES))).setSize(0);
    SearchResponse response = request.get();
    Map<String, Multimap<String, FacetValue>> stats = new HashMap<>();
    Aggregation aggregation = response.getAggregations().get(FIELD_ACTIVE_RULE_PROFILE_KEY);
    for (Terms.Bucket value : ((Terms) aggregation).getBuckets()) {
        stats.put(value.getKeyAsString(), processAggregations(value.getAggregations()));
    }
    return stats;
}
Also used : Aggregation(org.elasticsearch.search.aggregations.Aggregation) ArrayListMultimap(com.google.common.collect.ArrayListMultimap) Multimap(com.google.common.collect.Multimap) SearchRequestBuilder(org.elasticsearch.action.search.SearchRequestBuilder) HashMap(java.util.HashMap) StringTerms(org.elasticsearch.search.aggregations.bucket.terms.StringTerms) Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) SearchResponse(org.elasticsearch.action.search.SearchResponse)

Example 9 with Terms

use of org.elasticsearch.search.aggregations.bucket.terms.Terms in project elasticsearch by elastic.

the class CombiIT method testMultipleAggsOnSameField_WithDifferentRequiredValueSourceType.

/**
     * Making sure that if there are multiple aggregations, working on the same field, yet require different
     * value source type, they can all still work. It used to fail as we used to cache the ValueSource by the
     * field name. If the cached value source was of type "bytes" and another aggregation on the field required to see
     * it as "numeric", it didn't work. Now we cache the Value Sources by a custom key (field name + ValueSource type)
     * so there's no conflict there.
     */
public void testMultipleAggsOnSameField_WithDifferentRequiredValueSourceType() throws Exception {
    createIndex("idx");
    IndexRequestBuilder[] builders = new IndexRequestBuilder[randomInt(30)];
    IntIntMap values = new IntIntHashMap();
    long missingValues = 0;
    for (int i = 0; i < builders.length; i++) {
        String name = "name_" + randomIntBetween(1, 10);
        if (rarely()) {
            missingValues++;
            builders[i] = client().prepareIndex("idx", "type").setSource(jsonBuilder().startObject().field("name", name).endObject());
        } else {
            int value = randomIntBetween(1, 10);
            values.put(value, values.getOrDefault(value, 0) + 1);
            builders[i] = client().prepareIndex("idx", "type").setSource(jsonBuilder().startObject().field("name", name).field("value", value).endObject());
        }
    }
    indexRandom(true, builders);
    ensureSearchable();
    SubAggCollectionMode aggCollectionMode = randomFrom(SubAggCollectionMode.values());
    SearchResponse response = client().prepareSearch("idx").addAggregation(missing("missing_values").field("value")).addAggregation(terms("values").field("value").collectMode(aggCollectionMode)).execute().actionGet();
    assertSearchResponse(response);
    Aggregations aggs = response.getAggregations();
    Missing missing = aggs.get("missing_values");
    assertNotNull(missing);
    assertThat(missing.getDocCount(), equalTo(missingValues));
    Terms terms = aggs.get("values");
    assertNotNull(terms);
    Collection<Terms.Bucket> buckets = terms.getBuckets();
    assertThat(buckets.size(), equalTo(values.size()));
    for (Terms.Bucket bucket : buckets) {
        values.remove(((Number) bucket.getKey()).intValue());
    }
    assertTrue(values.isEmpty());
}
Also used : Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse) IndexRequestBuilder(org.elasticsearch.action.index.IndexRequestBuilder) IntIntMap(com.carrotsearch.hppc.IntIntMap) IntIntHashMap(com.carrotsearch.hppc.IntIntHashMap) Missing(org.elasticsearch.search.aggregations.bucket.missing.Missing) SubAggCollectionMode(org.elasticsearch.search.aggregations.Aggregator.SubAggCollectionMode)

Example 10 with Terms

use of org.elasticsearch.search.aggregations.bucket.terms.Terms in project elasticsearch by elastic.

the class AggregationsIntegrationIT method testScroll.

public void testScroll() {
    final int size = randomIntBetween(1, 4);
    SearchResponse response = client().prepareSearch("index").setSize(size).setScroll(new TimeValue(500)).addAggregation(terms("f").field("f")).get();
    assertSearchResponse(response);
    Aggregations aggregations = response.getAggregations();
    assertNotNull(aggregations);
    Terms terms = aggregations.get("f");
    assertEquals(Math.min(numDocs, 3L), terms.getBucketByKey("0").getDocCount());
    int total = response.getHits().getHits().length;
    while (response.getHits().getHits().length > 0) {
        response = client().prepareSearchScroll(response.getScrollId()).setScroll(new TimeValue(500)).execute().actionGet();
        assertNull(response.getAggregations());
        total += response.getHits().getHits().length;
    }
    clearScroll(response.getScrollId());
    assertEquals(numDocs, total);
}
Also used : Terms(org.elasticsearch.search.aggregations.bucket.terms.Terms) TimeValue(org.elasticsearch.common.unit.TimeValue) SearchResponse(org.elasticsearch.action.search.SearchResponse) ElasticsearchAssertions.assertSearchResponse(org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)

Aggregations

Terms (org.elasticsearch.search.aggregations.bucket.terms.Terms)300 SearchResponse (org.elasticsearch.action.search.SearchResponse)268 ElasticsearchAssertions.assertSearchResponse (org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse)209 Bucket (org.elasticsearch.search.aggregations.bucket.terms.Terms.Bucket)100 Histogram (org.elasticsearch.search.aggregations.bucket.histogram.Histogram)38 Sum (org.elasticsearch.search.aggregations.metrics.sum.Sum)37 Bucket (org.elasticsearch.search.aggregations.bucket.histogram.Histogram.Bucket)36 ArrayList (java.util.ArrayList)30 HashMap (java.util.HashMap)26 Filter (org.elasticsearch.search.aggregations.bucket.filter.Filter)26 SearchRequestBuilder (org.elasticsearch.action.search.SearchRequestBuilder)24 Script (org.elasticsearch.script.Script)22 StringTerms (org.elasticsearch.search.aggregations.bucket.terms.StringTerms)16 IncludeExclude (org.elasticsearch.search.aggregations.bucket.terms.support.IncludeExclude)16 ExtendedStats (org.elasticsearch.search.aggregations.metrics.stats.extended.ExtendedStats)16 TermsAggregationBuilder (org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder)15 TopHits (org.elasticsearch.search.aggregations.metrics.tophits.TopHits)15 Aggregation (org.elasticsearch.search.aggregations.Aggregation)14 SearchHits (org.elasticsearch.search.SearchHits)13 InternalBucketMetricValue (org.elasticsearch.search.aggregations.pipeline.bucketmetrics.InternalBucketMetricValue)13