Spring Boot 和 ElasticSearch 文档中日期转换异常

fsk*_*fsk 2 java elasticsearch spring-boot spring-data-elasticsearch spring-repositories

当我运行 Spring Boot 代码(带有 ElasticSearch)时,出现错误。

我想列出我的elasticsearch车辆文档中所有存在的元素

org.springframework.data.elasticsearch.core.convert.ConversionException: Unable to convert value '2022-01-01' to java.util.Date for property 'created'
Run Code Online (Sandbox Code Playgroud)

我尝试了这个这个链接。

但没有用。

我该如何解决这个问题?

以下代码是我的车辆类。

@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;

}
Run Code Online (Sandbox Code Playgroud)

以下接口是我的 VehicleRepository 接口

public interface VehicleRepository extends ElasticsearchRepository<Vehicle, String> {

    Page<Vehicle> findAll();

}
Run Code Online (Sandbox Code Playgroud)

以下代码是我的 getList 服务方法

    public List<Vehicle> getVehicleList() {
        return vehicleRepository.findAll().getContent();
    }
Run Code Online (Sandbox Code Playgroud)

以下代码是我的车辆控制器端点

    private final VehicleService vehicleService;

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

P.J*_*sch 5

索引中存储的日期似乎是本地日期(“2022-01-01”,没有时区,没有时间戳)。java.util.Date是 UTC 时区的某个时刻。您无法将仅日期字符串转换为日期。您的模式字符串包含的时间也与该字符串不匹配。

并且不要使用古老的类,而是使用自 Java 8 以来可用的包java.util.Date中的类。java.time

你应该使用

@Field(type = Date, format = DateFormat.date)
LocalDate created;
Run Code Online (Sandbox Code Playgroud)

并重新创建索引以调整映射。