Spring boot简单集成Elasticsearch

概述

本文主要介绍Spring boot如何简单集成Elasticsearch,关于es,可以理解为一个数据库,往es中插入数据,然后使用es进行检索。

步骤

  1. 环境准备
    安装es 和kibana :参考
    安装ik分词器:参考

  2. 相关配置
    pom.xml文件中引入es:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    

    yml文件配置es:

    # 数据源配置
    spring:
       elasticsearch:
           uris: localhost:9200
           username:
           password:
    
  3. ES查询
    往es插数据

    /**
     * 新增测试 - DB数据插入ES
     */
    @PreAuthorize("@ss.hasPermi('test:post1:add')")
    @Log(title = "测试", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysPost1 sysPost1)
    {
        sysPost1Service.insertSysPost1(sysPost1);
        this.updateToEs(sysPost1.toEsDocument());
        return toAjax(1);
    }
    
    private void updateToEs(SysPostEsDocument sysPostEsDocument){
        sysPostESService.save(sysPostEsDocument);
    }
    
    
    

需要让mapper层继承ElasticsearchRepository:

public interface SysPostEsRepository extends ElasticsearchRepository<SysPostEsDocument, Long> {
}

自定义es实体(即索引)

@Document(indexName = "post")
@Data
public class SysPostEsDocument {
    /**
     * ID
     */
    @Id
    private Long postId;

    /** 岗位编码 */
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart", copyTo = "searchKey")
    private String postCode;

    /** 岗位名称 */
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart", copyTo = "searchKey")
    private String postName;

    /** 岗位排序 */
    @Field(type = FieldType.Long)
    private Integer postSort;

    /** 状态(0正常 1停用) */
    @Field(type = FieldType.Keyword)
    private String status;

    public SysPost1 toSysPost1() {
        SysPost1 sysPost1 = new SysPost1();
        BeanUtils.copyProperties(this, sysPost1);
        return sysPost1;
    }

}

使用es进行分词检索:

@Resource
    private ElasticsearchRestTemplate esTemplate;
        /**
     * ES分词检索
     */
    @PostMapping("/search")
    public AjaxResult search(@RequestBody SysPost1 sysPost) throws Exception
    {
        Pageable pageRequest = getPage(sysPost.getCurrent(), sysPost.getPageSize());
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        /*if (!StringUtils.isBlank(sysPost.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("searchKey", sysPost.getKeyword()));
        }*/
        if (!StringUtils.isBlank(sysPost.getPostCode())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("postCode", sysPost.getPostCode()));
        }
        NativeSearchQuery searchQuery = new NativeSearchQuery(boolQueryBuilder);
        //searchQuery.addSort(Sort.by(Sort.Order.desc("id")));
        searchQuery.setPageable(pageRequest);
        SearchHits<SysPostEsDocument> searchResult = esTemplate.search(searchQuery, SysPostEsDocument.class);
        List<SysPost1> collect = searchResult.get().map(SearchHit::getContent).map(SysPostEsDocument::toSysPost1)
                .collect(Collectors.toList());
        return AjaxResult.success(collect);
    }

小结

  1. 多关键词检索
    即用一个搜索框同时匹配多个字段。需要在es实体中做如下配置:
/** 岗位编码 */
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart", copyTo = "searchKey")
    private String postCode;

    /** 岗位名称 */
    @Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart", copyTo = "searchKey")
    private String postName;
	
	@Field(type = FieldType.Text, analyzer = "ik_max_word", searchAnalyzer = "ik_smart")
    private String searchKey;

使用es搜索的代码:

boolQueryBuilder.must(QueryBuilders.matchQuery("searchKey", sysPost.getKeyword()));

解释:使用copyTo将postCode和postName两个字段拷贝到searchKey上,这样就让前端的搜索字段keyword,匹配上了es索引中的postCode和postName两个字段,即实现了多关键词检索。
2. 注解@Document和@Field解释说明
待续~

源码

码云

  • 21
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值