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
/*! Mapping for the Elasticsearch `date` type. */

use std::marker::PhantomData;
use serde::{Serialize, Serializer};
use serde::ser::SerializeStruct;
use super::{DateFormat, Date};
use private::field::{DocumentField, FieldMapping, SerializeField};
use document::FieldType;

/** A field that will be mapped as a `date`. */
pub trait DateFieldType<M, F>
    where M: DateMapping<Format = F>,
          F: DateFormat
{
}

impl<T, F, M> FieldType<M, DateFormatWrapper<F>> for T
    where F: DateFormat,
          M: DateMapping<Format = F>,
          T: DateFieldType<M, F> + Serialize
{
}

#[doc(hidden)]
#[derive(Default)]
pub struct DateFormatWrapper<F>
    where F: DateFormat
{
    _f: PhantomData<F>,
}

/**
The base requirements for mapping a `date` type.

# Examples

Define a custom `DateMapping`:

## Derive Mapping

Currently, deriving mapping only works for structs that take a generic `DateFormat` parameter.

```
# #[macro_use]
# extern crate elastic_types;
# extern crate serde;
# use std::marker::PhantomData;
# use elastic_types::prelude::*;
#[derive(Default)]
struct MyDateMapping;
impl DateMapping for MyDateMapping {
    type Format = EpochMillis;

    //Overload the mapping functions here
    fn boost() -> Option<f32> {
        Some(1.5)
    }
}
# fn main() {}
```

This will produce the following mapping when mapped with the `EpochMillis` format:

```
# #[macro_use]
# extern crate json_str;
# #[macro_use]
# extern crate elastic_types;
# extern crate serde;
# extern crate serde_json;
# use std::marker::PhantomData;
# use elastic_types::prelude::*;
# #[derive(Default)]
# struct MyDateMapping;
# impl DateMapping for MyDateMapping {
#     type Format = EpochMillis;
#     fn boost() -> Option<f32> {
#         Some(1.5)
#     }
# }
# fn main() {
# let mapping = standalone_field_ser(MyDateMapping).unwrap();
# let json = json_str!(
{
    "type": "date",
    "format": "epoch_millis",
    "boost": 1.5
}
# );
# assert_eq!(json, mapping);
# }
```

## Map with a generic Format

You can use a generic input parameter to make your `DateMapping` work for any kind of
`DateFormat`:

```
# #[macro_use]
# extern crate elastic_types;
# extern crate serde;
# use std::marker::PhantomData;
# use elastic_types::prelude::*;
#[derive(Default)]
struct MyDateMapping<F> {
    _marker: PhantomData<F>
}
impl <F: DateFormat> DateMapping for MyDateMapping<F> {
    type Format = F;
}
# fn main() {}
```
*/
pub trait DateMapping
    where Self: Default
{
    /**
    The date format bound to this mapping.

    The value of `Format::name()` is what's sent to Elasticsearch as the format to use.
    This is also used to serialise and deserialise formatted `Date`s.
    */
    type Format: DateFormat;

    /** Field-level index time boosting. Accepts a floating point number, defaults to `1.0`. */
    fn boost() -> Option<f32> {
        None
    }

    /**
    Should the field be stored on disk in a column-stride fashion,
    so that it can later be used for sorting, aggregations, or scripting?
    Accepts `true` (default) or `false`.
    */
    fn doc_values() -> Option<bool> {
        None
    }

    /**
    Whether or not the field value should be included in the `_all` field?
    Accepts true or false.
    Defaults to `false` if index is set to `no`, or if a parent object field sets `include_in_all` to false.
    Otherwise defaults to `true`.
    */
    fn include_in_all() -> Option<bool> {
        None
    }

    /** Should the field be searchable? Accepts `not_analyzed` (default) and `no`. */
    fn index() -> Option<bool> {
        None
    }

    /**
    Whether the field value should be stored and retrievable separately from the `_source` field.
    Accepts `true` or `false` (default).
    */
    fn store() -> Option<bool> {
        None
    }

    /**
    If `true`, malformed numbers are ignored.
    If `false` (default), malformed numbers throw an exception and reject the whole document.
    */
    fn ignore_malformed() -> Option<bool> {
        None
    }

    /**
    Accepts a date value in one of the configured format's as the field which is substituted for any explicit null values.
    Defaults to `null`, which means the field is treated as missing.
    */
    fn null_value() -> Option<Date<Self::Format, Self>> {
        None
    }
}

impl<T, F> FieldMapping<DateFormatWrapper<F>> for T
    where T: DateMapping<Format = F>,
          F: DateFormat
{
    fn data_type() -> &'static str {
        "date"
    }
}

impl<T, F> SerializeField<DateFormatWrapper<F>> for T
    where T: DateMapping<Format = F>,
          F: DateFormat
{
    type Field = DocumentField<T, DateFormatWrapper<F>>;
}

impl<T, F> Serialize for DocumentField<T, DateFormatWrapper<F>>
    where T: FieldMapping<DateFormatWrapper<F>> + DateMapping<Format = F>,
          F: DateFormat
{
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where S: Serializer
    {
        let mut state = try!(serializer.serialize_struct("mapping", 9));

        try!(state.serialize_field("type", T::data_type()));
        try!(state.serialize_field("format", T::Format::name()));

        ser_field!(state, "boost", T::boost());
        ser_field!(state, "doc_values", T::doc_values());
        ser_field!(state, "include_in_all", T::include_in_all());
        ser_field!(state, "index", T::index());
        ser_field!(state, "store", T::store());
        ser_field!(state, "ignore_malformed", T::ignore_malformed());
        ser_field!(state, "null_value", T::null_value());

        state.end()
    }
}

/** Default mapping for `date`. */
#[derive(PartialEq, Debug, Default, Clone, Copy)]
pub struct DefaultDateMapping<F>
    where F: DateFormat
{
    _f: PhantomData<F>,
}

impl<F> DateMapping for DefaultDateMapping<F>
    where F: DateFormat
{
    type Format = F;
}

#[cfg(test)]
mod tests {
    use serde_json;
    use chrono::{DateTime, Utc};

    use prelude::*;
    use private::field::DocumentField;

    #[derive(Default, Clone)]
    pub struct MyDateMapping;
    impl DateMapping for MyDateMapping {
        type Format = EpochMillis;

        fn null_value() -> Option<Date<Self::Format, Self>> {
            Some(Date::build(2015, 3, 14, 16, 45, 13, 778))
        }

        fn boost() -> Option<f32> {
            Some(1.01)
        }

        fn index() -> Option<bool> {
            Some(true)
        }

        fn doc_values() -> Option<bool> {
            Some(true)
        }

        fn include_in_all() -> Option<bool> {
            Some(false)
        }

        fn store() -> Option<bool> {
            Some(true)
        }

        fn ignore_malformed() -> Option<bool> {
            Some(true)
        }
    }

    #[test]
    fn datetime_has_default_mapping() {
        assert_eq!(DefaultDateMapping::<ChronoFormat>::default(), DateTime::<Utc>::mapping());
    }

    #[test]
    fn serialise_mapping_default() {
        let ser = serde_json::to_string(&DocumentField::from(DefaultDateMapping::<DefaultDateFormat>::default())).unwrap();

        let expected = json_str!({
            "type": "date",
            "format": "basic_date_time"
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_mapping_custom() {
        let ser = serde_json::to_string(&DocumentField::from(MyDateMapping)).unwrap();

        let expected = json_str!({
            "type": "date",
            "format": "epoch_millis",
            "boost": 1.01,
            "doc_values": true,
            "include_in_all": false,
            "index": true,
            "store": true,
            "ignore_malformed": true,
            "null_value": "1426351513778"
        });

        assert_eq!(expected, ser);
    }

}