Springboot2.X+Elasticsearch 实现分词搜索

Elasticsearch 安装

添加小编微信进入java学习交流群,小编微信:372787553,备注进群

具体安装步骤网上很多,大家可以借鉴一下;
关于分词插件的安装可以执行一下命令:
拼音插件
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-pinyin/releases/download/v6.1.1/elasticsearch-analysis-pinyin-6.1.1.zip
中文插件
./bin/elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v6.1.1/elasticsearch-analysis-ik-6.1.1.zip
如不行执行在线下载,也可以离线下载
放在安装 elasticsearch 下plugins内即可

Boot + Es

1.相关依赖

本文用的是boot2.0.2,这里也配置了数据库



    4.0.0
    
        com.javayh
        javayh-oauth2
        0.0.1-SNAPSHOT
        ../
    
    com.javayh
    javayh-elasticsearch
    0.0.1-SNAPSHOT
    javayh-elasticsearch
    jar
    Demo project for Spring Boot

    
        1.8
    

    
        
            com.javayh
            javayh-commons
            0.0.1-SNAPSHOT
        
        
            org.springframework.boot
            spring-boot-starter-data-elasticsearch
        
        
            mysql
            mysql-connector-java
        
        
            org.springframework.cloud
            spring-cloud-starter-netflix-eureka-client
        
        
            net.java.dev.jna
            jna
            3.0.9
        
    

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


2.配置文件

server:
  port: 8087

spring:
  application:
    name: javayh-elastic
  data:
    elasticsearch:
      repositories:
        enabled: true
      cluster-name: elasticsearch
      cluster-nodes: 127.0.0.1:9300
      properties:
        path:
          logs: ./elasticsearch/log
          data: ./elasticsearch/data
      local: true
  datasource:
    url: jdbc:mysql://localhost:3306/test?characterEncoding=UTF-8&useUnicode=true&useSSL=false
    username: root
    password: 1219320
    driver-class-name: com.mysql.jdbc.Driver

