1.添加依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.2.6.RELEASE</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.xh</groupId><artifactId>01-es</artifactId><version>0.0.1-SNAPSHOT</version><name>01-es</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><scope>runtime</scope><optional>true</optional></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- es的依赖 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId></dependency><!-- 方便程序员对Bean类能够进行简便的操作。 --><dependency><groupId>commons-beanutils</groupId><artifactId>commons-beanutils</artifactId><version>1.9.3</version></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId><configuration><excludes><exclude><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId></exclude></excludes></configuration></plugin></plugins></build></project>

2.配置文件

spring.application.name=es#配置服务器的名字  只能是这个名字
spring.data.elasticsearch.cluster-name=elasticsearch
#配置集群节点的名字  es的连接地址及端口号
spring.data.elasticsearch.cluster-nodes=localhost:9300#是否开启本地缓存
spring.data.elasticsearch.repositories.enabled=true

3.索引类型实体类

package com.xh.domain;import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;/*** @Description:* @Author: xiaohao* @Time: 2022/3/14 12:04*/
/*indexName:索引type:索引里面的类型*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "es_shop",type = "shop_product")
public class Product {private String id;/*analyzer 存储时使用的分词器searchAnalyzer  搜索时使用的分词器type  数据类型*/@Field(analyzer = "ik_smart", searchAnalyzer = "ik_smart", type = FieldType.Text)private String title;private Integer price;//价格@Field(analyzer = "ik_smart", searchAnalyzer = "ik_smart", type = FieldType.Text)private String intro;//简介//FieldType.Keyword 关键字@Field(type = FieldType.Keyword)private String brand;//品牌
}

4.高亮处理,测试类中

package com.xh;import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xh.dao.ProductRepository;
import com.xh.domain.Product;
import com.xh.service.ProductService;
import com.xh.service.impl.ProductServiceImpl;
import org.apache.commons.beanutils.BeanUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.junit.Ignore;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.SearchResultMapper;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.aggregation.impl.AggregatedPageImpl;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;import java.io.IOException;
import java.util.ArrayList;
import java.util.List;@SpringBootTest
class ApplicationTests {@Autowiredprivate ProductService service;//注入dao层是为了调用父接口中的方法进来封装条件,来完成一系列的操作@Autowiredprivate ProductRepository repository;//注入模板对象,高亮的时候使用@Autowiredprivate ElasticsearchTemplate template;//查询商品标题  或者简介中 符合 蓝牙 指纹 双卡 字样的商品,并且高亮显示@Testvoid testHightlight() {ObjectMapper mapper = new ObjectMapper();//建造一个NativeSearchQuery查询对象;,相当于把条件封装在里面NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();//你需要去找的索引和类型builder.withIndices("es_shop").withTypes("shop_product");//将条件封装在里面用于模糊查询builder.withQuery(QueryBuilders.multiMatchQuery("蓝牙 指纹 双卡 ","title","intro"));//在列添加属性builder.withHighlightFields(new HighlightBuilder.Field("title").preTags("<span style='color:red;'>").postTags("</span>"),new HighlightBuilder.Field("intro").preTags("<span style='color:red;'>").postTags("</span>"));AggregatedPage<Product> page = template.queryForPage(builder.build(), Product.class, new SearchResultMapper() {@Overridepublic <T> AggregatedPage<T> mapResults(SearchResponse response, Class<T> clazz, Pageable pageable) {List<T> list = new ArrayList<>();for (SearchHit hit:response.getHits().getHits()) {list.add(mapSearchHit(hit,clazz));}long total = response.getHits().totalHits;return new AggregatedPageImpl<>(list, pageable, total);}@Overridepublic <T> T mapSearchHit(SearchHit searchHit, Class<T> type) {T t= null;try {t = mapper.readValue(searchHit.getSourceAsString(), type);for (HighlightField field:searchHit.getHighlightFields().values()) {//替换一下高亮显示的字段BeanUtils.setProperty(t, field.getName(), field.getFragments()[0].string());}} catch (Exception e) {e.printStackTrace();return null;}return t;}});page.forEach(System.err::println);}}

springboot集成Elasticsearch高亮显示(比较复杂)相关推荐

