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
282
283
284
285
286
use crate::util::*;
use serde_json::Value;
use std::collections::HashMap;

/// Search response
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SearchResponse<H = Value, IH = Value> {
    /// The time that it took Elasticsearch to process the query
    pub took: u32,

    /// Indicates whether there have been timed-out shards, if `true` - responses are partial
    pub timed_out: bool,

    /// Number of shards touched with their states
    #[serde(rename = "_shards")]
    pub shards: Shards,

    /// Search hits
    pub hits: Hits<H, IH>,

    /// Search aggregations
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pub aggregations: Option<Value>,
}

/// Number of shards touched with their states
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Shards {
    /// Total number of touched shards
    pub total: u32,

    /// Total number of successful shards
    pub successful: u32,

    /// Total number of skipped shards
    pub skipped: u32,

    /// Total number of failed shards
    pub failed: u32,

    /// Partial response failures
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pub failures: Option<Value>,
}

/// Matched hits
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Hits<H, IH> {
    /// Total number of matched documents
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pub total: Option<Total>,

    /// Maximum document score. [`None`] when documents are implicitly sorted
    /// by a field other than `_score`
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pub max_score: Option<f32>,

    /// Matched hits
    #[serde(default = "Vec::new")]
    pub hits: Vec<Hit<H, IH>>,
}

/// Represents a single matched document
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Hit<H, IH> {
    /// Document index
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_index")]
    pub index: Option<String>,

    /// Document ID
    #[serde(rename = "_id")]
    pub id: String,

    /// Document score. [`None`] when documents are implicitly sorted by a
    /// field other than `_score`
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_score")]
    pub score: Option<f32>,

    /// Document source
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_source")]
    pub source: Option<H>,

    /// Highlighted matches
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", default)]
    pub highlight: HashMap<String, Vec<String>>,

    /// Inner hits
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pub inner_hits: Option<InnerHitsResponse<IH>>,

    /// Matched queries
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", default)]
    pub matched_queries: Vec<String>,

    /// Values document was sorted by
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", default)]
    pub sort: Vec<Value>,

    /// Field values for the documents. Need to be specified in the request
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", default)]
    pub fields: std::collections::BTreeMap<String, Value>,
}

/// Hit can be considered equal to another hit when index and id are equal
impl<H, IH> PartialEq for Hit<H, IH> {
    fn eq(&self, other: &Self) -> bool {
        self.index == other.index && self.id == other.id
    }
}

/// Represents inner hits
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct InnerHitsResponse<IH> {
    /// Inner hits items
    pub items: InnerHitsItems<IH>,
}

/// Represents inner hits
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct InnerHitsItems<IH> {
    /// The actual inner hits
    pub hits: InnerHitsItemsHits<IH>,
}

/// Matched inner hits
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct InnerHitsItemsHits<IH> {
    /// Total number of matched documents
    #[serde(default)]
    pub total: Option<Total>,

    /// Maximum document score. [`None`] when documents are implicitly sorted
    /// by a field other than `_score`
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pub max_score: Option<f32>,

    /// Matched hits
    #[serde(default = "Vec::new")]
    pub hits: Vec<InnerHit<IH>>,
}

/// Represents a single matched inner hit document
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct InnerHit<IH> {
    /// Document index
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_index")]
    pub index: Option<String>,

    /// Document ID
    #[serde(rename = "_id")]
    pub id: String,

    /// Document score. [`None`] when documents are implicitly sorted by a
    /// field other than `_score`
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_score")]
    pub score: Option<f32>,

    /// Nested document metadata
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_nested")]
    pub nested: Option<Nested>,

    /// Document source
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", rename = "_source")]
    pub source: Option<IH>,

    /// Matched queries
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", default)]
    pub matched_queries: Vec<String>,

    /// Values document was sorted by
    #[serde(skip_serializing_if = "ShouldSkip::should_skip", default)]
    pub sort: Vec<Value>,
}

/// Total number of matched documents
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq)]
pub struct Total {
    /// Number of total documents
    pub value: u64,

    /// Relation to total number of matched documents
    pub relation: Relation,
}

impl Total {
    /// Create default Total instance
    pub fn new(value: Option<u64>) -> Self {
        Total {
            value: value.unwrap_or(0),
            relation: Relation::Equal,
        }
    }
}

/// Nested document metadata
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Nested {
    /// Field
    pub field: String,

    /// Offset
    pub offset: u64,
}

/// Relation to total number of matched documents
#[derive(Debug, Copy, Clone, Serialize, Deserialize, PartialEq)]
pub enum Relation {
    /// When `track_total_hits` is `false` (default), Elasticsearch returns that
    /// there have been more than 10,000 documents
    #[serde(rename = "gte")]
    GreaterThanOrEqualTo,

    /// When there are less than 10,000 documents or `track_total_hits` is set
    /// to `true`, exact number of matched documents will be brought back
    #[serde(rename = "eq")]
    Equal,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn deserializes_successfully() {
        let json = serde_json::json!({
          "took": 6,
          "timed_out": false,
          "_shards": {
            "total": 10,
            "successful": 5,
            "skipped": 3,
            "failed": 2
          },
          "hits": {
            "total": {
              "value": 10000,
              "relation": "gte"
            },
            "max_score": 1.0,
            "hits": [
              {
                "_index": "_index",
                "_type": "_doc",
                "_id": "123",
                "_score": 1.0
              }
            ]
          }
        });

        let actual: SearchResponse = serde_json::from_value(json).unwrap();

        let expected = SearchResponse {
            took: 6,
            timed_out: false,
            shards: Shards {
                total: 10,
                successful: 5,
                skipped: 3,
                failed: 2,
                failures: Default::default(),
            },
            hits: Hits {
                total: Some(Total {
                    value: 10_000,
                    relation: Relation::GreaterThanOrEqualTo,
                }),
                max_score: Some(1.0),
                hits: vec![Hit {
                    index: Some("_index".into()),
                    id: "123".into(),
                    score: Some(1.0),
                    source: None,
                    highlight: Default::default(),
                    inner_hits: None,
                    matched_queries: Default::default(),
                    sort: Default::default(),
                    fields: Default::default(),
                }],
            },
            aggregations: None,
        };

        assert_eq!(actual, expected);
    }
}