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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use crate::search::*;
use crate::util::*;
use serde::Serialize;

/// Boosts the relevance score of documents based on the numeric value of a `rank_feature` or
/// `rank_features` field.
///
/// To create a rank feature query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test");
/// ```
/// To apply mathematical functions:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test").saturation();
/// # let query =
/// Query::rank_feature("test").saturation().pivot(2.2);
/// # let query =
/// Query::rank_feature("test").logarithm(3.0);
/// # let query =
/// Query::rank_feature("test").sigmoid(1.0, 2.0);
/// # let query =
/// Query::rank_feature("test").linear();
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-rank-feature-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RankFeatureQuery {
    #[serde(rename = "rank_feature")]
    inner: Inner,
}

/// Boosts the relevance score of documents based on the numeric value of a `rank_feature` or
/// `rank_features` field.
///
/// To create a rank feature query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test");
/// ```
/// To apply mathematical functions:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test").saturation();
/// # let query =
/// Query::rank_feature("test").saturation().pivot(2.2);
/// # let query =
/// Query::rank_feature("test").logarithm(3.0);
/// # let query =
/// Query::rank_feature("test").sigmoid(1.0, 2.0);
/// # let query =
/// Query::rank_feature("test").linear();
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-rank-feature-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RankFeatureSaturationQuery {
    #[serde(rename = "rank_feature")]
    inner: InnerSaturation,
}

/// Boosts the relevance score of documents based on the numeric value of a `rank_feature` or
/// `rank_features` field.
///
/// To create a rank feature query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test");
/// ```
/// To apply mathematical functions:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test").saturation();
/// # let query =
/// Query::rank_feature("test").saturation().pivot(2.2);
/// # let query =
/// Query::rank_feature("test").logarithm(3.0);
/// # let query =
/// Query::rank_feature("test").sigmoid(1.0, 2.0);
/// # let query =
/// Query::rank_feature("test").linear();
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-rank-feature-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RankFeatureLogarithmQuery {
    #[serde(rename = "rank_feature")]
    inner: InnerLogarithm,
}

/// Boosts the relevance score of documents based on the numeric value of a `rank_feature` or
/// `rank_features` field.
///
/// To create a rank feature query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test");
/// ```
/// To apply mathematical functions:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test").saturation();
/// # let query =
/// Query::rank_feature("test").saturation().pivot(2.2);
/// # let query =
/// Query::rank_feature("test").logarithm(3.0);
/// # let query =
/// Query::rank_feature("test").sigmoid(1.0, 2.0);
/// # let query =
/// Query::rank_feature("test").linear();
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-rank-feature-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RankFeatureSigmoidQuery {
    #[serde(rename = "rank_feature")]
    inner: InnerSigmoid,
}

