我只是想知道是否有人知道如何为elasticsearch date字段提供空值。
您可以在下面的屏幕截图中看到,可以将DateTime用作空值,但是当我尝试使用它时,它不接受它。产生错误消息:
““NullValue”不是有效的命名属性参数,因为它不是有效的属性参数类型。”
Date field options
最佳答案
由于NullValue
的DateAttribute
是DateTime
,因此无法在应用于POCO属性的属性上进行设置,因为设置值必须是编译时间常数。这是使用属性方法进行映射的限制之一。NullValue
可以通过以下两种方式设置:
使用流畅的API
流利的映射可以完成属性映射可以做的所有事情,还可以处理诸如空值,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())
);
流利的 map 绘制和访问者都会产生以下请求
{
"properties": {
"dateOfBirth": {
"null_value": "1970-01-01T00:00:00Z",
"type": "date"
}
}
}
Take a look at the automapping documentation for more information.
关于c# - 为Elasticsearch日期字段提供空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39610803/