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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
use std::sync::{Mutex, RwLock};
use std::borrow::Cow;
use std::marker::PhantomData;
use serde::ser::{Serialize, SerializeStruct};
use serde_json::{self, Value};
use super::mapping::{DocumentMapping, PropertiesMapping};
use private::field::FieldMapping;

/**
The additional fields available to an indexable Elasticsearch type.

This trait is implemented for the type being mapped, rather than the mapping
type itself.
*/
pub trait DocumentType {
    /** The mapping type for this document. */
    type Mapping: DocumentMapping;

    /**
    Get the name for this type.
    
    This is a convenience method that returns the `name` of the bound `DocumentMapping`.
    */
    fn name() -> &'static str {
        Self::Mapping::name()
    }
}

/**
The base representation of an Elasticsearch data type.

`FieldType` is the main `trait` you need to care about when building your own Elasticsearch types.
Each type has two generic arguments that help define its mapping:

- A mapping type, which implements `FieldMapping`
- A format type, which is usually `()`. Types with multiple formats, like `Date`, can use the format in the type definition.

# Links

- [Elasticsearch docs](https://www.elastic.co/guide/en/elasticsearch/reference/current/mapping-types.html)
*/
pub trait FieldType<M, F>
    where M: FieldMapping<F>,
          F: Default
{
    /**
    Get the mapping for this type.
    */
    fn mapping() -> M {
        M::default()
    }
}

/**
A wrapper type for serialising user types.

Serialising `Document` will produce the mapping for the given type,
suitable as the mapping for
[Put Mapping](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-put-mapping.html)
or [Create Index](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices-create-index.html).

# Examples

To serialise a document mapping, you can use its mapping type as a generic parameter in `IndexDocumentMapping<M>`.
For example, we can define an index type for the Create Index API that includes the mapping for `MyType`:

```
# #[macro_use]
# extern crate json_str;
# #[macro_use]
# extern crate serde_derive;
# #[macro_use]
# extern crate elastic_types_derive;
# #[macro_use]
# extern crate elastic_types;
# extern crate serde;
# use elastic_types::prelude::*;
#[derive(Serialize, ElasticType)]
pub struct MyType {
    pub my_date: Date<DefaultDateFormat>,
    pub my_string: String,
    pub my_num: i32
}

#[derive(Default, Serialize)]
pub struct MyIndex {
    pub mappings: Mappings
}

#[derive(Default, Serialize)]
pub struct Mappings {
    pub mytype: IndexDocumentMapping<MyTypeMapping>
}
# fn main() {
# }
```

Serialising `MyIndex` will produce the following json:

```
# #[macro_use]
# extern crate json_str;
# #[macro_use]
# extern crate serde_derive;
# #[macro_use]
# extern crate elastic_types_derive;
# #[macro_use]
# extern crate elastic_types;
# extern crate serde;
# extern crate serde_json;
# use elastic_types::prelude::*;
# #[derive(Serialize, ElasticType)]
# pub struct MyType {
#     pub my_date: Date<DefaultDateFormat>,
#     pub my_string: String,
#     pub my_num: i32
# }
# #[derive(Default, Serialize)]
# pub struct MyIndex {
#     pub mappings: Mappings
# }
# #[derive(Default, Serialize)]
# pub struct Mappings {
#     pub mytype: IndexDocumentMapping<MyTypeMapping>
# }
# fn main() {
# let index = serde_json::to_string(&MyIndex::default()).unwrap();
# let json = json_str!(
{
    "mappings": {
        "mytype": {
            "properties": {
                "my_date": {
                    "type": "date",
                    "format": "basic_date_time"
                },
                "my_string": {
                    "type": "text",
                    "fields": {
                        "keyword":{
                            "type":"keyword",
                            "ignore_above":256
                        }
                    }
                },
                "my_num": {
                    "type": "integer"
                }
            }
        }
    }
}
# );
# assert_eq!(json, index);
# }
```

Alternatively, you can implement serialisation manually for `MyIndex` and avoid having
to keep field names up to date if the document type name changes:

```
# #[macro_use]
# extern crate json_str;
# #[macro_use]
# extern crate serde_derive;
# #[macro_use]
# extern crate elastic_types_derive;
# #[macro_use]
# extern crate elastic_types;
# extern crate serde;
# extern crate serde_json;
# use serde::{Serialize, Serializer};
# use serde::ser::SerializeStruct;
# use elastic_types::prelude::*;
#[derive(Serialize, ElasticType)]
# pub struct MyType {
#     pub my_date: Date<DefaultDateFormat>,
#     pub my_string: String,
#     pub my_num: i32
# }
#[derive(Default, Serialize)]
pub struct MyIndex {
    mappings: Mappings
}

#[derive(Default)]
struct Mappings;
impl Serialize for Mappings {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let mut state = try!(serializer.serialize_struct("mappings", 1));

        try!(state.serialize_field(MyType::name(), &IndexDocumentMapping::from(MyType::mapping())));

        state.end()
    }
}
# fn main() {
# let index = serde_json::to_string(&MyIndex::default()).unwrap();
# let json = json_str!(
# {
#     "mappings": {
#         "mytype": {
#             "properties": {
#                 "my_date": {
#                     "type": "date",
#                     "format": "basic_date_time"
#                 },
#                 "my_string": {
#                     "type": "text",
#                     "fields": {
#                         "keyword":{
#                             "type":"keyword",
#                             "ignore_above":256
#                         }
#                     }
#                 },
#                 "my_num": {
#                     "type": "integer"
#                 }
#             }
#         }
#     }
# }
# );
# assert_eq!(json, index);
# }
```
*/
#[derive(Default)]
pub struct IndexDocumentMapping<M>
    where M: DocumentMapping
{
    _m: PhantomData<M>,
}

