org.elasticsearch.search.aggregations.metrics.max.Max Java Examples

The following examples show how to use org.elasticsearch.search.aggregations.metrics.max.Max. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ElasticsearchDataQuery.java    From frostmourne with MIT License 6 votes vote down vote up
private Double findAggregationValue(MetricContract metricContract, SearchResponse searchResponse) {
    String aggType = metricContract.getAggregation_type();
    if (aggType.equalsIgnoreCase("max")) {
        Max max = searchResponse.getAggregations().get("maxNumber");
        return max.getValue();
    }
    if (aggType.equalsIgnoreCase("min")) {
        Min min = searchResponse.getAggregations().get("minNumber");
        return min.getValue();
    }
    if (aggType.equalsIgnoreCase("avg")) {
        Avg avg = searchResponse.getAggregations().get("avgNumber");
        return avg.getValue();
    }
    if (aggType.equalsIgnoreCase("sum")) {
        Sum sum = searchResponse.getAggregations().get("sumNumber");
        return sum.getValue();
    }

    throw new IllegalArgumentException("unsupported aggregation type: " + aggType);
}
 
Example #2
Source File: AggregationResponseHandle.java    From jetlinks-community with Apache License 2.0 6 votes vote down vote up
private static <A extends Aggregation> void route(Bucket bucket, A a) {
    if (a instanceof Terms) {
        bucket.setBuckets(terms(a));
    } else if (a instanceof Range) {
        bucket.setBuckets(range(a));
    } else if (a instanceof Histogram) {
        bucket.setBuckets(range(a));
    } else if (a instanceof Avg) {
        bucket.setAvg(avg(a));
    } else if (a instanceof Min) {
        bucket.setMin(min(a));
    } else if (a instanceof Max) {
        bucket.setMax(max(a));
    } else if (a instanceof Sum) {
        bucket.setSum(sum(a));
    } else if (a instanceof Stats) {
        stats(bucket, a);
    }  else if (a instanceof ValueCount) {
        bucket.setValueCount(count(a));
    } else {
        throw new UnsupportedOperationException("不支持的聚合类型");
    }
}
 
Example #3
Source File: FactSearchManager.java    From act-platform with ISC License 5 votes vote down vote up
private long retrieveMaxTimestamp(Terms.Bucket bucket, String targetAggregationName) {
  Aggregation maxAggregation = bucket.getAggregations().get(targetAggregationName);
  if (!(maxAggregation instanceof Max)) {
    LOGGER.warning("Could not retrieve maximum timestamp when calculating statistics for Objects.");
    return -1;
  }

  // Retrieve maximum timestamp from the max aggregation.
  return Math.round(Max.class.cast(maxAggregation).getValue());
}
 
Example #4
Source File: Search.java    From elasticsearch-rest-command with The Unlicense 5 votes vote down vote up
public static String getValueFromAggregation(Aggregation a, Function f){
	
	String value = null;
	switch(f.type){
	case Function.SUM :
		value = String.valueOf(((Sum) a).getValue());
		break;
	case Function.COUNT :
		value = String.valueOf(((ValueCount) a).getValue());
		break;
	case Function.DC :
		value = String.valueOf(((Cardinality) a).getValue());
		break;
	case Function.AVG :
		value = String.valueOf(((Avg) a).getValue());
		break;
	case Function.MAX :
		value = String.valueOf(((Max) a).getValue());
		break;
	case Function.MIN :
		value = String.valueOf(((Min) a).getValue());
		break;
	}
	
	return value;
	
	
}
 
Example #5
Source File: ElasticStatsService.java    From staccato with Apache License 2.0 4 votes vote down vote up
/**
 * Populates an {@link Extent} object with the bounding box for the items matched in the provided query.
 *
 * @param index The Elasticsearch index to api
 * @param query The query that should be executed against the provided index
 * @return The extent of the items matched during the api
 */
