报错信息:

2025-05-21T15:56:04.730+08:00 DEBUG 30384 --- [wxf-backend-client] [nio-8080-exec-2]
 .m.m.a.ExceptionHandlerExceptionResolver : Resolved [java.lang.RuntimeException: 搜索失败:
co.elastic.clients.transport.TransportException: node: http://127.0.0.1:9200/, status: 200,
 [es/search] Failed to decode response]

如果你的项目满足以下条件:

  • 你的项目中映射到elasticsearch文档的类包含 OffsetDataTime 类型的字段
  • 已经给OffsetDataTime类型的字段加了注解 @JsonFormat 

  • 已经注册了全局的 JavaTimeModule 
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());
        objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        return objectMapper;
    }

}

解决方法:

新建一个ElasticsearchConfig类并输入以下代码:

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ElasticsearchConfig {

    @Autowired
    private RestClient restClient; // 注入 Spring Boot 自动配置的 RestClient

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.registerModule(new JavaTimeModule());

        JacksonJsonpMapper jacksonJsonpMapper = new JacksonJsonpMapper(objectMapper);

        RestClientTransport transport = new RestClientTransport(restClient, jacksonJsonpMapper);
        return new ElasticsearchClient(transport);
    }
}

原因:

  • Spring Boot 的全局 ObjectMapper 配置(JacksonConfig)只对 Spring MVC、RabbitMQ 等生效,不会自动作用于 elasticsearch-java 客户端。
  • elasticsearch-java 客户端默认的 Jackson 实例没有注册 JavaTimeModule,所以无法反序列化 OffsetDateTime。所以需要自定义 ElasticsearchClient 的配置来注册 JavaTimeModule。

 

    Logo

    中国智能体开发者社区,聚焦智能体与大模型开发,提供前沿资讯、实用工具链、开源项目及行业案例。通过技术沙龙、开发者大赛等活动,促进经验交流与协作,助力开发者快速构建创新智能应用。

    更多推荐