ES如何打印DSL
- 开源代码
- 2025-09-19 12:54:02

看了一下官网版本已经来到了8.17
正常打印似乎不行,突破的地方则是 藏在@JsonpDeserializable 这个注解上;
@JsonpDeserializable public class SearchRequest因此只有反序列化出来之后才能打印,似乎就这么简单,看源码或许能更快的解决问题
方法一 查询打印 SearchRequest.Builder builder = new SearchRequest.Builder(); builder.query(q -> q.bool(boolQuery)); SearchRequest build = builder.build(); log.info("search request:【{}】", searchDSL(build)); public String searchDSL(SearchRequest searchRequest) { // 创建 JSON 生成器和 JSON 映射器 try (StringWriter writer = new StringWriter(); JsonGenerator generator = Json.createGenerator(writer) ) { JsonpMapper mapper = new JacksonJsonpMapper(); searchRequest.serialize(generator, mapper); generator.close(); return writer.toString(); } catch (Exception e) { log.error("search exception", e); } return null; }打印es请求日志,在application.properties中添加 或者放到yaml 文件中
logging.level.org.elasticsearch.client.RestClient=DEBUG效果
2025-02-26T22:59:26.458+08:00 INFO 35528 --- [unique-search] [nio-8080-exec-4] c.u.framework mon.utils.EsClient : search request:【{"query":{"bool":{"must":[{"term":{"id":{"value":"1"}}},{"term":{"edition":{"value":"工信部出版社"}}},{"fuzzy":{"bookName":{"value":"我"}}}]}}}】 2025-02-26T22:59:26.594+08:00 DEBUG 35528 --- [unique-search] [nio-8080-exec-4] org.elasticsearch.client.RestClient : request [POST localhost:9200/textbook/_search?typed_keys=true] returned [HTTP/1.1 200 OK]
方式二 AOP打印使用aop对调用的方法进行处理;
import co.elastic.clients.elasticsearch.core.SearchRequest; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.aspectj.lang.annotation.Pointcut; import org.springframework.stereotype.Component; @Aspect @Component @Slf4j public class WebLogAspect { @Pointcut("execution(public * co.elastic.clients.elasticsearch.ElasticsearchClient.search(..))") public void before() { } @Before("before()") public void logRequest(JoinPoint joinPoint) { Object[] args = joinPoint.getArgs(); if (args.length > 0 && args[0] instanceof SearchRequest) { SearchRequest searchRequest = (SearchRequest) args[0]; log.info("请求参数: {}", searchRequest); } } }效果
2025-03-01T18:23:02.180+08:00 INFO 30812 --- [unique-search] [nio-8080-exec-4] c.u.framework mon.aop.WebLogAspect : 请求参数: SearchRequest: POST /textbook/_search?typed_keys=true {"from":0,"query":{"bool":{"must":[{"wildcard":{"email":{"value":"*qq "}}}]}},"size":10,"sort":[{"id":{"order":"desc"}}]}