ElasticsearchAggregationResponseParser { public static List<Map<String, Object>> parse(Aggregations aggregations) { List<Aggregation> aggregationList = aggregations.asList(); ImmutableList.Builder<Map<String, Object>> builder = new ImmutableList.Builder<>(); for (Aggregation aggregation : aggregationList) { if (aggregation instanceof CompositeAggregation) { for (CompositeAggregation.Bucket bucket : ((CompositeAggregation) aggregation).getBuckets()) { builder.add(parse(bucket)); } } else { builder.add(parseInternal(aggregation)); } } return builder.build(); }  static List<Map<String, Object>> parse(Aggregations aggregations);  }
@Test void no_bucket_one_metric_should_pass() { String response = "{\n" + " \"max#max\": {\n" + " \"value\": 40\n" + " }\n" + "}"; assertThat(parse(response), contains(entry("max", 40d))); }
@Test void no_bucket_two_metric_should_pass() { String response = "{\n" + " \"max#max\": {\n" + " \"value\": 40\n" + " },\n" + " \"min#min\": {\n" + " \"value\": 20\n" + " }\n" + "}"; assertThat(parse(response), containsInAnyOrder(entry("max", 40d), entry("min", 20d))); }
@Test void one_bucket_one_metric_should_pass() { String response = "{\n" + " \"composite#composite_buckets\": {\n" + " \"after_key\": {\n" + " \"type\": \"sale\"\n" + " },\n" + " \"buckets\": [\n" + " {\n" + " \"key\": {\n" + " \"type\": \"cost\"\n" + " },\n" + " \"doc_count\": 2,\n" + " \"avg#avg\": {\n" + " \"value\": 20\n" + " }\n" + " },\n" + " {\n" + " \"key\": {\n" + " \"type\": \"sale\"\n" + " },\n" + " \"doc_count\": 2,\n" + " \"avg#avg\": {\n" + " \"value\": 105\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; assertThat(parse(response), containsInAnyOrder(ImmutableMap.of("type", "cost", "avg", 20d), ImmutableMap.of("type", "sale", "avg", 105d))); }
@Test void two_bucket_one_metric_should_pass() { String response = "{\n" + " \"composite#composite_buckets\": {\n" + " \"after_key\": {\n" + " \"type\": \"sale\",\n" + " \"region\": \"us\"\n" + " },\n" + " \"buckets\": [\n" + " {\n" + " \"key\": {\n" + " \"type\": \"cost\",\n" + " \"region\": \"us\"\n" + " },\n" + " \"avg#avg\": {\n" + " \"value\": 20\n" + " }\n" + " },\n" + " {\n" + " \"key\": {\n" + " \"type\": \"sale\",\n" + " \"region\": \"uk\"\n" + " },\n" + " \"avg#avg\": {\n" + " \"value\": 130\n" + " }\n" + " }\n" + " ]\n" + " }\n" + "}"; assertThat(parse(response), containsInAnyOrder(ImmutableMap.of("type", "cost", "region", "us", "avg", 20d), ImmutableMap.of("type", "sale", "region", "uk", "avg", 130d))); }
@Test void unsupported_aggregation_should_fail() { String response = "{\n" + " \"date_histogram#max\": {\n" + " \"value\": 40\n" + " }\n" + "}"; IllegalStateException exception = assertThrows(IllegalStateException.class, () -> parse(response)); assertEquals("unsupported aggregation type date_histogram", exception.getMessage()); }