SpringBoot 2.x集成Elasticsearch 多字段高亮显示

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);
        //设置需要高亮的字段 firstCode和secordCode 对应的是es中字段名称(key键)
        //preTags postTags 这两个是设置的标签内容,实现开发中可按照实际场景设置不用的标签
        //requireFieldMatch 多字段高亮需设置成false
        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.<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值