springboot集成Elasticsearch高亮显示(比较复杂)

本文档展示了如何在Spring Boot项目中整合Elasticsearch,并配置相关依赖,设置集群信息。接着,定义了一个索引类型实体类`Product`,用于映射Elasticsearch的索引。在测试类中,演示了如何进行高亮查询操作,通过`NativeSearchQueryBuilder`构造查询条件,使用`HighlightBuilder`进行高亮设置,最后将结果进行解析并打印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 {
    @Autowired
    private ProductService service;

    //注入dao层是为了调用父接口中的方法进来封装条件,来完成一系列的操作
    @Autowired
    private ProductRepository repository;

    //注入模板对象,高亮的时候使用
    @Autowired
    private ElasticsearchTemplate template;
    
    //查询商品标题  或者简介中 符合 蓝牙 指纹 双卡 字样的商品,并且高亮显示
    @Test
    void 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() {
            @Override
            public <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);
            }

            @Override
            public <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);

    }



}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值