2016-09-21 97 views
0

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

您可以在下面的屏幕截圖中看到可以利用DateTime作爲空值,但是當我嘗試它時不接受它。生成錯誤消息:

「'NullValue'不是有效的命名屬性參數,因爲它不是有效的屬性參數類型。」

Date field options

回答

1

因爲NullValueDateAttribute是一個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.

+0

這是一個偉大的答案謝謝!我開始認爲這可能是因爲我使用的方法,所以這就是爲什麼我繼續使用流利的API設置空值。猜想記住這一點以備將來參考是有用的。 謝謝你的幫助 – GSkidmore

+0

@GSkidmore - 不用擔心,高興地幫助:) –

0

只是用來代替聲明它的類日屬性下面的代碼:

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

相關問題