@@ -2,7 +2,8 @@ use std::fmt::Debug;
2
2
3
3
use serde:: { Deserialize , Serialize } ;
4
4
5
- use super :: { IntermediateStats , SegmentStatsCollector } ;
5
+ use super :: * ;
6
+ use crate :: aggregation:: * ;
6
7
7
8
/// A single-value metric aggregation that computes the average of numeric values that are
8
9
/// extracted from the aggregated documents.
@@ -24,7 +25,7 @@ pub struct AverageAggregation {
24
25
/// By default they will be ignored but it is also possible to treat them as if they had a
25
26
/// value. Examples in JSON format:
26
27
/// { "field": "my_numbers", "missing": "10.0" }
27
- #[ serde( default ) ]
28
+ #[ serde( default , deserialize_with = "deserialize_option_f64" ) ]
28
29
pub missing : Option < f64 > ,
29
30
}
30
31
@@ -65,3 +66,62 @@ impl IntermediateAverage {
65
66
self . stats . finalize ( ) . avg
66
67
}
67
68
}
69
+
70
+ #[ cfg( test) ]
71
+ mod tests {
72
+ use super :: * ;
73
+
74
+ #[ test]
75
+ fn deserialization_with_missing_test1 ( ) {
76
+ let json = r#"{
77
+ "field": "score",
78
+ "missing": "10.0"
79
+ }"# ;
80
+ let avg: AverageAggregation = serde_json:: from_str ( json) . unwrap ( ) ;
81
+ assert_eq ! ( avg. field, "score" ) ;
82
+ assert_eq ! ( avg. missing, Some ( 10.0 ) ) ;
83
+ // no dot
84
+ let json = r#"{
85
+ "field": "score",
86
+ "missing": "10"
87
+ }"# ;
88
+ let avg: AverageAggregation = serde_json:: from_str ( json) . unwrap ( ) ;
89
+ assert_eq ! ( avg. field, "score" ) ;
90
+ assert_eq ! ( avg. missing, Some ( 10.0 ) ) ;
91
+
92
+ // from value
93
+ let avg: AverageAggregation = serde_json:: from_value ( json ! ( {
94
+ "field" : "score_f64" ,
95
+ "missing" : 10u64 ,
96
+ } ) )
97
+ . unwrap ( ) ;
98
+ assert_eq ! ( avg. missing, Some ( 10.0 ) ) ;
99
+ // from value
100
+ let avg: AverageAggregation = serde_json:: from_value ( json ! ( {
101
+ "field" : "score_f64" ,
102
+ "missing" : 10u32 ,
103
+ } ) )
104
+ . unwrap ( ) ;
105
+ assert_eq ! ( avg. missing, Some ( 10.0 ) ) ;
106
+ let avg: AverageAggregation = serde_json:: from_value ( json ! ( {
107
+ "field" : "score_f64" ,
108
+ "missing" : 10i8 ,
109
+ } ) )
110
+ . unwrap ( ) ;
111
+ assert_eq ! ( avg. missing, Some ( 10.0 ) ) ;
112
+ }
113
+
114
+ #[ test]
115
+ fn deserialization_with_missing_test_fail ( ) {
116
+ let json = r#"{
117
+ "field": "score",
118
+ "missing": "a"
119
+ }"# ;
120
+ let avg: Result < AverageAggregation , _ > = serde_json:: from_str ( json) ;
121
+ assert ! ( avg. is_err( ) ) ;
122
+ assert ! ( avg
123
+ . unwrap_err( )
124
+ . to_string( )
125
+ . contains( "Failed to parse f64 from string: \" a\" " ) ) ;
126
+ }
127
+ }
0 commit comments