/// Boosts the relevance score of documents based on the numeric value of a `rank_feature` or
/// `rank_features` field.
///
/// To create a rank feature query:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test");
/// ```
/// To apply mathematical functions:
/// ```
/// # use elasticsearch_dsl::queries::*;
/// # use elasticsearch_dsl::queries::params::*;
/// # let query =
/// Query::rank_feature("test").saturation();
/// # let query =
/// Query::rank_feature("test").saturation().pivot(2.2);
/// # let query =
/// Query::rank_feature("test").logarithm(3.0);
/// # let query =
/// Query::rank_feature("test").sigmoid(1.0, 2.0);
/// # let query =
/// Query::rank_feature("test").linear();
/// ```
/// <https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-rank-feature-query.html>
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct RankFeatureLinearQuery {
    #[serde(rename = "rank_feature")]
    inner: InnerLinear,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Saturation {
    #[serde(skip_serializing_if = "ShouldSkip::should_skip")]
    pivot: Option<f64>,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Logarithm {
    scaling_factor: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Sigmoid {
    pivot: f64,
    exponent: f64,
}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Linear {}

#[derive(Debug, Clone, PartialEq, Serialize)]
struct Inner {
    field: String,

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

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

#[derive(Debug, Clone, PartialEq, Serialize)]
struct InnerSaturation {
    field: String,

    saturation: Saturation,

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

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

#[derive(Debug, Clone, PartialEq, Serialize)]
struct InnerLogarithm {
    field: String,

    log: Logarithm,

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

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

#[derive(Debug, Clone, PartialEq, Serialize)]
struct InnerSigmoid {
    field: String,

    sigmoid: Sigmoid,

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

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

#[derive(Debug, Clone, PartialEq, Serialize)]
struct InnerLinear {
    field: String,

    linear: Linear,

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

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

impl Query {
    /// Creates an instance of [`RankFeatureQuery`]
    ///
    /// - `field` - `rank_feature` or `rank_features` field used to boost relevance scores
    pub fn rank_feature(field: impl Into<String>) -> RankFeatureQuery {
        RankFeatureQuery {
            inner: Inner {
                field: field.into(),
                boost: None,
                _name: None,
            },
        }
    }
}

impl RankFeatureQuery {
    /// The `saturation` function gives a score equal to `S / (S + pivot)`, where `S` is the value
    /// of the rank feature field and `pivot` is a configurable pivot value so that the result will
    /// be less than `0.5` if `S` is less than pivot and greater than `0.5` otherwise.
    /// Scores are always `(0,1)`.
    ///
    /// If the rank feature has a negative score impact then the function will be computed as
    /// `pivot / (S + pivot)`, which decreases when `S` increases.
    ///
    /// If a `pivot` value is not provided, Elasticsearch computes a default value equal to the
    /// approximate geometric mean of all rank feature values in the index. We recommend using this
    /// default value if you haven’t had the opportunity to train a good pivot value.
    pub fn saturation(self) -> RankFeatureSaturationQuery {
        RankFeatureSaturationQuery {
            inner: InnerSaturation {
                field: self.inner.field,
                boost: self.inner.boost,
                _name: self.inner._name,
                saturation: Saturation { pivot: None },
            },
        }
    }

    /// The `log` function gives a score equal to `log(scaling_factor + S)`, where `S` is the value
    /// of the rank feature field and `scaling_factor` is a configurable scaling factor.
    /// Scores are unbounded.
    ///
    /// This function only supports rank features that have a positive score impact.
    pub fn logarithm(self, scaling_factor: f64) -> RankFeatureLogarithmQuery {
        RankFeatureLogarithmQuery {
            inner: InnerLogarithm {
                field: self.inner.field,
                boost: self.inner.boost,
                _name: self.inner._name,
                log: Logarithm { scaling_factor },
            },
        }
    }

    /// The `sigmoid` function is an extension of `saturation` which adds a configurable exponent.
    /// Scores are computed as `S^exp^ / (S^exp^ + pivot^exp^)`. Like for the `saturation` function,
    /// `pivot` is the value of `S` that gives a score of `0.5` and scores are `(0,1)`.
    ///
    /// The `exponent` must be positive and is typically in `[0.5, 1]`. A good value should be
    /// computed via training. If you don’t have the opportunity to do so, we recommend you use the
    /// `saturation` function instead.
    pub fn sigmoid(self, pivot: f64, exponent: f64) -> RankFeatureSigmoidQuery {
        RankFeatureSigmoidQuery {
            inner: InnerSigmoid {
                field: self.inner.field,
                boost: self.inner.boost,
                _name: self.inner._name,
                sigmoid: Sigmoid { pivot, exponent },
            },
        }
    }

    /// The `linear` function is the simplest function, and gives a score equal to the indexed
    /// value of `S`, where `S` is the value of the rank feature field. If a rank feature field is
    /// indexed with `"positive_score_impact": true`, its indexed value is equal to `S` and rounded
    /// to preserve only 9 significant bits for the precision. If a rank feature field is indexed
    /// with `"positive_score_impact": false`, its indexed value is equal to `1/S` and rounded to
    /// preserve only 9 significant bits for the precision.
    pub fn linear(self) -> RankFeatureLinearQuery {
        RankFeatureLinearQuery {
            inner: InnerLinear {
                field: self.inner.field,
                boost: self.inner.boost,
                _name: self.inner._name,
                linear: Linear {},
            },
        }
    }

    add_boost_and_name!();
}

impl RankFeatureSaturationQuery {
    /// Sets pivot value
    pub fn pivot(mut self, pivot: impl Into<Option<f64>>) -> Self {
        self.inner.saturation.pivot = pivot.into();
        self
    }

    add_boost_and_name!();
}

impl RankFeatureLogarithmQuery {
    add_boost_and_name!();
}

impl RankFeatureSigmoidQuery {
    add_boost_and_name!();
}

impl RankFeatureLinearQuery {
    add_boost_and_name!();
}

impl ShouldSkip for RankFeatureQuery {}
impl ShouldSkip for RankFeatureSaturationQuery {}
impl ShouldSkip for RankFeatureLogarithmQuery {}
impl ShouldSkip for RankFeatureSigmoidQuery {}
impl ShouldSkip for RankFeatureLinearQuery {}

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

    test_serialization! {
        with_required_fields(
            Query::rank_feature("test"),
            json!({
                "rank_feature": {
                    "field": "test",
                }
            })
        );

        with_all_fields(
            Query::rank_feature("test").boost(2).name("query"),
            json!({
                "rank_feature": {
                    "field": "test",
                    "boost": 2,
                    "_name": "query",
                }
            })
        );

        with_saturation(
            Query::rank_feature("test").saturation().boost(2).name("query"),
            json!({
                "rank_feature": {
                    "field": "test",
                    "boost": 2,
                    "_name": "query",
                    "saturation": {},
                }
            })
        );

        with_saturation_and_pivot_value(
            Query::rank_feature("test").saturation().pivot(2.2).boost(2).name("query"),
            json!({
                "rank_feature": {
                    "field": "test",
                    "boost": 2,
                    "_name": "query",
                    "saturation": {
                        "pivot": 2.2,
                    },
                }
            })
        );

        with_logarithm(
            Query::rank_feature("test").logarithm(2.2).boost(2).name("query"),
            json!({
                "rank_feature": {
                    "field": "test",
                    "boost": 2,
                    "_name": "query",
                    "log": {
                        "scaling_factor": 2.2
                    },
                }
            })
        );

        with_sigmoid(
            Query::rank_feature("test").sigmoid(2.2, 3.3).boost(2).name("query"),
            json!({
                "rank_feature": {
                    "field": "test",
                    "boost": 2,
                    "_name": "query",
                    "sigmoid": {
                        "pivot": 2.2,
                        "exponent": 3.3,
                    },
                }
            })
        );

        with_linear(
            Query::rank_feature("test").linear().boost(2).name("query"),
            json!({
                "rank_feature": {
                    "field": "test",
                    "boost": 2,
                    "_name": "query",
                    "linear": {},
                }
            })
        );
    }
}