impl<M> From<M> for IndexDocumentMapping<M>
    where M: DocumentMapping
{
    fn from(_: M) -> Self {
        IndexDocumentMapping::<M>::default()
    }
}

/** Serialise a field mapping as a field using the given serialiser. */
#[inline]
pub fn field_ser<S, M, F>(state: &mut S, field: &'static str, _: M) -> Result<(), S::Error>
    where S: SerializeStruct,
          M: FieldMapping<F>,
          F: Default
{
    state.serialize_field(field, &M::Field::default())
}

/** Serialise a document mapping as a field using the given serialiser. */
#[inline]
pub fn doc_ser<S, M>(state: &mut S, field: &'static str, _: M) -> Result<(), S::Error>
    where S: SerializeStruct,
          M: DocumentMapping
{
    state.serialize_field(field, &IndexDocumentMapping::<M>::default())
}

/**
Serialize a field individually.

This method isn't intended to be used publicly, but is useful in the docs.
*/
#[doc(hidden)]
#[inline]
pub fn standalone_field_ser<M, F>(_: M) -> Result<String, serde_json::Error>
    where M: FieldMapping<F>,
          F: Default
{
    serde_json::to_string(&M::Field::default())
}

/** Mapping for an anonymous json object. */
#[derive(Default)]
pub struct ValueDocumentMapping;

impl DocumentMapping for ValueDocumentMapping {
    fn name() -> &'static str {
        "value"
    }
}

impl DocumentType for Value {
    type Mapping = ValueDocumentMapping;
}

impl PropertiesMapping for ValueDocumentMapping {
    fn props_len() -> usize {
        0
    }

    fn serialize_props<S>(_: &mut S) -> Result<(), S::Error>
        where S: SerializeStruct
    {
        Ok(())
    }
}

impl<'a, TDocument, TMapping> DocumentType for &'a TDocument
    where TDocument: DocumentType<Mapping = TMapping> + Serialize,
          TMapping: DocumentMapping
{
    type Mapping = TMapping;
}

impl<TDocument, TMapping> DocumentType for Mutex<TDocument>
    where TDocument: DocumentType<Mapping = TMapping> + Serialize,
          TMapping: DocumentMapping
{
    type Mapping = TMapping;
}

impl<TDocument, TMapping> DocumentType for RwLock<TDocument>
    where TDocument: DocumentType<Mapping = TMapping> + Serialize,
          TMapping: DocumentMapping
{
    type Mapping = TMapping;
}

impl<'a, TDocument, TMapping> DocumentType for Cow<'a, TDocument>
    where TDocument: DocumentType<Mapping = TMapping> + Serialize + Clone,
          TMapping: DocumentMapping
{
    type Mapping = TMapping;
}

#[cfg(test)]
mod tests {
    use std::sync::{Mutex, RwLock};
    use std::borrow::Cow;
    use serde_json::{self, Value};
    use prelude::*;

    // Make sure we can derive with no `uses`.
    pub mod no_prelude {
        #![allow(dead_code)]

        #[derive(Serialize, ElasticType)]
        pub struct TypeWithNoPath {
            id: i32,
        }

        #[derive(Default, ElasticDateFormat)]
        #[elastic(date_format="yyyy")]
        pub struct DateFormatWithNoPath;
    }

    // Make sure we can derive in a function scope
    #[allow(dead_code)]
    fn fn_scope() {
        #[derive(Serialize, ElasticType)]
        pub struct TypeInFn {
            id: i32,
        }

        #[derive(Default, ElasticDateFormat)]
        #[elastic(date_format="yyyy")]
        pub struct DateFormatInFn;
    }

    #[derive(Clone, Serialize, ElasticType)]
    pub struct SimpleType {
        pub field1: Date<EpochMillis>,
        pub field2: SimpleNestedType,
    }

    #[derive(Clone, Serialize, ElasticType)]
    pub struct SimpleNestedType {
        pub field: i32,
    }

    #[derive(Serialize, ElasticType)]
    #[elastic(mapping="ManualCustomTypeMapping")]
    pub struct CustomType {
        pub field: i32,
        #[serde(skip_serializing)]
        pub ignored_field: i32,
        #[serde(rename="renamed_field")]
        pub field2: i32,
    }

    #[derive(PartialEq, Debug, Default)]
    pub struct ManualCustomTypeMapping;
    impl DocumentMapping for ManualCustomTypeMapping {
        fn name() -> &'static str {
            "renamed_type"
        }
    }

    #[derive(Serialize, ElasticType)]
    pub struct Wrapped {
        pub field1: Vec<i32>,
        pub field2: Option<bool>,
        pub field3: &'static str,
        pub field4: Value,
        pub field5: Option<SimpleNestedType>,
    }

    #[derive(Serialize, ElasticType)]
    pub struct NoProps {}

    #[derive(Default, Serialize)]
    pub struct Index {
        mappings: Mappings,
    }

    #[derive(Default, Serialize)]
    pub struct Mappings {
        simpletype: IndexDocumentMapping<SimpleTypeMapping>,
    }

    #[test]
    fn use_doc_as_generic_without_supplying_mapping_param() {
        fn use_document<TDocument>()
            where TDocument: DocumentType
        {
            assert!(true);
        }

        use_document::<SimpleType>();
    }

    #[test]
    fn get_type_name() {
        assert_eq!("simpletype", SimpleTypeMapping::name());
    }

    #[test]
    fn get_default_type_name() {
        assert_eq!("simpletype", SimpleType::name());
    }

    #[test]
    fn get_custom_type_name() {
        assert_eq!("renamed_type", CustomType::name());
    }

    #[test]
    fn get_value_type_name() {
        assert_eq!("value", Value::name());
    }

    #[test]
    fn derive_custom_type_mapping() {
        assert_eq!(ManualCustomTypeMapping, CustomType::mapping());
    }

    #[test]
    fn serialise_document() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(SimpleType::mapping())).unwrap();

        let expected = json_str!({
            "properties":{
                "field1": {
                    "type": "date",
                    "format": "epoch_millis"
                },
                "field2": {
                    "type": "nested",
                    "properties": {
                        "field": {
                            "type": "integer"
                        }
                    }
                }
            }
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_borrowed() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(<&'static SimpleType>::mapping())).unwrap();

        let expected = serde_json::to_string(&IndexDocumentMapping::from(SimpleType::mapping())).unwrap();

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_mutex() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(Mutex::<SimpleType>::mapping())).unwrap();

        let expected = serde_json::to_string(&IndexDocumentMapping::from(SimpleType::mapping())).unwrap();

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_rwlock() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(RwLock::<SimpleType>::mapping())).unwrap();

        let expected = serde_json::to_string(&IndexDocumentMapping::from(SimpleType::mapping())).unwrap();

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_cow() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(Cow::<'static, SimpleType>::mapping())).unwrap();

        let expected = serde_json::to_string(&IndexDocumentMapping::from(SimpleType::mapping())).unwrap();

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_with_no_props() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(NoProps::mapping())).unwrap();

        let expected = json_str!({
            "properties": {

            }
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_for_custom_mapping() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(CustomType::mapping())).unwrap();

        let expected = json_str!({
            "properties": {
                "field": {
                    "type": "integer"
                },
                "renamed_field": {
                    "type": "integer"
                }
            }
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_document_for_value() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(Value::mapping())).unwrap();

        let expected = json_str!({
            "properties": {}
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_mapping_with_wrapped_types() {
        let ser = serde_json::to_string(&IndexDocumentMapping::from(Wrapped::mapping())).unwrap();

        let expected = json_str!({
            "properties": {
                "field1": {
                    "type": "integer"
                },
                "field2": {
                    "type": "boolean"
                },
                "field3": {
                    "type": "text",
                    "fields": {
                        "keyword":{
                            "type": "keyword",
                            "ignore_above": 256
                        }
                    }
                },
                "field4": {
                    "type": "nested"
                },
                "field5": {
                    "type": "nested",
                    "properties": {
                        "field": {
                            "type": "integer"
                        }
                    }
                }
            }
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_index_mapping() {
        let ser = serde_json::to_string(&Index::default()).unwrap();

        let expected = json_str!({
            "mappings": {
                "simpletype": {
                    "properties": {
                        "field1": {
                            "type": "date",
                            "format": "epoch_millis"
                        },
                        "field2": {
                            "type": "nested",
                            "properties": {
                                "field": {
                                    "type": "integer"
                                }
                            }
                        }
                    }
                }
            }
        });

        assert_eq!(expected, ser);
    }

    #[test]
    fn serialise_mapping_dynamic() {
        let d_opts: Vec<String> = vec![
            Dynamic::True,
            Dynamic::False,
            Dynamic::Strict
        ]
                .iter()
                .map(|i| serde_json::to_string(i).unwrap())
                .collect();

        let expected_opts = vec![
            r#"true"#,
            r#"false"#,
            r#""strict""#
        ];

        let mut success = true;
        for i in 0..d_opts.len() {
            if expected_opts[i] != d_opts[i] {
                success = false;
                break;
            }
        }

        assert!(success);
    }
}