一、问题调试
1.1 问题:发现后台可以正常搜索数据,但是在for循环输出传递到前端的时候出了问题,highlightFields变为null了
1.2 debug
分页,遍历搜索的结果for (SearchHit hit : search.getHits())
接着获取hit.getHighlightFields(),经过调试排查发现获取为null
此时的hit是一个SearchHit对象
我们进入SearchHit类中查看hit.getHighlightFields()方法的源码,发现由于this.highlightFields = null,此方法会返回null
return this.highlightFields == null ? Collections.emptyMap() : this.highlightFields;
因此这里的Map<>自然也就什么都接不到了,highlightFields也为null了。
1.3 去SearchResponse类查找为什么hit的highlightFields属性会为null
SearchHit类的hit对象是由search.getHits()得到的,而search是一个SearchResponse类
我们进入getHits方法
public SearchHits getHits() {
return this.internalResponse.hits();
}
发现其getHits()是另一个类中的hit()
二、解决
加高亮操作参考:ElasticSearch7.9.3集成Springboot 高亮查询
SpringBoot+Elasticsearch-7.X实现高亮分词搜索
ElasticSearch7.x版本踩坑记录:SpringBoot2.3.x整合ElasticSearch7.x(ElasticsearchRestTemplate)
最后不加高亮操作,直接转为json,然后转为对象,前端也正常了
public List