os_query_builder_rs/term/
terms_set.rs

1use serde::{Serialize, Serializer};
2use serde::ser::SerializeMap;
3use crate::misc::script::Script;
4
5#[derive(Debug, Default, Clone)]
6pub struct TermsSet {
7    field: Option<String>,
8    value: TermsSetValue
9}
10#[derive(Debug, Default, Clone, Serialize)]
11pub struct TermsSetValue {
12
13    terms: Vec<String>,
14    #[serde(skip_serializing_if = "Option::is_none")]
15    minimum_should_match_field: Option<String>,
16    #[serde(skip_serializing_if = "Option::is_none")]
17    minimum_should_match_script: Option<Script>,
18    #[serde(skip_serializing_if = "Option::is_none")]
19    boost: Option<f64>
20}
21
22impl TermsSet {
23
24    pub fn new() -> Self {
25        Self::default()
26    }
27
28    pub fn field<T:Into<String> + Serialize>(self, field: T) -> Self {
29        Self {
30            field: Some(field.into()),
31            ..self
32        }
33    }
34
35    pub fn minimum_should_match_field<T:Into<String> + Serialize>(self, minimum_should_match_field: T) -> Self {
36        Self {
37            value: TermsSetValue {
38                minimum_should_match_field: Some(minimum_should_match_field.into()),
39                minimum_should_match_script: None,
40                ..self.value
41            },
42            ..self
43        }
44    }
45
46    pub fn minimum_should_match_script<T:Into<Script> + Serialize>(self, minimum_should_match_script: T) -> Self {
47        Self {
48            value: TermsSetValue {
49                minimum_should_match_script: Some(minimum_should_match_script.into()),
50                minimum_should_match_field: None,
51                ..self.value
52            },
53            ..self
54        }
55    }
56
57    pub fn terms<T, F>(self, terms: F) -> Self
58        where T: Into<String> + Serialize,
59              F: IntoIterator<Item=T>
60    {
61        Self {
62            value: TermsSetValue {
63                terms: terms.into_iter().map(|x| x.into()).collect(),
64                ..self.value
65            },
66            ..self
67        }
68    }
69
70
71    pub fn boost<T:Into<f64> + Serialize>(self, boost: T) -> Self {
72        Self {
73            value: TermsSetValue {
74                boost: Some(boost.into()),
75                ..self.value
76            },
77            ..self
78        }
79    }
80
81
82}
83
84impl Serialize for TermsSet {
85    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
86        where
87            S: Serializer,
88    {
89        let mut state = serializer.serialize_map(Some(1))?;
90        state.serialize_entry(self.field.as_deref().unwrap_or_default(), &self.value)?;
91        state.end()
92    }
93}