【问题标题】:Providing null value for elasticsearch date field为弹性搜索日期字段提供空值
【发布时间】:2016-09-21 08:04:57
【问题描述】:

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

您可以在下面的屏幕截图中看到,可以将 DateTime 用于 null 值,但是当我尝试时它不接受它。产生错误信息:

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

Date field options

【问题讨论】:

    标签: c# .net class elasticsearch nest


    【解决方案1】:

    因为NullValue for DateAttributeDateTime,所以不能在应用于 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.

    【讨论】:

    • 这是一个很好的答案,谢谢!我开始认为这可能是因为我使用的方法,所以这就是我继续使用 fluent API 设置空值的原因。猜猜记住这一点以备将来参考很有用。感谢您的帮助
    • @GSkidmore - 不用担心,很乐意提供帮助 :)
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多