【发布时间】:2016-09-21 08:04:57
【问题描述】:
我只是想知道是否有人知道如何为弹性搜索日期字段提供空值。
您可以在下面的屏幕截图中看到,可以将 DateTime 用于 null 值,但是当我尝试时它不接受它。产生错误信息:
“'NullValue' 不是有效的命名属性参数,因为它不是有效的属性参数类型。”
【问题讨论】:
标签: c# .net class elasticsearch nest
我只是想知道是否有人知道如何为弹性搜索日期字段提供空值。
您可以在下面的屏幕截图中看到,可以将 DateTime 用于 null 值,但是当我尝试时它不接受它。产生错误信息:
“'NullValue' 不是有效的命名属性参数,因为它不是有效的属性参数类型。”
【问题讨论】:
标签: c# .net class elasticsearch nest
因为NullValue for DateAttribute 是DateTime,所以不能在应用于 POCO 属性的属性上设置它,因为设置值需要是编译时间常数。这是使用属性方法进行映射的限制之一。
NullValue 可以通过多种方式设置:
使用流畅的 API
fluent 映射可以做属性映射可以做的所有事情,以及处理空值、multi_fields 等功能。
public class MyDocument
{
public DateTime DateOfBirth { get; set; }
}
var fluentMappingResponse = client.Map<MyDocument>(m => m
.Index("index-name")
.AutoMap()
.Properties(p => p
.Date(d => d
.Name(n => n.DateOfBirth)
.NullValue(new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc))
)
)
);
使用访问者模式
定义一个访问者,它将访问 POCO 中的所有属性,并使用它来设置一个空值。访问者模式对于将约定应用于您的映射很有用,例如,所有字符串属性都应该是一个带有未分析的原始子字段的 multi_field。
public class MyPropertyVisitor : NoopPropertyVisitor
{
public override void Visit(IDateProperty type, PropertyInfo propertyInfo, ElasticsearchPropertyAttributeBase attribute)
{
if (propertyInfo.DeclaringType == typeof(MyDocument) &&
propertyInfo.Name == nameof(MyDocument.DateOfBirth))
{
type.NullValue = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
}
}
}
var visitorMappingResponse = client.Map<MyDocument>(m => m
.Index("index-name")
.AutoMap(new MyPropertyVisitor())
);
fluent 映射和访问者都产生以下请求
{
"properties": {
"dateOfBirth": {
"null_value": "1970-01-01T00:00:00Z",
"type": "date"
}
}
}
Take a look at the automapping documentation for more information.
【讨论】:
只需使用以下代码,而不是在类日期属性上声明它:
.Properties(pr => pr
.Date(dt => dt
.Name(n => n.dateOfBirth)
.NullValue(new DateTime(0001, 01, 01))))
【讨论】: