elasticsearch_dsl/search/aggregations/params/
terms_order.rs

1use crate::{
2    util::{KeyValuePair, ShouldSkip},
3    SortOrder,
4};
5
6/// Terms Aggregation sorting criterion
7#[derive(Clone, PartialEq, Eq, Serialize)]
8pub struct TermsOrder(KeyValuePair<String, SortOrder>);
9
10impl std::fmt::Debug for TermsOrder {
11    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12        f.debug_struct("TermsOrder")
13            .field(&self.0.key, &self.0.value)
14            .finish()
15    }
16}
17
18impl TermsOrder {
19    /// Creates an instance of [TermsOrder]
20    ///
21    /// - `key` - Key to sort by
22    /// - `order` - Sorting order
23    pub fn new<T>(key: T, order: SortOrder) -> Self
24    where
25        T: ToString,
26    {
27        Self(KeyValuePair::new(key.to_string(), order))
28    }
29
30    /// Sorts terms by a given key in ascending order
31    pub fn ascending<T>(key: T) -> Self
32    where
33        T: ToString,
34    {
35        Self::new(key, SortOrder::Asc)
36    }
37
38    /// Sorts terms by a given key in descending order
39    pub fn descending<T>(key: T) -> Self
40    where
41        T: ToString,
42    {
43        Self::new(key, SortOrder::Desc)
44    }
45
46    /// Sorts terms by count ascending
47    pub fn count_ascending() -> Self {
48        Self::ascending("_count")
49    }
50
51    /// Sorts terms by count descending
52    pub fn count_descending() -> Self {
53        Self::descending("_count")
54    }
55
56    /// Sorts terms by count ascending
57    pub fn key_ascending() -> Self {
58        Self::ascending("_key")
59    }
60
61    /// Sorts terms by count descending
62    pub fn key_descending() -> Self {
63        Self::descending("_key")
64    }
65}
66
67/// Terms Aggregation sorting criteria
68#[derive(Default, Clone, PartialEq, Eq, Serialize)]
69pub struct TermsOrderCollection(Vec<TermsOrder>);
70
71impl ShouldSkip for TermsOrderCollection {
72    fn should_skip(&self) -> bool {
73        self.0.should_skip()
74    }
75}
76
77impl std::fmt::Debug for TermsOrderCollection {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        self.0.fmt(f)
80    }
81}
82
83impl From<TermsOrder> for TermsOrderCollection {
84    fn from(value: TermsOrder) -> Self {
85        Self(vec![value])
86    }
87}
88
89impl<T> From<T> for TermsOrderCollection
90where
91    T: IntoIterator,
92    T::Item: Into<TermsOrder>,
93{
94    fn from(value: T) -> Self {
95        Self(value.into_iter().map(Into::into).collect())
96    }
97}
98
99#[cfg(test)]
100mod tests {
101    use super::*;
102    use crate::util::assert_serialize;
103
104    #[test]
105    fn serializes() {
106        assert_serialize(TermsOrder::key_ascending(), json!({ "_key": "asc" }));
107        assert_serialize(TermsOrder::count_descending(), json!({ "_count": "desc" }));
108    }
109}