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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
use serde::de::DeserializeOwned;
use serde_json::{Map, Value};
use super::{Shards, HttpResponseHead};
use parse::{IsOk, ResponseBody, Unbuffered, MaybeOkResponse};
use error::*;
use std::borrow::Cow;
use std::collections::BTreeMap;
use std::slice::Iter;
#[derive(Deserialize, Debug)]
pub struct SearchResponseOf<T> {
pub took: u64,
pub timed_out: bool,
#[serde(rename = "_shards")]
pub shards: Shards,
pub hits: Hits<T>,
pub aggregations: Option<Aggregations>,
pub status: Option<u16>,
}
pub type SearchResponse = SearchResponseOf<Hit<Value>>;
impl<T: DeserializeOwned> IsOk for SearchResponseOf<T> {
fn is_ok<B: ResponseBody>(head: HttpResponseHead, body: Unbuffered<B>) -> Result<MaybeOkResponse<B>, ParseResponseError> {
match head.status() {
200...299 => Ok(MaybeOkResponse::ok(body)),
_ => Ok(MaybeOkResponse::err(body)),
}
}
}
impl<T> SearchResponseOf<T> {
pub fn hits(&self) -> &[T] {
&self.hits.hits()
}
pub fn aggs(&self) -> &Aggregations {
self.aggregations.as_ref().unwrap()
}
}
#[derive(Deserialize, Debug)]
pub struct Hits<T> {
pub total: u64,
pub max_score: Option<f32>,
pub hits: Vec<T>,
}
impl<T> Hits<T> {
fn hits(&self) -> &[T] {
&self.hits
}
}
#[derive(Deserialize, Debug)]
pub struct Hit<T> {
#[serde(rename = "_index")]
pub index: String,
#[serde(rename = "_type")]
pub ty: String,
#[serde(rename = "_version")]
pub version: Option<u32>,
#[serde(rename = "_score")]
pub score: Option<f32>,
#[serde(rename = "_source")]
pub source: Option<T>,
#[serde(rename="_routing")]
pub routing: Option<String>,
}
#[derive(Deserialize, Debug)]
pub struct Aggregations(Value);
impl<'a> IntoIterator for &'a Aggregations {
type Item = RowData<'a>;
type IntoIter = AggregationIterator<'a>;
fn into_iter(self) -> AggregationIterator<'a> {
AggregationIterator::new(self)
}
}
#[derive(Debug)]
pub struct AggregationIterator<'a> {
current_row: Option<RowData<'a>>,
current_row_finished: bool,
iter_stack: Vec<(Option<&'a String>, Iter<'a, Value>)>,
aggregations: &'a Aggregations,
}
impl<'a> AggregationIterator<'a> {
fn new(a: &'a Aggregations) -> AggregationIterator<'a> {
let o = a.0
.as_object()
.expect("Not implemented, we only cater for bucket objects");
let s = o.into_iter()
.filter_map(|(key, child)| {
child.as_object()
.and_then(|child| child.get("buckets"))
.and_then(Value::as_array)
.map(|array| (Some(key), array.iter()))
})
.collect();
AggregationIterator {
current_row: None,
current_row_finished: false,
iter_stack: s,
aggregations: a,
}
}
}
type Object = Map<String, Value>;
type RowData<'a> = BTreeMap<Cow<'a, str>, &'a Value>;
fn insert_value<'a>(fieldname: &str,
json_object: &'a Object,
keyname: &str,
rowdata: &mut RowData<'a>) {
if let Some(v) = json_object.get(fieldname) {
let field_name = format!("{}_{}", keyname, fieldname);
debug!("ITER: Insert value! {} {:?}", field_name, v);
rowdata.insert(Cow::Owned(field_name), v);
}
}
impl<'a> Iterator for AggregationIterator<'a> {
type Item = RowData<'a>;
fn next(&mut self) -> Option<RowData<'a>> {
if self.current_row.is_none() {
self.current_row = Some(BTreeMap::new())
}
loop {
if let Some(mut i) = self.iter_stack.pop() {
let n = i.1.next();
let active_name = &i.0.unwrap();
let mut has_buckets = false;
self.iter_stack.push(i);
debug!("ITER: Depth {}", self.iter_stack.len());
if let Some(n) = n {
if let Some(ref mut row) = self.current_row {
debug!("ITER: Row: {:?}", row);
for (key, value) in n.as_object().expect("Shouldn't get here!") {
if let Some(c) = value.as_object() {
if let Some(buckets) = c.get("buckets") {
has_buckets = true;
if let Value::Array(ref a) = *buckets {
self.iter_stack.push((Some(key), a.iter()));
}
continue;
}
if let Some(v) = c.get("value") {
debug!("ITER: Insert value! {} {:?}", key, v);
row.insert(Cow::Borrowed(key), v);
continue;
}
insert_value("count", c, key, row);
insert_value("min", c, key, row);
insert_value("max", c, key, row);
insert_value("avg", c, key, row);
insert_value("sum", c, key, row);
insert_value("sum_of_squares", c, key, row);
insert_value("variance", c, key, row);
insert_value("std_deviation", c, key, row);
if c.contains_key("std_deviation_bounds") {
if let Some(child_values) = c.get("std_deviation_bounds")
.unwrap()
.as_object() {
let u = child_values.get("upper");
let l = child_values.get("lower");
let un = format!("{}_std_deviation_bounds_upper", key);
let ln = format!("{}_std_deviation_bounds_lower", key);
debug!("ITER: Insert std_dev_bounds! {} {} u: {:?} l: \
{:?}",
un,
ln,
u.unwrap(),
l.unwrap());
row.insert(Cow::Owned(un), u.unwrap());
row.insert(Cow::Owned(ln), l.unwrap());
}
}
}
if key == "key" {
debug!("ITER: Insert bucket! {} {:?}", active_name, value);
row.insert(Cow::Borrowed(active_name), value);
} else if key == "doc_count" {
debug!("ITER: Insert bucket count! {} {:?}", active_name, value);
let field_name = format!("{}_doc_count", active_name);
row.insert(Cow::Owned(field_name), value);
}
}
}
} else {
debug!("ITER: Exit!");
self.iter_stack.pop();
continue;
}
if !has_buckets {
debug!("ITER: Bucketless!");
break;
} else {
debug!("ITER: Dive!");
}
} else {
debug!("ITER: Done!");
self.current_row = None;
break;
};
}
match self.current_row {
Some(ref x) => Some(x.clone()),
None => None,
}
}
}