首页 / 教程列表 / Elasticsearch.NET/NEST中文文档(教程) / 特性映射(Attribute mapping)

特性映射(Attribute mapping)

985 更新于: 2021-04-07 读完约需 2 分钟

概述

自动映射(Auto mapping)小节中,我们已经学习了如何使用.AutoMap()方法来处理NEST的数据类型与Elasticsearch数据类型之间的映射。但是,当你想以不同的方式映射到推断映射时,又应该怎么做呢?这时,特性映射可能会派上用场。

你可以使用特性来定义实体属性的映射类型,在实体上定义好映射特性之后,再调用 .AutoMap()方法,NEST将使用属性的特性来推断实体在Elasticsearch上对应的数据类型。

注:当使用特性映射时,必须调用.AutoMap()方法来让特性映射生效。

以下定义了一个Employee实体类,并使用特性映射定义了映射关系:

[ElasticsearchType(RelationName = "employee")]
public class Employee
{
    [Text(Name = "first_name", Norms = false, Similarity = "LMDirichlet")]
    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())
);

映射后得到的Elasticsearch映射关系为:

{
  "mappings": {
    "properties": {
      "birthday": {
        "format": "MMddyyyy",
        "type": "date"
      },
      "empl": {
        "properties": {},
        "type": "nested"
      },
      "first_name": {
        "type": "text",
        "norms": false,
        "similarity": "LMDirichlet"
      },
      "isManager": {
        "null_value": false,
        "store": true,
        "type": "boolean"
      },
      "last_name": {
        "type": "text"
      },
      "office_hours": {
        "type": "text"
      },
      "salary": {
        "coerce": true,
        "doc_values": false,
        "ignore_malformed": true,
        "type": "float"
      },
      "skills": {
        "properties": {
          "level": {
            "type": "byte"
          },
          "name": {
            "type": "text"
          }
        },
        "type": "object"
      }
    }
  }
}

特性映射是一种方便的方法,可以用最少的代码来控制实体的映射关系,但是有些映射特性不能用属性表示,例如,多字段。为了在NEST中使用映射的全部功能,下面来看一下链式映射(Fluent mapping)。

版权声明:本作品系原创,版权归码友网所有,如未经许可,禁止任何形式转载,违者必究。

发表评论

登录用户才能发表评论, 请 登 录 或者 注册