Home > Enterprise >  how to format and store date in ElasticSearch
how to format and store date in ElasticSearch

Time:01-17

I am trying to store date value in ElasticSearch. BElow is my code

pom.xml

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

Model class

@Document(indexName="employee", createIndex=true, shards = 4)
public class Employee { 
   @Nullable
    @Field(type = FieldType.Date, pattern = "yyyy-MM-dd", format = DateFormat.date)
    private LocalDate joinedDate;
}

ElasticSearch index properties

"mappings": {
"employee": {
"properties": {
"joinedDate": {
"format": "date",
"type": "date"
}

My Configuration file

@Configuration
@EnableElasticsearchRepositories("com.sample.dao")
public class ElasticSearchClientBuilder extends AbstractElasticsearchConfiguration{
    Logger logger = LoggerFactory.getLogger(ElasticSearchClientBuilder.class);
 

    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
    //Configuration for ResthighClient
    }
    }

Error i am getting for above setting

Caused by: org.elasticsearch.client.ResponseException: method [PUT], host [https://ausdlcceesdb01.us.dell.com:9200], URI [/employee/employee/a77055df-2a79-4d8d-8911-315003bfed28?timeout=1m], status line [HTTP/1.1 400 Bad Request]
Warnings: [299 Elasticsearch-7.6.2-ef48eb35cf30adf4db14086e8aabd07ef6fb113f "[types removal] Specifying types in document index requests is deprecated, use the typeless endpoints instead (/{index}/_doc/{id}, /{index}/_doc, or /{index}/_create/{id})."]
{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"failed to parse field [joinedDate] of type [date] in document with id 'a77055df-2a79-4d8d-8911-315003bfed28'. Preview of field's value: '{dayOfWeek=THURSDAY, month=JANUARY, year=2022, dayOfMonth=6, era=CE, dayOfYear=6, monthValue=1, chronology={calendarType=iso8601, id=ISO}, leapYear=false}'"}],
"type":"mapper_parsing_exception","reason":"failed to parse field [joinedDate] of type [date] in document with id 'a77055df-2a79-4d8d-8911-315003bfed28'. Preview of field's value: '{dayOfWeek=THURSDAY, month=JANUARY, year=2022, dayOfMonth=6, era=CE, dayOfYear=6, monthValue=1, chronology={calendarType=iso8601, id=ISO}, leapYear=false}'","caused_by":{"type":"illegal_state_exception","reason":"Can't get text on a START_OBJECT at 1:83"}},
"status":400}

Without pattern in model my date is stores as below columns in index

        
joinedDate.year
joinedDate.month
joinedDate.dayOfMonth
joinedDate.dayOfWeek
joinedDate.era
joinedDate.dayOfYear
joinedDate.monthValue
joinedDate.chronology
joinedDate.leapYear

Please help how to store yyyy-MM-dd in index

CodePudding user response:

I think you will need something like this:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS")
@JsonSerialize(using = CustomLocalDateTimeSerializer.class)
@JsonDeserialize(using = CustomLocalDateTimeDeserializer.class)
private LocalDateTime createDate;

CustomLocalDateTimeSerializer class:

public class CustomLocalDateTimeSerializer extends StdSerializer<LocalDateTime> {


    public CustomLocalDateTimeSerializer() {
        this(null);
    }

    private CustomLocalDateTimeSerializer(Class<LocalDateTime> t) {
        super(t);
    }

    @Override
    public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider provider) throws IOException {
        gen.writeString(value.format(DateTimeFormatter.ofPattern(Constants.DATE_FORMAT_SIMPLE)));
    }
}

CustomLocalDateTimeDeserializer class:

public class CustomLocalDateTimeDeserializer extends StdDeserializer<LocalDateTime> {

    public CustomLocalDateTimeDeserializer() {
        this(null);
    }

    private CustomLocalDateTimeDeserializer(Class<LocalDateTime> t) {
        super(t);
    }

    @Override
    public LocalDateTime deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException, JsonProcessingException {            
        String date = jsonParser.getText();
        try {
            return LocalDateTime.parse(date);
        } catch (Exception ex) {
            log.debug("Error while parsing date: {} ", date, ex);
            throw new RuntimeException("Cannot Parse Date");
        }
    }
}
  •  Tags:  
  • Related