1. 首页
  2. 软件开发
  3. JAVA
  4. Spring boot简单集成Elasticsearch

Spring boot简单集成Elasticsearch

  • 发布于 2024-08-15
  • 0 次阅读

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

文章目录

概述

本文主要介绍 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 解释说明
待续~

源码

码云