SpringBoot 2.x集成Elasticsearch 多字段高亮显示
1.主要依赖
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.1.RELEASE</version>
</parent>
<!-- 对应的ES版本是 6.4.3 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>commons-beanutils</groupId>
<artifactId>commons-beanutils</artifactId>
<version>1.9.3</version>
</dependency>
2.核心代码
Pageable pageable = new PageRequest(0, 10);
HighlightBuilder.Field allHighLight = new HighlightBuilder.Field("firstCode").
preTags("<span style=\"color:red\">").postTags("</span>").requireFieldMatch(false);
HighlightBuilder.Field allHighLight1 = new HighlightBuilder.Field("secordCode").requireFieldMatch(false).
preTags("<span style=\"color:red\">").postTags("</span>");
HighlightBuilder.Field[] ary = new HighlightBuilder.Field[2];
ary[0] = allHighLight;
ary[1] = allHighLight1;
SearchQuery query = new NativeSearchQueryBuilder().
withQuery(QueryBuilders.matchQuery("firstCode",bean.getFirstCode())).
withQuery(QueryBuilders.matchQuery("secordCode",bean.getSecordCode())).
withHighlightFields(ary).
build();
Page<DocBean> search = elasticsearchTemplate.queryForPage(query,DocBean.class, myResultMapper);
return search;
3.工具类MyResultMapper
package com.example.rest.service.impl;
import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonGenerator;
import org.apache.commons.beanutils.PropertyUtils;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.document.DocumentField;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.<