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
//! You can specify a `runtime_mappings` section in a search request to create
//! runtime fields that exist only as part of the query. You specify a script
//! as part of the `runtime_mappings` section, just as you would if
//! [adding a runtime field to the mappings](https://www.elastic.co/guide/en/elasticsearch/reference/master/runtime-mapping-fields.html).
//!
//! Defining a runtime field in a search request uses the same format as
//! defining a runtime field in the index mapping. Just copy the field
//! definition from the `runtime_mappings` in the search request to the
//! `runtime` section of the index mapping.
//!
//! <https://www.elastic.co/guide/en/elasticsearch/reference/master/runtime-search-request.html>

use serde::ser::{Serialize, SerializeStruct, Serializer};

/// A runtime data type that is used in a search request.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd)]
pub enum RuntimeDataType {
    /// Boolean
    Boolean,

    /// Composite
    Composite,

    /// Date with optional `format`
    Date(Option<String>),

    /// Double
    Double,

    /// Geo point
    GeoPoint,

    /// IP address
    Ip,

    /// Keyword
    Keyword,

    /// Long
    Long,
}

impl Serialize for RuntimeDataType {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Boolean => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "boolean")?;
                state.end()
            }
            Self::Composite => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "composite")?;
                state.end()
            }
            Self::Date(format) => match format {
                Some(format) => {
                    let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 2)?;
                    state.serialize_field("type", "date")?;
                    state.serialize_field("format", format)?;
                    state.end()
                }
                None => {
                    let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                    state.serialize_field("type", "date")?;
                    state.end()
                }
            },
            Self::Double => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "double")?;
                state.end()
            }
            Self::GeoPoint => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "geo_point")?;
                state.end()
            }
            Self::Ip => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "ip")?;
                state.end()
            }
            Self::Keyword => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "keyword")?;
                state.end()
            }
            Self::Long => {
                let mut state = serializer.serialize_struct("RuntimeDataType_Boolean", 1)?;
                state.serialize_field("type", "long")?;
                state.end()
            }
        }
    }
}

/// A runtime field that is used in a search request.
#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
pub struct RuntimeMapping {
    #[serde(flatten)]
    r#type: RuntimeDataType,
    script: RuntimeScript,
}

#[derive(Debug, Clone, PartialEq, PartialOrd, Serialize)]
struct RuntimeScript {
    source: String,
}

impl RuntimeMapping {
    /// Creates a new instance of [RuntimeMapping]
    pub fn new<T>(r#type: RuntimeDataType, source: T) -> Self
    where
        T: ToString,
    {
        RuntimeMapping {
            r#type,
            script: RuntimeScript {
                source: source.to_string(),
            },
        }
    }

    /// Creates a new instance of [RuntimeDataType::Boolean] [RuntimeMapping]
    pub fn boolean<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Boolean, source)
    }

    /// Creates a new instance of [RuntimeDataType::Composite] [RuntimeMapping]
    pub fn composite<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Composite, source)
    }

    /// Creates a new instance of [RuntimeDataType::Date] [RuntimeMapping] without format
    pub fn date<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Date(None), source)
    }

    /// Creates a new instance of [RuntimeDataType::Date] [RuntimeMapping] with format
    pub fn date_format<F, T>(format: F, source: T) -> Self
    where
        F: ToString,
        T: ToString,
    {
        Self::new(RuntimeDataType::Date(Some(format.to_string())), source)
    }

    /// Creates a new instance of [RuntimeDataType::Double] [RuntimeMapping]
    pub fn double<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Double, source)
    }

    /// Creates a new instance of [RuntimeDataType::GeoPoint] [RuntimeMapping]
    pub fn geo_point<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::GeoPoint, source)
    }

    /// Creates a new instance of [RuntimeDataType::Ip] [RuntimeMapping]
    pub fn ip<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Ip, source)
    }

    /// Creates a new instance of [RuntimeDataType::Keyword] [RuntimeMapping]
    pub fn keyword<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Keyword, source)
    }

    /// Creates a new instance of [RuntimeDataType::Long] [RuntimeMapping]
    pub fn long<T>(source: T) -> Self
    where
        T: ToString,
    {
        Self::new(RuntimeDataType::Long, source)
    }
}

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

    #[test]
    fn serialization() {
        assert_serialize(
            RuntimeMapping::boolean("doc['field'].value"),
            json!({
                "type": "boolean",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::composite("doc['field'].value"),
            json!({
                "type": "composite",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::date("doc['field'].value"),
            json!({
                "type": "date",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::date_format("YYYY-mm-dd", "doc['field'].value"),
            json!({
                "type": "date",
                "format": "YYYY-mm-dd",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::double("doc['field'].value"),
            json!({
                "type": "double",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::geo_point("doc['field'].value"),
            json!({
                "type": "geo_point",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::ip("doc['field'].value"),
            json!({
                "type": "ip",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::keyword("doc['field'].value"),
            json!({
                "type": "keyword",
                "script": { "source": "doc['field'].value" }
            }),
        );

        assert_serialize(
            RuntimeMapping::long("doc['field'].value"),
            json!({
                "type": "long",
                "script": { "source": "doc['field'].value" }
            }),
        );
    }
}