logo
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
use crate::search::*;
use crate::util::*;

/// The `function_score` allows you to modify the score of documents that are retrieved by a query.
///
/// This can be useful if, for example, a score function is computationally expensive and it is
/// sufficient to compute the score on a filtered set of documents.
///
/// To use `function_score`, the user has to define a query and one or more functions, that compute
/// a new score for each document returned by the query.
///
/// To create function_score query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::function_score(Query::term("test", 1))
///     .function(RandomScore::new())
///     .function(Weight::new(2.0))
///     .max_boost(2.2)
///     .min_score(2.3)
///     .score_mode(FunctionScoreMode::Avg)
///     .boost_mode(FunctionBoostMode::Max)
///     .boost(1.1)
///     .name("test");
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(remote = "Self")]
pub struct FunctionScoreQuery {
    query: Box<Query>,

    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    functions: Vec<Function>,

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

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

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

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

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

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

impl Query {
    /// Creates an instance of [`FunctionScoreQuery`]
    pub fn function_score<T>(query: T) -> FunctionScoreQuery
    where
        T: Into<Query>,
    {
        FunctionScoreQuery {
            query: Box::new(query.into()),
            functions: Default::default(),
            max_boost: None,
            min_score: None,
            score_mode: None,
            boost_mode: None,
            boost: None,
            _name: None,
        }
    }
}

impl FunctionScoreQuery {
    /// Push function to the list
    pub fn function<T>(mut self, function: T) -> Self
    where
        T: Into<Option<Function>>,
    {
        let function = function.into();

        if let Some(function) = function {
            self.functions.push(function);
        }

        self
    }

    /// Maximum score value after applying all the functions
    pub fn max_boost<T>(mut self, max_boost: T) -> Self
    where
        T: num_traits::AsPrimitive<f32>,
    {
        self.max_boost = Some(max_boost.as_());
        self
    }

    /// By default, modifying the score does not change which documents match. To exclude documents

    /// that do not meet a certain score threshold the `min_score` parameter can be set to the
    /// desired score threshold.
    pub fn min_score<T>(mut self, min_score: T) -> Self
    where
        T: Into<f32>,
    {
        self.min_score = Some(min_score.into());
        self
    }

    /// Each document is scored by the defined functions. The parameter `score_mode` specifies how
    /// the computed scores are combined
    pub fn score_mode(mut self, score_mode: FunctionScoreMode) -> Self {
        self.score_mode = Some(score_mode);
        self
    }

    /// The newly computed score is combined with the score of the query. The parameter
    /// `boost_mode` defines how.
    pub fn boost_mode(mut self, boost_mode: FunctionBoostMode) -> Self {
        self.boost_mode = Some(boost_mode);
        self
    }

    add_boost_and_name!();
}

impl ShouldSkip for FunctionScoreQuery {
    fn should_skip(&self) -> bool {
        self.query.should_skip() || self.functions.should_skip()
    }
}

serialize_with_root!("function_score": FunctionScoreQuery);

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

    #[test]
    fn serialization() {
        assert_serialize_query(
            Query::function_score(Query::term("test", 1)).function(RandomScore::new()),
            json!({
                "function_score": {
                    "query": {
                        "term": {
                            "test": {
                                "value": 1
                            }
                        }
                    },
                    "functions": [
                        {
                            "random_score": {}
                        }
                    ]
                }
            }),
        );

        assert_serialize_query(
            Query::function_score(Query::term("test", 1))
                .function(RandomScore::new())
                .function(Weight::new(2.0))
                .max_boost(2.2)
                .min_score(2.3)
                .score_mode(FunctionScoreMode::Avg)
                .boost_mode(FunctionBoostMode::Max)
                .boost(1.1)
                .name("test"),
            json!({
                "function_score": {
                    "query": {
                        "term": {
                            "test": {
                                "value": 1
                            }
                        }
                    },
                    "functions": [
                        {
                            "random_score": {}
                        },
                        {
                            "weight": 2.0
                        }
                    ],
                    "max_boost": 2.2,
                    "min_score": 2.3,
                    "score_mode": "avg",
                    "boost_mode": "max",
                    "boost": 1.1,
                    "_name": "test"
                }
            }),
        );
    }
}