@Override
public Extent getExtent(String index, Map<String, String> query) {
    StringBuilder sb = new StringBuilder();
    if (null != query) {

        Iterator<Map.Entry<String, String>> it = query.entrySet().iterator();

        while (it.hasNext()) {
            Map.Entry entry = it.next();
            sb.append("properties." + entry.getKey() + "=" + entry.getValue());
            if (it.hasNext()) {
                sb.append(" AND ");
            }
        }
    }

    Optional<QueryBuilder> filter = QueryBuilderHelper.queryBuilder(sb.toString());
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

    if (filter.isPresent()) {
        searchSourceBuilder.query(filter.get());
    }

    searchSourceBuilder
            .aggregation(AggregationBuilders.min("start").field(FieldName.DATETIME_FULL))
            .aggregation(AggregationBuilders.max("end").field(FieldName.DATETIME_FULL))
            .aggregation(AggregationBuilders.geoBounds("bbox").field(FieldName.CENTROID))
            //we don't want records back, just aggregations
            .size(0);

    SearchRequest sr = new SearchRequest().indices(index).source(searchSourceBuilder);

    log.debug("Getting stats on {} with the following request: \n {}", index, sr.source().toString());
    SearchResponse resp;
    try {
        resp = restClient.search(sr);
    } catch (Exception ex) {
        throw new RuntimeException("Error getting aggregations.", ex);
    }

    Min start = resp.getAggregations().get("start");
    Max end = resp.getAggregations().get("end");
    GeoBounds bboxAggregation = resp.getAggregations().get("bbox");

    Extent extent = new Extent();
    List<String> temporalExtent = new ArrayList<>(2);

    Consumer<String> temporalCheck = value -> {
        if (null != value && !value.toLowerCase().contains("infinity")) {
            temporalExtent.add(value);
        } else {
            temporalExtent.add(null);
        }
    };

    temporalCheck.accept(start.getValueAsString());
    temporalCheck.accept(end.getValueAsString());
    extent.getTemporal().getInterval().add(temporalExtent);

    List<Double> bbox = getBboxExtent(bboxAggregation);
    if (bbox != null && (bbox.size() == 4 || bbox.size() == 6)) {
        extent.getSpatial().getBbox().add(bbox);
    }

    return extent;
}
 
Example #6
Source File: ElasticStatsService.java    From staccato with Apache License 2.0 4 votes vote down vote up
/**
 * Blocking method to fetch aggregations from Elasticsearch.
 *
 * @param index The index to build aggregations for.
 * @return An {@link ItemStatisticsResponse ItemStatisticsResponse} object containing the aggregated data for the index
 */
private ItemStatisticsResponse getStatsSync(String index) {
    SearchRequest sr = new SearchRequest().indices(index).source(
            new SearchSourceBuilder()
                    .aggregation(AggregationBuilders.min("start").field(FieldName.DATETIME_FULL))
                    .aggregation(AggregationBuilders.max("end").field(FieldName.DATETIME_FULL))
                    //.stats(AggregationBuilders.terms("licenses").field(FieldName.LICENSE_FULL).size(5).order(BucketOrder.count(true)))
                    //.stats(AggregationBuilders.terms("providers").field(FieldName.PROVIDER_FULL).size(5).order(BucketOrder.count(true)))
                    .aggregation(AggregationBuilders.geoBounds("bbox").field(FieldName.CENTROID))
                    //we don't want records back, just aggregations
                    .size(0)
    );
    log.debug("Getting stats on {} with the following request: \n {}", index, sr.source().toString());

    SearchResponse resp;
    try {
        resp = restClient.search(sr, RequestOptions.DEFAULT);
    } catch (IOException ex) {
        return new ItemStatisticsResponse();
    }

    Min start = resp.getAggregations().get("start");
    Max end = resp.getAggregations().get("end");
    //Terms lics = resp.getAggregations().get("licenses");
    //Terms provs = resp.getAggregations().get("providers");
    GeoBounds bboxAggregation = resp.getAggregations().get("bbox");

    ItemStatisticsResponse stats = new ItemStatisticsResponse();
    stats.setType(index);
    stats.setCount(resp.getHits().totalHits);

    String endValue = end.getValueAsString();
    if (null != endValue && !endValue.toLowerCase().contains("infinity")) {
        stats.setEnd(endValue);
    }

    String startValue = start.getValueAsString();
    if (null != startValue && !startValue.toLowerCase().contains("infinity")) {
        stats.setStart(startValue);
    }

    List<Double> bbox = getBboxExtent(bboxAggregation);
    if (bbox != null && (bbox.size() == 4 || bbox.size() == 6)) {
        stats.setBounds(bbox);
    }

    return stats;
}
 
Example #7
Source File: SimpleTests.java    From elasticsearch-topk-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void assertTop10of50OneShardNestedAggregations() {
    client.admin().indices().prepareCreate("topk-4").setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 1)).execute().actionGet();
    
    double sum = 0;
    for (int i = 0; i < 50; ++i) { // 50 values
        client.prepareIndex("topk-4", "type0", "doc" + i).setSource("{ \"field0\": \"foo" + i + "\", \"field1\":" + i +" }").setRefresh(true).execute().actionGet();
    }
    
    // foo0 x 50
    for (int i = 50; i < 100; ++i) {
        client.prepareIndex("topk-4", "type0", "doc" + i).setSource("{ \"field0\": \"foo0\", \"field1\":" + i +" }").setRefresh(true).execute().actionGet();
        sum += i;
    }
   
    SearchResponse searchResponse = client.prepareSearch("topk-4")
            .setQuery(matchAllQuery())
            .addAggregation(new TopKBuilder("topk").field("field0").size(10)
                    .subAggregation(new AvgBuilder("avg").field("field1"))
                    .subAggregation(new MaxBuilder("max").field("field1"))
            )
            .execute().actionGet();
    assertEquals(100, searchResponse.getHits().getTotalHits());
    TopK topk = searchResponse.getAggregations().get("topk");
    assertNotNull(topk);
    List<TopK.Bucket> buckets = new ArrayList<>(topk.getBuckets());
    assertEquals(10, buckets.size());
    assertEquals("foo0", buckets.get(0).getKey());
    assertEquals(51, buckets.get(0).getDocCount());
    assertEquals(2, buckets.get(0).getAggregations().asList().size());
    for (Aggregation agg : buckets.get(0).getAggregations()) {
        switch (agg.getName()) {
        case "avg":
            assertEquals(sum / 51, ((Avg) agg).getValue(), 0.01);
            break;
        case "max":
            assertEquals(99.0, ((Max) agg).getValue(), 0.001);
            break;
        default:
            assertTrue(false);
        } 
    }
}
 
