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
//! Allows you to add one or more sorts on specific fields.
//! Each sort can be reversed as well.
//! The sort is defined on a per field level, with special field name for `_score` to sort by score, and `_doc` to sort by index order.
//!
//! <https://www.elastic.co/guide/en/elasticsearch/reference/master/search-your-data.html>
use serde::ser::{Serialize, Serializer};

use crate::util::*;

/// The order defaults to `desc` when sorting on the `_score`, and defaults to `asc` when sorting on anything else.
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_sort_order>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SortOrder {
    /// Sort in ascending order
    Asc,

    /// Sort in descending order
    Desc,
}

/// Elasticsearch supports sorting by array or multi-valued fields. The `mode` option controls what array value is picked for sorting the document it belongs to.
///
/// The default sort mode in the ascending sort order is `min` — the lowest value is picked. The default sort mode in the descending order is `max` — the highest value is picked.
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_sort_mode_option>
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SortMode {
    /// Pick the lowest value.
    Min,

    /// Pick the highest value.
    Max,

    /// Use the sum of all values as sort value.\
    /// Only applicable for number based array fields.
    Sum,

    /// Use the average of all values as sort value.\
    /// Only applicable for number based array fields.
    Avg,

    /// Use the median of all values as sort value.\
    /// Only applicable for number based array fields.
    Median,
}

/// The `missing` parameter specifies how docs which are missing the sort field should be treated:
///
/// The `missing` value can be set to `_last`, `_first`, or a custom value (that will be used for missing docs as the sort value). The default is `_last`.
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_missing_values>
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SortMissing {
    /// Sorts missing fields first
    First,

    /// Sorts missing field last
    Last,

    /// Provide a custom scalar value for missing fields
    Custom(String),
}

impl Serialize for SortMissing {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::First => "_first".serialize(serializer),
            Self::Last => "_last".serialize(serializer),
            Self::Custom(field) => field.as_str().serialize(serializer),
        }
    }
}

impl From<String> for SortMissing {
    fn from(value: String) -> Self {
        SortMissing::Custom(value)
    }
}

impl From<&str> for SortMissing {
    fn from(value: &str) -> Self {
        SortMissing::Custom(value.into())
    }
}

/// Allows you to add one or more sorts on specific fields. Each sort can be reversed as well. The sort is defined on a per field level.
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#sort-search-results>
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SortField {
    /// Sort by `_id` field
    Id,

    /// Sort by `_score`
    Score,

    /// Sort by key within aggregations
    Key,

    /// Sort by count within aggregations,
    Count,

    /// Sort by index order
    Doc,

    /// Sorts by a given field name
    Field(String),
}

impl Serialize for SortField {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Id => "_id".serialize(serializer),
            Self::Score => "_score".serialize(serializer),
            Self::Key => "_key".serialize(serializer),
            Self::Count => "_count".serialize(serializer),
            Self::Doc => "_doc".serialize(serializer),
            Self::Field(field) => field.as_str().serialize(serializer),
        }
    }
}

impl From<String> for SortField {
    fn from(field: String) -> Self {
        SortField::Field(field)
    }
}

impl From<&str> for SortField {
    fn from(field: &str) -> Self {
        SortField::Field(field.into())
    }
}

/// Sorts search hits by other field values
///
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#sort-search-results>
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct Sort(KeyValuePair<SortField, SortInner>);

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)]
struct SortInner {
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    order: Option<SortOrder>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    mode: Option<SortMode>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    unmapped_type: Option<String>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    missing: Option<SortMissing>,
}

impl Sort {
    /// Creates an instance of [`Sort`]
    pub fn new(field: impl Into<SortField>) -> Self {
        Self(KeyValuePair::new(field.into(), Default::default()))
    }

    /// Explicit order
    ///
    /// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_sort_order>
    pub fn order(mut self, order: SortOrder) -> Self {
        self.0.value.order = Some(order);
        self
    }

    /// Sort mode for numeric fields
    ///
    /// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_sort_mode_option>
    pub fn mode(mut self, mode: SortMode) -> Self {
        self.0.value.mode = Some(mode);
        self
    }

    /// Fallback type if mapping is not defined
    ///
    /// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_ignoring_unmapped_fields>
    pub fn unmapped_type(mut self, unmapped_type: impl Into<String>) -> Self {
        self.0.value.unmapped_type = Some(unmapped_type.into());
        self
    }

    /// The missing parameter specifies how docs which are missing the sort field should be treated
    ///
    /// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_missing_values>
    pub fn missing(mut self, missing: impl Into<SortMissing>) -> Self {
        self.0.value.missing = Some(missing.into());
        self
    }
}

impl From<Sort> for Vec<Sort> {
    fn from(sort: Sort) -> Self {
        vec![sort]
    }
}

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

    test_serialization! {
        with_field_only(
            Sort::new("test"),
            json!({"test": {}})
        );

        with_predefined_sort_field(
            Sort::new(SortField::Id),
            json!({"_id": {}})
        );

        with_all_attributes(
            Sort::new("test")
                .order(SortOrder::Asc)
                .mode(SortMode::Max)
                .unmapped_type("long")
                .missing("miss"),
            json!({
                "test": {
                    "order": "asc",
                    "mode": "max",
                    "unmapped_type": "long",
                    "missing": "miss",
                }
            })
        );
    }
}