mybatis:
  dao-locations: classpath:dao/*.mapper
  type-aliases-package: com.javayh.entity

eureka:
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
  client:
    service-url:
      defaultZone: http://localhost:8090/eureka/

3.实体映射

@Data
@Document(indexName = "javayh",type = "sys_es")
public class EsEntiy implements Serializable {
    @Id
    private String esId;
    @Field(type = FieldType.Text)
    private String esIndex;
    @Field(type = FieldType.Text)
    private String esType;
    @Field(type = FieldType.Text)
    private String esCode;
}

4.Repository JPA的封装

@Repository
public interface EsRepository extends ElasticsearchRepository {
}

5.EsService

这里包含了新增、普通的查询、模糊查询、高亮检索

@Service
public class EsService {

    @Autowired
    private EsRepository esRepository;

    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;

    /**
     * 保存
     * @param esEntiy
     * @return
     */
    public EsEntiy save(EsEntiy esEntiy){
        if (StringUtils.isEmpty(esEntiy.getEsCode()))
            throw new BaseException("eslasticsearch code is null");
        esEntiy.setEsId(UuidUtils.getUuid());
        return esRepository.save(esEntiy);
    }

    /**
     * 查询
     * @param code
     * @return
     */
    public EsEntiy findbyEs(String code){
        Optional byId = esRepository.findById(code);
        return byId.get();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    public int delete(String id){
        if(StringUtils.isEmpty(id))
            esRepository.deleteById(id);
        EsEntiy esEntiy = esRepository.findById(id).get();
        return  esEntiy == null ? 0: 1 ;
    }

    /**
     * matchQuery       : 单个字段查询
     * matchAllQuery    : 匹配所有
     * multiMatchQuery  : 多个字段匹配某一个值
     * wildcardQuery    : 模糊查询
     * boost            : 设置权重,数值越大权重越大
     * 混合搜索
     * @param content
     * @return
     */
    public Page querySearch(String content){
        DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
        QueryBuilder ikTypeQuery = QueryBuilders.matchQuery("esType", content).boost(2f);
        QueryBuilder pinyinTypeQuery = QueryBuilders.matchQuery("esType.pinyin", content);
        QueryBuilder ikCodeQuery = QueryBuilders.matchQuery("esCode", content).boost(2f);
        QueryBuilder pinyinCodeQuery = QueryBuilders.matchQuery("esCode.pinyin", content);
        QueryBuilder wildcardCodeQuery = QueryBuilders.wildcardQuery("esCode", content);
        QueryBuilder multiCodeQuery = QueryBuilders.multiMatchQuery(content,"esType","esCode");
        disMaxQueryBuilder.add(ikTypeQuery);
        disMaxQueryBuilder.add(pinyinTypeQuery);
        disMaxQueryBuilder.add(ikCodeQuery);
        disMaxQueryBuilder.add(pinyinCodeQuery);
        disMaxQueryBuilder.add(wildcardCodeQuery);
        disMaxQueryBuilder.add(multiCodeQuery);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(disMaxQueryBuilder).build();
        Page search = esRepository.search(searchQuery);
        return search;
    }

    /**
     * 高亮检索
     * @param type
     * @return
     */
    public AggregatedPage querySearchType(String type){
        DisMaxQueryBuilder disMaxQueryBuilder = QueryBuilders.disMaxQuery();
        QueryBuilder ikTypeQuery = QueryBuilders.wildcardQuery("esType", type).boost(2f);
        QueryBuilder ikCodeQuery = QueryBuilders.wildcardQuery("esCode", type).boost(2f);
        List highlightFields = new ArrayList();
        highlightFields.add("esType");
        highlightFields.add("esCode");
        HighlightBuilder.Field[] fields = new HighlightBuilder.Field[highlightFields.size()];
        for (int x = 0; x < highlightFields.size(); x++) {
            fields[x] = new HighlightBuilder.Field(highlightFields.get(x)).preTags(EsHighlight.HIGH_LIGHT_START_TAG)
                    .postTags(EsHighlight.HIGH_LIGHT_END_TAG);
        }
        disMaxQueryBuilder.add(ikTypeQuery);
        disMaxQueryBuilder.add(ikCodeQuery);
        SearchQuery searchQuery = new NativeSearchQueryBuilder()
                .withQuery(disMaxQueryBuilder)
                .withHighlightFields(fields)
                //.withPageable(PageRequest.of(1, 10))
                .build();
        //不需要高亮就直接分页返回
        //Page esEntiys = esRepository.search(searchQuery);
        //高亮显示
        AggregatedPage esEntiys = elasticsearchTemplate.queryForPage(searchQuery, EsEntiy.class, new SearchResultMapper() {
            @Override
            public  AggregatedPage mapResults(SearchResponse searchResponse, Class aClass, Pageable pageable) {
                pageable = PageRequest.of(1, 10);
                List chunk = new ArrayList<>();
                for (SearchHit searchHit : searchResponse.getHits()) {
                    if (searchResponse.getHits().getHits().length <= 0) {
                        return null;
                    }
                    EsEntiy esEntiy = new EsEntiy();
                    esEntiy.setEsId(searchHit.getId());
                    esEntiy.setEsIndex(searchHit.getIndex());
                    //name or memoe
                    HighlightField code = searchHit.getHighlightFields().get("esCode");
                    if (code != null) {
                        esEntiy.setEsCode(code.fragments()[0].toString());
                    } else {
                        Object esCode = searchHit.getSourceAsMap().get("esCode");
                        if(esCode == null)
                            esEntiy.setEsCode("");
                        else
                            esEntiy.setEsCode(esCode.toString());
                    }
                    HighlightField type = searchHit.getHighlightFields().get("esType");
                    if (type != null) {
                        esEntiy.setEsType(type.fragments()[0].toString());
                    }else {
                        Object esType = searchHit.getSourceAsMap().get("esType");
                        if(esType == null )
                            esEntiy.setEsType("");
                        else
                            esEntiy.setEsType(esType.toString());
                    }
                    chunk.add(esEntiy);
                }
                if (chunk.size() > 0) {
                    return  new AggregatedPageImpl((List) chunk);
                }
                return null;
            }
        });
        return esEntiys;
    }
}

6. 高亮配置

承接上边的代码

public interface EsHighlight {
    /**
     * 高亮显示 - 开始标签
     */
    String HIGH_LIGHT_START_TAG = "";

    /**
     * 高亮显示 - 结束标签
     */
    String HIGH_LIGHT_END_TAG = "";

    /**
     * 索引名称
     */
    class INDEX_NAME {
        /**
         * 游记
         */
        public static final String TRAVEL = "travel";
    }

效果展示

1.新增

Springboot2.X+Elasticsearch 实现分词搜索_第1张图片
我们可以通过es-head进行查看
Springboot2.X+Elasticsearch 实现分词搜索_第2张图片

2. 高亮检索

Springboot2.X+Elasticsearch 实现分词搜索_第3张图片
可以看出已经将我们的搜索条件“测”,进行了高亮显示
boot2.X整合es已经完成,希望对看到的朋友有所帮助!
如有疑问可以添加小编微信:372787553,互相交流!

关注 Java有货领取更多资料

联系小编。微信:372787553,带您进群互相学习
左侧小编微信,右侧获取免费资料
在这里插入图片描述

  • SpringCloud 自定义封装架构https://github.com/yanghaiji/javayh-platform
  • Java 设计模式学习代码 https://github.com/yanghaiji/design-pattern
  • SpringCloud学习代码: https://github.com/yanghaiji/javayh-cloud
  • AlibabaCloud学习代码:https://github.com/yanghaiji/javayh-cloud-nacos
  • SpringBoot+Mybatis 多数据源切换:https://github.com/yanghaiji/javayh-boot-data-soure
  • Redis、Mongo、Rabbitmq、Kafka学习代码: https://github.com/yanghaiji/javayh-middleware
  • SpringBoot+SpringSecurity实现自定义登录学习代码:https://github.com/yanghaiji/javayh-distribution

你可能感兴趣的:(Elasticsearch)