1

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?

1
  • Why do you want to exclude the timezone offset? Commented Aug 24, 2015 at 22:21

2 Answers 2

3

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"
},
Sign up to request clarification or add additional context in comments.

1 Comment

SetJsonSerializerSettingsModifier doesn't exist in NEST 7.8.1 version :/
0

For NEST 6.X and onwards,things have changed a bit.

Now you need 2 steps to achieve serializer settings .

1.Import NEST.JsonNetSerializer ,with a version identified with your NEST version.

2.

 var settings = new ConnectionSettings(pool, sourceSerializer: (builtin, settings) => new JsonNetSerializer(builtin, settings, () => 
                    new JsonSerializerSettings
                    {
                        DateFormatString = "yyyy-MM-dd HH:mm:ss",
                        DateTimeZoneHandling = DateTimeZoneHandling.Local
                    })
                )

refering to nest doc here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.