1+ /*
2+ * Licensed to Elasticsearch under one or more contributor
3+ * license agreements. See the NOTICE file distributed with
4+ * this work for additional information regarding copyright
5+ * ownership. Elasticsearch licenses this file to you under
6+ * the Apache License, Version 2.0 (the "License"); you may
7+ * not use this file except in compliance with the License.
8+ * You may obtain a copy of the License at
9+ *
10+ * http://www.apache.org/licenses/LICENSE-2.0
11+ *
12+ * Unless required by applicable law or agreed to in writing,
13+ * software distributed under the License is distributed on an
14+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15+ * KIND, either express or implied. See the License for the
16+ * specific language governing permissions and limitations
17+ * under the License.
18+ */
19+
20+ package org .elasticsearch .search .aggregations .metrics .avg ;
21+
22+ import org .elasticsearch .common .xcontent .ObjectParser ;
23+ import org .elasticsearch .common .xcontent .XContentBuilder ;
24+ import org .elasticsearch .common .xcontent .XContentParser ;
25+ import org .elasticsearch .search .aggregations .metrics .ParsedSingleValueNumericMetricsAggregation ;
26+
27+ import java .io .IOException ;
28+
29+ public class ParsedAvg extends ParsedSingleValueNumericMetricsAggregation implements Avg {
30+
31+ @ Override
32+ public double getValue () {
33+ return value ();
34+ }
35+
36+ @ Override
37+ protected String getType () {
38+ return AvgAggregationBuilder .NAME ;
39+ }
40+
41+ @ Override
42+ protected XContentBuilder doXContentBody (XContentBuilder builder , Params params ) throws IOException {
43+ // InternalAvg renders value only if the avg normalizer (count) is not 0.
44+ // We parse back `null` as Double.POSITIVE_INFINITY so we check for that value here to get the same xContent output
45+ boolean hasValue = value != Double .POSITIVE_INFINITY ;
46+ builder .field (CommonFields .VALUE .getPreferredName (), hasValue ? value : null );
47+ if (hasValue && valueAsString != null ) {
48+ builder .field (CommonFields .VALUE_AS_STRING .getPreferredName (), valueAsString );
49+ }
50+ return builder ;
51+ }
52+
53+ private static final ObjectParser <ParsedAvg , Void > PARSER = new ObjectParser <>(ParsedAvg .class .getSimpleName (), true , ParsedAvg ::new );
54+
55+ static {
56+ declareSingeValueFields (PARSER , Double .POSITIVE_INFINITY );
57+ }
58+
59+ public static ParsedAvg fromXContent (XContentParser parser , final String name ) {
60+ ParsedAvg avg = PARSER .apply (parser , null );
61+ avg .setName (name );
62+ return avg ;
63+ }
64+ }
0 commit comments