NativeSearchQuery打印完整DSL语句工具类

@Slf4j
public class DslLogUtil {

    public static void log(ElasticsearchOperations elasticsearchOperations, NativeSearchQuery nativeSearchQuery) {
        if (elasticsearchOperations instanceof ElasticsearchRestTemplate) {
            try {
                ElasticsearchRestTemplate elasticsearchRestTemplate = (ElasticsearchRestTemplate) elasticsearchOperations;
                Method searchRequest = ReflectionUtils.findMethod(Class.forName("org.springframework.data.elasticsearch.core.RequestFactory"), "searchRequest", Query.class, Class.class, IndexCoordinates.class);
                searchRequest.setAccessible(true);
                Object o = ReflectionUtils.invokeMethod(searchRequest, elasticsearchRestTemplate.getRequestFactory(), nativeSearchQuery, ChargingStationDTO.class, elasticsearchRestTemplate.getIndexCoordinatesFor(ChargingStationDTO.class));
                Field source =ReflectionUtils.findField(Class.forName("org.elasticsearch.action.search.SearchRequest"), "source");
                source.setAccessible(true);
                Object s = ReflectionUtils.getField(source, o);
                log.info("请求DSL语句:{}", s);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }


}

你可能感兴趣的:(Elasticsearch,java,打印完整DSL)