ElasticSearch Spring-Data Date format always is long

后端 未结 4 707
Happy的楠姐
Happy的楠姐 2021-02-07 06:01

When using spring-data to insert Elasticsearch document with Date type, I can\'t get right date format, the date format always is Long.

here is the java code: Entity.jav

相关标签:
4条回答
  • 2021-02-07 06:55

    Starting from Elasticsearch 7 you should't use yyyy but uuuu. e.g:

    @Field(type = FieldType.Date, format = DateFormat.custom, pattern = "uuuu-MM-dd'T'HH:mm:ss.SSSZZ")
    private Date lastModifiedDate;
    

    You don't need @JsonProperty because now Spring Data Elasticsearch doesn't use Jackson but instead a MappingElasticsearchConverter. With this annotation, a converter is automatically created for this property and used.

    0 讨论(0)
  • 2021-02-07 07:01

    It worked for me with below settings. Note: delete your index before to test this change. Make sure that the patterns are same at all places.

    @Field(type = FieldType.Date, store = true, format = DateFormat.custom, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    @JsonFormat (shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
    private Date date;
    
    0 讨论(0)
  • 2021-02-07 07:04

    Something to keep in mind:

    JSON doesn’t have a date data type, so dates in Elasticsearch can either be:

    • Strings containing formatted dates, e.g. "2015-01-01" or "2015/01/01. 12:10:30".
    • A long number representing milliseconds-since-the-epoch.
    • An integer representing seconds-since-the-epoch.

    Also from the same doc:

    Dates will always be rendered as strings, even if they were initially supplied as a long in the JSON document

    This implies that querying the data type for a date field will always be a string, a long or an integer. There is no special "Date" field in elastic search.

    Read more here: https://www.elastic.co/guide/en/elasticsearch/reference/current/date.html

    0 讨论(0)
  • 2021-02-07 07:07

    Your mapping is created correctly. The problem is more likely to come from the Jackson JSON serializer. You should try adding this annotation to your date fields: @JsonFormat (shape = JsonFormat.Shape.STRING, pattern ="yyyy-MM-dd'T'HH:mm:ss.SSSZZ").

    There are also some alternative solutions that might better suit your case (i.e. creating a CustomDateSerializer, etc).

    0 讨论(0)
提交回复
热议问题