为elasticsearch日期字段提供空值
问题描述:
我只想知道是否有人知道如何为elasticsearch日期字段提供空值。为elasticsearch日期字段提供空值
您可以在下面的屏幕截图中看到可以利用DateTime作为空值,但是当我尝试它时不接受它。生成错误消息:
“'NullValue'不是有效的命名属性参数,因为它不是有效的属性参数类型。”
答
因为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中所有属性的访问者,并使用它来设置空值。访问者模式对于将约定应用于您的映射非常有用,例如,所有字符串属性都应该是具有未分析的原始子字段的多字段。
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())
);
流畅的地图和游客都产生下面的请求
{
"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))))
这是一个伟大的答案谢谢!我开始认为这可能是因为我使用的方法,所以这就是为什么我继续使用流利的API设置空值。猜想记住这一点以备将来参考是有用的。 谢谢你的帮助 – GSkidmore
@GSkidmore - 不用担心,高兴地帮助:) –