使用自动映射的时候,NEST 会将 POCO 模型属性的数据类型自动推断出对应的 ES 数据类型。同样,NEST 也提供了一系列特性,方便你进行一些定制。
唯一需要注意的是,虽然使用特性进行了映射,但依然需要调用 .AutoMap() 方法,以便在特性上自定义的值生效。
示例:
在 Employee 和 Skill 类上使用特性
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
| [ElasticsearchType(RelationName = "employee")] public class Employee { [Text(Name = "first_name", Norms = false)] public string FirstName { get; set; }
[Text(Name = "last_name")] public string LastName { get; set; }
[Number(DocValues = false, IgnoreMalformed = true, Coerce = true)] public int Salary { get; set; }
[Date(Format = "MMddyyyy")] public DateTime Birthday { get; set; }
[Boolean(NullValue = false, Store = true)] public bool IsManager { get; set; }
[Nested] [PropertyName("empl")] public List<Employee> Employees { get; set; }
[Text(Name = "office_hours")] public TimeSpan? OfficeHours { get; set; }
[Object] public List<Skill> Skills { get; set; } }
public class Skill { [Text] public string Name { get; set; }
[Number(NumberType.Byte, Name = "level")] public int Proficiency { get; set; } }
|
在创建索引的时候调用 .AutoMap
1 2 3
| var createIndexResponse = _client.Indices.Create("myindex", c => c .Map<Employee>(m => m.AutoMap()) );
|
效果如下:
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
| { "myindex" : { "mappings" : { "properties" : { "birthday" : { "type" : "date", "format" : "MMddyyyy" }, "empl" : { "type" : "nested" }, "first_name" : { "type" : "text", "norms" : false }, "isManager" : { "type" : "boolean", "store" : true, "null_value" : false }, "last_name" : { "type" : "text" }, "office_hours" : { "type" : "text" }, "salary" : { "type" : "float", "doc_values" : false, "ignore_malformed" : true, "coerce" : true }, "skills" : { "properties" : { "level" : { "type" : "byte" }, "name" : { "type" : "text" } } } } } } }
|