Example #8
Source File: SimpleTests.java    From elasticsearch-topk-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void assertTop10of50TwoShardNestedAggregations() {
    client.admin().indices().prepareCreate("topk-5").setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 2)).execute().actionGet();
    
    double sum = 0;
    for (int i = 0; i < 50; ++i) { // 50 values
        client.prepareIndex("topk-5", "type0", "doc" + i).setSource("{ \"field0\": \"foo" + i + "\", \"field1\":" + i +" }").setRefresh(true).execute().actionGet();
    }
    
    // foo0 x 50
    for (int i = 50; i < 100; ++i) {
        client.prepareIndex("topk-5", "type0", "doc" + i).setSource("{ \"field0\": \"foo0\", \"field1\":" + i +" }").setRefresh(true).execute().actionGet();
        sum += i;
    }
   
    SearchResponse searchResponse = client.prepareSearch("topk-5")
            .setQuery(matchAllQuery())
            .addAggregation(new TopKBuilder("topk").field("field0").size(10)
                    .subAggregation(new AvgBuilder("avg").field("field1"))
                    .subAggregation(new MaxBuilder("max").field("field1"))
            )
            .execute().actionGet();
    assertEquals(100, searchResponse.getHits().getTotalHits());
    TopK topk = searchResponse.getAggregations().get("topk");
    assertNotNull(topk);
    List<TopK.Bucket> buckets = new ArrayList<>(topk.getBuckets());
    assertEquals(10, buckets.size());
    assertEquals("foo0", buckets.get(0).getKey());
    assertEquals(51, buckets.get(0).getDocCount());
    assertEquals(2, buckets.get(0).getAggregations().asList().size());
    for (Aggregation agg : buckets.get(0).getAggregations()) {
        switch (agg.getName()) {
        case "avg":
            assertEquals(sum / 51, ((Avg) agg).getValue(), 0.01);
            break;
        case "max":
            assertEquals(99.0, ((Max) agg).getValue(), 0.001);
            break;
        default:
            assertTrue(false);
        } 
    }
}
 
Example #9
Source File: SimpleTests.java    From elasticsearch-topk-plugin with Apache License 2.0 4 votes vote down vote up
@Test
public void assertTop10of50TwoShardNestedAggregationsStress() {
    client.admin().indices().prepareCreate("topk-6").setSettings(ImmutableSettings.settingsBuilder().put("index.number_of_shards", 4)).execute().actionGet();
    
    final int N = 30000;
    double sum = 0;
    int n = 0;
    int max = Integer.MIN_VALUE;
    Random r = new Random();
    for (int i = 0; i < N; ++i) {
        int v = r.nextInt();
        if (i % 7 == 0) {
            sum += v;
            ++n;
            if (v > max) {
                max = v;
            }
        }
        client.prepareIndex("topk-6", "type0", "doc" + i).setSource("{ \"field0\": \"foo" + (i % 7 == 0 ? "bar" : String.valueOf(i)) + "\", \"field1\":" + v +" }").setRefresh(i == N - 1).execute().actionGet();
    }
    try { Thread.sleep(2000); } catch (InterruptedException e) {} // FIXME: wait until all docs are searchable
    
    SearchResponse searchResponse = client.prepareSearch("topk-6")
            .setQuery(matchAllQuery())
            .addAggregation(new TopKBuilder("topk").field("field0").size(10)
                    .subAggregation(new AvgBuilder("avg").field("field1"))
                    .subAggregation(new MaxBuilder("max").field("field1"))
            )
            .execute().actionGet();
    assertEquals(N, searchResponse.getHits().getTotalHits());
    TopK topk = searchResponse.getAggregations().get("topk");
    assertNotNull(topk);
    List<TopK.Bucket> buckets = new ArrayList<>(topk.getBuckets());
    assertEquals(10, buckets.size());
    assertEquals("foobar", buckets.get(0).getKey());
    assertEquals(n, buckets.get(0).getDocCount());
    assertEquals(2, buckets.get(0).getAggregations().asList().size());
    for (Aggregation agg : buckets.get(0).getAggregations()) {
        switch (agg.getName()) {
        case "avg":
            assertEquals(sum / n, ((Avg) agg).getValue(), 0.01);
            break;
        case "max":
            assertEquals((double) max, ((Max) agg).getValue(), 0.001);
            break;
        default:
            assertTrue(false);
        } 
    }
}