  1. 史上最简单的Elasticsearch教程:SpringBoot集成Elasticsearch 实时流量监测平台

    SpringBoot集成Elasticsearch 实时流量监测平台 目录: 第一章:初尝 Elasticsearch 第二章:玩转 Kibana 第三章:开发原生 Elasticsearch 案例 ...

  2. GitChat优质文章-SpringBoot集成Elasticsearch

    Elasticsearch 是一个基于 Lucene 库的搜索引擎.Elasticsearch 是目前大数据领域最热门的技术栈之一.目前 Elasticsearch 被广泛应用在搜索.安全.数据分析等 ...

  3. springboot集成Elasticsearch实现各种搜索功能

    springboot集成Elasticsearch各类搜索功能实现 springboot集成Elasticsearch使用completion suggest实现自动关键字补全 建立学生的索引和映射: ...

  4. 【SpringBoot高级篇】SpringBoot集成Elasticsearch搜索引擎

    [SpringBoot高级篇]SpringBoot集成Elasticsearch搜索引擎 1. 什么是Elasticsearch? 2. 安装并运行Elasticsearch 2.1 拉取镜像 2.2 ...

  5. Springboot集成elasticsearch 使用IK+拼音分词

    Springboot集成elasticsearch 使用IK+拼音分词 docker安装ES 下载 docker pull docker.elastic.co/elasticsearch/elasti ...

  6. springboot——集成elasticsearch进行搜索并高亮关键词

    目录 1.elasticsearch概述 3.springboot集成elasticsearch 4.实现搜索并高亮关键词 1.elasticsearch概述 (1)是什么: Elasticsearc ...

  7. springboot集成elasticsearch,实现搜索提示补全功能

    springboot集成elasticsearch,通过实体类创建索引,实现搜索提示补全功能 文章目录 springboot集成elasticsearch,通过实体类创建索引,实现搜索提示补全功能 一 ...

  8. 自学笔记-SpringBoot集成ElasticSearch

    目录 一.ElasticSearch介绍: 二.ElasticSearch安装: 三.Kibana的安装 四.配置ik分词器 五.Springboot集成ElasticSearch Ⅰ.依赖 Ⅱ.配置 ...

  9. SpringBoot集成Elasticsearch搜索引擎(九)

    官网:https://www.elastic.co/cn/ 官方文档:https://www.elastic.co/guide/en/elasticsearch/reference/current/i ...

最新文章

  1. caffe-cuda测试
  2. Python存储生成的决策树——pickle模块
  3. DC/OS 的安装与部署
  4. 【官方教程】Ubuntu 安装 mongoDB
  5. PHP正则表达式入门教程
  6. SHFileOperation的用法
  7. excel找出重复值
  8. 用C++实现魔方并输出步骤
  9. 三个基本的布尔逻辑算符是_什么是布尔逻辑运算符?布尔逻辑运算符一共有哪几种?...
  10. 将微信聊天记录转成txt文件的最实用方法
  11. 机器学习的安全及隐私保护研究
  12. 冯诺依曼结构、哈佛结构、改进型哈佛结构
  13. 解决mysql load data加载本地null数据,表里出现0的情况
  14. UI-网站首页轮播图、易拉宝、发布在微信公众号的宣传海报的图片设计信息
  15. 巧推网站seo优化推动网站快速排名
  16. 什么叫矫顽力(bHc),什么叫内禀矫顽力(jHc)?
  17. 玩vr游戏的计算机配置要求,4款电脑横向评测: 寻找最适合玩VR的PC配置
  18. 通过率低推广费昂贵 - 中国苹果开发者掘金难
  19. mysql 分批提交_spark dataframe 数据批量写入 redis(pipeline、分批提交)
  20. JAVA翻译HTML网页内容

热门文章

  1. XCTF攻防世界Web之WriteUp
  2. ps选中区域填充前景色
  3. Wwise入门和实战
  4. docker下载镜像timeout超时
  5. 机房收费系统——概览
  6. 避免window.open弹出窗口被阻止,避免IE7限制,在登录成功后弹出窗口屏蔽菜单栏地址栏
  7. 西门子plc的上升沿和下降沿是什么意思?
  8. iview添加自定义表头
  9. 前序、中序和后序表达式转换问题
  10. less加管道tail_第二天作业