1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
use std::collections::HashMap;
use serde::ser::{Serialize, Serializer};
use ::json::{MergeSerialize, serialize_map_optional_kv};
use ::units::JsonVal;
macro_rules! agg {
($b:ident) => {
impl<'a> $b<'a> {
pub fn field(field: &'a str) -> Self {
$b(Agg {
field: Some(field),
..Default::default()
})
}
pub fn script<S: Into<Script<'a>>>(script: S) -> Self {
$b(Agg {
script: script.into(),
..Default::default()
})
}
pub fn with_script<S: Into<Script<'a>>>(mut self, script: S) -> Self {
self.0.script = script.into();
self
}
pub fn with_missing<J: Into<JsonVal>>(mut self, missing: J) -> Self {
self.0.missing = Some(missing.into());
self
}
}
impl<'a> Serialize for $b<'a> {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer {
self.0.serialize(serializer)
}
}
}
}
#[derive(Debug, Default)]
pub struct Script<'a> {
pub inline: Option<&'a str>,
pub file: Option<&'a str>,
pub id: Option<&'a str>,
pub params: Option<HashMap<&'a str, JsonVal>>
}
#[derive(Debug, Default)]
pub struct Agg<'a, E>
where E: MergeSerialize {
pub field: Option<&'a str>,
pub script: Script<'a>,
pub missing: Option<JsonVal>,
pub extra: E
}
macro_rules! add_extra_option {
($n:ident, $e:ident, $t:ty) => {
pub fn $n<T: Into<$t>>(mut self, val: T) -> Self {
self.0.extra.$e = Some(val.into());
self
}
}
}
impl<'a, E> Serialize for Agg<'a, E>
where E: MergeSerialize {
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer {
let mut state = try!(serializer.serialize_map(None));
try!(serialize_map_optional_kv(serializer, &mut state, "field", &self.field));
try!(serialize_map_optional_kv(serializer, &mut state, "inline", &self.script.inline));
try!(serialize_map_optional_kv(serializer, &mut state, "file", &self.script.file));
try!(serialize_map_optional_kv(serializer, &mut state, "id", &self.script.id));
try!(serialize_map_optional_kv(serializer, &mut state, "params", &self.script.params));
try!(serialize_map_optional_kv(serializer, &mut state, "missing", &self.missing));
try!(self.extra.merge_serialize(serializer, &mut state));
serializer.serialize_map_end(state)
}
}
macro_rules! agg_as {
($n:ident,$st:ident,$tp:ident,$t:ident,$rt:ty) => {
pub fn $n<'a>(&'a self) -> Result<&'a $rt, EsError> {
match self {
&AggregationResult::$st(ref res) => {
match res {
&$tp::$t(ref res) => Ok(res),
_ => Err(EsError::EsError(format!("Wrong type: {:?}", self)))
}
},
_ => Err(EsError::EsError(format!("Wrong type: {:?}", self)))
}
}
}
}