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
use super::{SortMode, SortOrder};
use crate::util::ShouldSkip;
use crate::Term;
use serde::Serialize;

/// 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, Serialize)]
#[serde(remote = "Self")]
pub struct FieldSort {
    #[serde(skip)]
    field: String,

    #[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")]
    format: Option<String>,

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

impl FieldSort {
    /// Creates an instance of [FieldSort]
    pub fn new<T>(field: T) -> Self
    where
        T: ToString,
    {
        Self {
            field: field.to_string(),
            order: None,
            mode: None,
            unmapped_type: None,
            format: None,
            missing: None,
        }
    }

    /// Creates an instance of [FieldSort] by ascending order
    pub fn ascending<T>(field: T) -> Self
    where
        T: ToString,
    {
        Self::new(field).order(SortOrder::Asc)
    }

    /// Creates an instance of [FieldSort] by descending order
    pub fn descending<T>(field: T) -> Self
    where
        T: ToString,
    {
        Self::new(field).order(SortOrder::Desc)
    }

    /// 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.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.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<T>(mut self, unmapped_type: T) -> Self
    where
        T: ToString,
    {
        self.unmapped_type = Some(unmapped_type.to_string());
        self
    }

    /// Optional format for datetime sorts
    ///
    /// <https://www.elastic.co/guide/en/elasticsearch/reference/current/sort-search-results.html#_ignoring_unmapped_fields>
    pub fn format<T>(mut self, format: T) -> Self
    where
        T: ToString,
    {
        self.format = Some(format.to_string());
        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<T>(mut self, missing: T) -> Self
    where
        T: Serialize,
    {
        self.missing = Term::new(missing);
        self
    }
}

impl IntoIterator for FieldSort {
    type Item = Self;

    type IntoIter = std::option::IntoIter<Self::Item>;

    fn into_iter(self) -> Self::IntoIter {
        Some(self).into_iter()
    }
}

serialize_keyed!(FieldSort: field);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::util::assert_serialize;
    use crate::SortSpecialField;

    #[test]
    fn serialization() {
        assert_serialize(FieldSort::new("test"), json!({"test": {}}));

        assert_serialize(
            FieldSort::new(SortSpecialField::Score),
            json!({"_score": {}}),
        );

        assert_serialize(
            FieldSort::ascending("field"),
            json!({ "field": { "order": "asc" } }),
        );

        assert_serialize(
            FieldSort::descending("field"),
            json!({ "field": { "order": "desc" } }),
        );

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