概述
实体类中的属性映射可以通过多种方式进行忽略:
在继承自
ElasticsearchPropertyAttributeBase
类型的属性上使用Ignore
参数,比如TextAttribute
特性在
PropertyNameAttribute
特性上设置Ignore
参数在
ConnectionSettings
连接配置中设置.DefaultMappingFor<TDocument>(Func<ClrTypeMappingDescriptor<TDocument>, IClrTypeMapping<TDocument>> selector)
以下示例演示了几种忽略属性映射的方式:
[ElasticsearchType(RelationName = "company")]
public class CompanyWithAttributesAndPropertiesToIgnore
{
public string Name { get; set; }
[Text(Ignore = true)]
public string PropertyToIgnore { get; set; }
[PropertyName("anotherPropertyToIgnore", Ignore = true)]
public string AnotherPropertyToIgnore { get; set; }
public string FluentMappingPropertyToIgnore { get; set; }
[Ignore, JsonIgnore]
public string JsonIgnoredProperty { get; set; }
}
以下示例演示映射中除了Name
之外的所有属性都被忽略:
var connectionSettings = new ConnectionSettings(new InMemoryConnection())
.DisableDirectStreaming()
.DefaultMappingFor<CompanyWithAttributesAndPropertiesToIgnore>(m => m
.Ignore(p => p.FluentMappingPropertyToIgnore)
);
var client = new ElasticClient(connectionSettings);
var createIndexResponse = client.Indices.Create("myindex", c => c
.Map<CompanyWithAttributesAndPropertiesToIgnore>(m => m
.AutoMap()
)
);
输出的JSON结果中不包含被忽略的属性:
{
"mappings": {
"properties": {
"name": {
"type": "text",
"fields": {
"keyword": {
"type": "keyword",
"ignore_above": 256
}
}
}
}
}
}
忽略继承的属性
在ConnectionSettings
的DefaultMappingFor<T>
中配置的忽略属性,对来自继承的属性也生效,如下:
public class Parent
{
public int Id { get; set; }
public string Description { get; set; }
public string IgnoreMe { get; set; }
}
public class Child : Parent { }
var connectionSettings = new ConnectionSettings(new InMemoryConnection())
.DisableDirectStreaming()
.DefaultMappingFor<Child>(m => m
.PropertyName(p => p.Description, "desc")
.Ignore(p => p.IgnoreMe)
);
var client = new ElasticClient(connectionSettings);
var createIndexResponse = client.Indices.Create("myindex", c => c
.Map<Child>(m => m
.AutoMap()
)
);
由于在DefaultMappingFor<Child>
中配置了.Ignore(p => p.IgnoreMe)
,所以父类中的IgnoreMe
属性在子类中也被忽略了,得到的JSON结果为:
{
"mappings": {
"properties": {
"id": {
"type": "integer"
},
"desc": {
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
},
"type": "text"
}
}
}
}
重写继承属性的映射
ConnectionSettings
连接配置中的DefaultMappingFor<T>()
方法还可以重写继承属性的映射关系,在接下来的示例中,Id
属性被ParentWithStringId
重写成了string
类型,结果导致NEST
将其推断为text
并默认设置了多字段属性类型映射:
public class ParentWithStringId : Parent
{
public new string Id { get; set; }
}
var connectionSettings = new ConnectionSettings(new InMemoryConnection())
.DisableDirectStreaming()
.DefaultMappingFor<ParentWithStringId>(m => m
.Ignore(p => p.Description)
.Ignore(p => p.IgnoreMe)
);
var client = new ElasticClient(connectionSettings);
var createIndexResponse = client.Indices.Create("myindex", c => c
.Map<ParentWithStringId>(m => m
.AutoMap()
)
);
得到的JSON映射结果为:
{
"mappings": {
"properties": {
"id": {
"type": "text",
"fields": {
"keyword": {
"ignore_above": 256,
"type": "keyword"
}
}
}
}
}
}
发表评论
登录用户才能发表评论, 请 登 录 或者 注册