Search code examples
elasticsearchnest

How to map array of dates to elastic search?


I have an array of dates and I want to create the mapping by Nest. But my current mapping searches do not work. Query sample is:

publicationDates: '1995-01-11'

My mapping:

[ElasticsearchType(Name = "doc-index", IdProperty = "Id")]
public class DocumentIndex
{
    [Keyword(Index = false)]
    public string Id { get; set; }
    [Text]
    public string Title { get; set; }
    [Date(Format = "yyyy-MM-dd")]
    public IEnumerable<DateTime> PublicationDates { get; set; }
}

Solution

  • The Format parameter tells Elasticsearch how to parse the incoming string into a date on the server side, but it doesn't affect the way that DateTime are serialized by the client, which serializes DateTime to ISO8601 format using Json.NET internal DateTime serialization handling.

    If you'd like to serialize DateTime for your POCO differently, the easiest way is to implement a JsonConverter and attribute the PublicationDates property to use this converter. This is all that is needed for NEST 5.x and previous.

    In NEST 6.x, the Json.NET dependency is internalized, so if you're using NEST 6.x, you need to also use the NEST.JsonNetSerializer package and hook up the serializer so that serialization of your types is delegated to Json.NET.