为elasticsearch日期字段

时间:2016-09-21 08:04:57

标签: c# .net class elasticsearch nest

我只是想知道是否有人知道如何为elasticsearch日期字段提供空值。

您可以在下面的屏幕截图中看到可以使用DateTime作为空值,但是当我尝试它时不接受它。生成错误消息:

“'NullValue'不是有效的命名属性参数,因为它不是有效的属性参数类型。”

Date field options

2 个答案:

答案 0 :(得分:1)

因为NullValue的{​​{1}}是DateAttribute,所以无法在应用于POCO属性的属性上设置它,因为设置值需要是编译时常量。这是使用属性方法进行映射的限制之一。

DateTime可以通过以下几种方式设置:

使用流畅的API

Fluent映射可以完成属性映射可以执行的所有操作,以及处理null值,multi_fields等功能。

NullValue

使用访客模式

定义将访问POCO中所有属性的访问者,并使用它来设置空值。访问者模式对于将约定应用于映射非常有用,例如,所有字符串属性都应该是具有未分析的原始子字段的multi_field。

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))
        )
    )
);

流畅的映射和访问者都会产生以下请求

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())
);

Take a look at the automapping documentation for more information.

答案 1 :(得分:0)

使用以下代码而不是在类日期属性上声明它:

&#13;
&#13;
.Properties(pr => pr
  .Date(dt => dt
    .Name(n => n.dateOfBirth)
    .NullValue(new DateTime(0001, 01, 01))))
&#13;
&#13;
&#13;

相关问题