Reputation: 107
I just wanted to know if anyone knows how to provide a null value for an elasticsearch date field.
You can see in the screenshot below that it is possible to utilise a DateTime for the null value but when I try it doesn't accept it. Producing the error message:
"'NullValue' is not a valid named attribute argument brecause it is not a valid attribute parameter type."
Upvotes: 0
Views: 4612
Reputation: 125488
Because NullValue
for DateAttribute
is a DateTime
, it can't be set on a attribute applied to a POCO property because the set value would need to be a compile time constant. This is one of the limitations of going with the attribute approach to mapping.
NullValue
can be set in a couple of ways:
Using the fluent API
The fluent mapping can do everything that attribute mapping can do, as well as handle functionality such as null values, multi_fields, etc.
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))
)
)
);
Using a visitor pattern
Define a visitor that will visit all the properties in the POCO, and use this to set a null value. The visitor pattern is useful for applying conventions to your mapping, for example, all string properties should be a multi_field with a not analyzed raw sub 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())
);
both the fluent mapping and visitor produce the following request
{
"properties": {
"dateOfBirth": {
"null_value": "1970-01-01T00:00:00Z",
"type": "date"
}
}
}
Take a look at the automapping documentation for more information.
Upvotes: 4
Reputation: 107
Just used the following code instead of declaring it on the class date attribute:
.Properties(pr => pr
.Date(dt => dt
.Name(n => n.dateOfBirth)
.NullValue(new DateTime(0001, 01, 01))))
Upvotes: 0