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
287
288
289
290
291
292
293
294
295
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(Query::term("test", 1))
///     .function(RandomScore::new().filter(Query::term("test", 1)).weight(2.0))
///     .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 {
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    query: Option<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() -> FunctionScoreQuery {
        FunctionScoreQuery {
            query: None,
            functions: Default::default(),
            max_boost: None,
            min_score: None,
            score_mode: None,
            boost_mode: None,
            boost: None,
            _name: None,
        }
    }
}

impl FunctionScoreQuery {
    /// Base function score query
    pub fn query<T>(mut self, query: T) -> Self
    where
        T: Into<Option<Query>>,
    {
        self.query = query.into().map(Box::new);
        self
    }

    /// 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().function(RandomScore::new()),
            json!({
                "function_score": {
                    "functions": [
                        {
                            "random_score": {}
                        }
                    ]
                }
            }),
        );

        assert_serialize_query(
            Query::function_score()
                .query(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"
                }
            }),
        );
    }

    #[test]
    fn issue_24() {
        let _ = json!({
            "function_score": {
                "boost_mode": "replace",
                "functions": [
                    {
                        "filter": { "term": { "type": "stop" } },
                        "field_value_factor": {
                            "field": "weight",
                            "factor": 1.0,
                            "missing": 1.0
                        },
                        "weight": 1.0
                    },
                    {
                        "filter": { "term": { "type": "address" } },
                        "filter": { "term": { "type": "addr" } },
                        "field_value_factor": {
                            "field": "weight",
                            "factor": 1.0,
                            "missing": 1.0
                        },
                        "weight": 1.0
                    },
                    {
                        "filter": { "term": { "type": "admin" } },
                        "field_value_factor": {
                            "field": "weight",
                            "factor": 1.0,
                            "missing": 1.0
                        },
                        "weight": 1.0
                    },
                    {
                        "filter": { "term": { "type": "poi" } },
                        "field_value_factor": {
                            "field": "weight",
                            "factor": 1.0,
                            "missing": 1.0
                        },
                        "weight": 1.0
                    },
                    {
                        "filter": { "term": { "type": "street" } },
                        "field_value_factor": {
                            "field": "weight",
                            "factor": 1.0,
                            "missing": 1.0
                        },
                        "weight": 1.0
                    }
                ]
            }
        });

        let _ = Query::function_score()
            .boost_mode(FunctionBoostMode::Replace)
            .function(
                FieldValueFactor::new("weight")
                    .factor(1.0)
                    .missing(1.0)
                    .weight(1.0)
                    .filter(Query::term("type", "stop")),
            )
            .function(
                FieldValueFactor::new("weight")
                    .factor(1.0)
                    .missing(1.0)
                    .weight(1.0)
                    .filter(Query::terms("type", ["address", "addr"])),
            )
            .function(
                FieldValueFactor::new("weight")
                    .factor(1.0)
                    .missing(1.0)
                    .weight(1.0)
                    .filter(Query::term("type", "admin")),
            )
            .function(
                FieldValueFactor::new("weight")
                    .factor(1.0)
                    .missing(1.0)
                    .weight(1.0)
                    .filter(Query::term("type", "poi")),
            )
            .function(
                FieldValueFactor::new("weight")
                    .factor(1.0)
                    .missing(1.0)
                    .weight(1.0)
                    .filter(Query::term("type", "street")),
            );
    }
}