栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

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

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

1.添加依赖


    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.2.6.RELEASE
         
    
    com.xh
    01-es
    0.0.1-SNAPSHOT
    01-es
    Demo project for Spring Boot
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
        
        
            commons-beanutils
            commons-beanutils
            1.9.3
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



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;



@Data
@AllArgsConstructor
@NoArgsConstructor
@document(indexName = "es_shop",type = "shop_product")
public class Product {
    private String id;
    
    @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("").postTags(""),
                new HighlightBuilder.Field("intro").
                        preTags("").postTags("")
        );
        AggregatedPage page = template.queryForPage(builder.build(), Product.class, new SearchResultMapper() {
            @Override
            public  AggregatedPage mapResults(SearchResponse response, Class clazz, Pageable pageable) {
                List 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 mapSearchHit(SearchHit searchHit, Class 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);

    }



}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/762003.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号