Search code examples
javaspring-bootelasticsearchspring-data-elasticsearchspring-repositories

Date Conversion Exception in Spring Boot and ElasticSearch Document


While i running my Spring Boot code (with have ElasticSearch), i give an error.

i want to list get that all exist element in my elasticsearch vehicle document

org.springframework.data.elasticsearch.core.convert.ConversionException: Unable to convert value '2022-01-01' to java.util.Date for property 'created'

i tried this and this links.

But didnt work.

How can i fix this problem.?

Following code its my Vehicle class.

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = Indicies.VEHICLE_INDEX)
public class Vehicle {

@Id
@Field(type = FieldType.Keyword)
private String id;

@Field(type = FieldType.Text)
private String number;

@Field(type = FieldType.Text)
private String name;

@Field(type = FieldType.Date, format = DateFormat.date, pattern = "yyyy-MM-dd'T'HH:mm:ssz")
private Date created;

}

Following interface its my VehicleRepository Interface

public interface VehicleRepository extends ElasticsearchRepository<Vehicle, String> {

    Page<Vehicle> findAll();

}

Following code its my Service Method for getList

    public List<Vehicle> getVehicleList() {
        return vehicleRepository.findAll().getContent();
    }

Following code its my Vehicle Controller Endpoint

    private final VehicleService vehicleService;

    @GetMapping("/vehicle-list")
    public List<Vehicle> getVehicleList() {
        return vehicleService.getVehicleList();
    }

Solution

  • The date that is store in your index seems to be a local date ("2022-01-01", no time zone, no timestamp). java.util.Date is an instant in time in the UTC timezone. You cannot convert a date-only string into a Date. Your pattern String that contains a time that does not match the string either.

    And don't use the ancient java.util.Date class, use the classes from the java.time package which are available since Java 8.

    You should use

    @Field(type = Date, format = DateFormat.date)
    LocalDate created;
    

    and have the index recreated to adjust the mapping.