c# - 为Elasticsearch日期字段提供空值

标签 c# .net class elasticsearch nest

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

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

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

Date field options

最佳答案

由于NullValueDateAttributeDateTime,因此无法在应用于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/

相关文章:

c# - 如何在控制台应用程序中使用 UnityResolver?

c# - CSharpCodeProvider 编译性能

c# - 从 Datetime.Today 中减去一个月

c# - 如何将 gtk# 依赖项与可执行文件打包

c# - WPF 中的嵌套样式

c# - 使用 C# Lambda 运算符

c# - WinRT 和持久化结构与字节数组?

class - RDF/OWL/Protege : let a subclass be a union of some disjoint super classes?

c++ - 指向类成员函数的指针

c++ - 用户定义类中的空指针无效?