datetimeelasticsearchnestelasticsearch-net

NEST is adding TimeZone while indexing docs in Elasticsearch


I have a DateTime field in my c# class as below

 public DateTime PassedCreatedDate { get; set; }

While indexing it from NEST to elasticssearch, it is saving it along with local timezone. How to avoid this?

 "PassedCreatedDate": "2015-08-14T15:50:04.0479046+05:30" //Actual value saved in ES
 "PassedCreatedDate": "2015-08-14T15:50:04.047" //Expected value

mapping of PassedCreatedDate in elasticsearch is

  "PassedCreatedDate": {
                  "type": "date",
                  "format": "dateOptionalTime"
               },

I am aware to have a field as string and provide the format in ElasticProperty, but is there any setting to avoid this timezone addition while using datetime field only?


Solution

  • There are two things to change to achieve saving DateTimes without the time zone offset.

    Firstly, NEST uses JSON.Net for json serialization, so we need to change the serializer settings on the ElasticClient to serialize DateTimes into the format desired, and interpret those DateTimes as Local kind when deserializing

    var settings = new ConnectionSettings(new Uri("http://localhost:9200"));
    
    settings.SetJsonSerializerSettingsModifier(jsonSettings => 
    {
        jsonSettings.DateFormatString = "yyyy-MM-ddTHH:mm:ss",
        jsonSettings.DateTimeZoneHandling = DateTimeZoneHandling.Local
    });
    
    var connection = new InMemoryConnection(settings);
    var client = new ElasticClient(connection: connection);
    

    Secondly,we need to tell Elasticsearch via mapping, the format of our DateTime for the field(s) in question

    "PassedCreatedDate": {
        "type": "date",
        "format": "yyyy-MM-ddTHH:mm:ss"
    },