elasticsearch_dsl/search/queries/params/
negative_boost.rs

1//! A container type for boost values
2use std::{f32, fmt};
3
4/// A container type for boost values
5#[derive(Clone, Copy, PartialEq, PartialOrd, Serialize)]
6pub struct NegativeBoost(f32);
7
8impl fmt::Debug for NegativeBoost {
9    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
10        self.0.fmt(f)
11    }
12}
13
14impl fmt::Display for NegativeBoost {
15    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16        self.0.fmt(f)
17    }
18}
19
20impl NegativeBoost {
21    /// Minimum boost value
22    const MINIMUM: f32 = 0f32;
23
24    /// Maximum boost value
25    const MAXIMUM: f32 = 1f32;
26
27    /// Creates a new instance of a negative boost value
28    ///
29    /// Floating point number between `0` and `1.0` used to decrease the
30    /// [relevance scores](https://www.elastic.co/guide/en/elasticsearch/reference/current/query-filter-context.html#relevance-scores)
31    /// of documents matching the `negative` query.
32    pub fn new(boost: f32) -> Self {
33        Self(boost.clamp(Self::MINIMUM, Self::MAXIMUM))
34    }
35}
36
37impl From<f32> for NegativeBoost {
38    fn from(boost: f32) -> Self {
39        Self::new(boost)
40    }
41}
42
43impl From<i32> for NegativeBoost {
44    fn from(boost: i32) -> Self {
45        Self::new(boost as f32)
46    }
47}
48
49impl PartialEq<f32> for NegativeBoost {
50    fn eq(&self, other: &f32) -> bool {
51        self.0.eq(other)
52    }
53}
54
55#[cfg(test)]
56mod tests {
57    use super::*;
58
59    #[test]
60    fn out_of_bounds_integers() {
61        let min: NegativeBoost = (-1).into();
62        let max: NegativeBoost = 101.into();
63
64        assert_eq!(min, NegativeBoost::new(0f32));
65        assert_eq!(max, NegativeBoost::new(1f32));
66    }
67
68    #[test]
69    fn out_of_bounds_floats() {
70        let min: NegativeBoost = (-1.0).into();
71        let max: NegativeBoost = 101.0.into();
72
73        assert_eq!(min, NegativeBoost::new(0f32));
74        assert_eq!(max, NegativeBoost::new(1f32));
75    }
76
77    #[test]
78    fn within_bounds_floats() {
79        let min: NegativeBoost = 0.01.into();
80        let max: NegativeBoost = 0.99.into();
81
82        assert_eq!(min, NegativeBoost::new(0.01));
83        assert_eq!(max, NegativeBoost::new(0.99));
84    }
85}