Elasticsearch.Nest 教程系列 4-2 映射:Attribute mapping | 通过特性进行映射


使用自动映射的时候,NEST 会将 POCO 模型属性的数据类型自动推断出对应的 ES 数据类型。同样,NEST 也提供了一系列特性,方便你进行一些定制。

唯一需要注意的是,虽然使用特性进行了映射,但依然需要调用 .AutoMap() 方法,以便在特性上自定义的值生效。

示例:

在 Employee 和 Skill 类上使用特性

[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

var createIndexResponse = _client.Indices.Create("myindex", c => c
    .Map<Employee>(m => m.AutoMap())
);

效果如下:

{
  "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"
            }
          }
        }
      }
    }
  }
}