springboot 集成elasticsearch7.6.1,实现2种增删改查方式

3 篇文章 0 订阅
2 篇文章 0 订阅
本文介绍了如何在SpringBoot项目中集成Elasticsearch 7.6.1,包括配置ElasticSearchConfig、设置应用配置、创建Controller和服务实现,以及展示关键代码如数据导入ES、查询操作。详细步骤展示了如何处理数据库数据与ES之间的交互,涉及Mapper、Service和DAO层的实现。
摘要由CSDN通过智能技术生成

1、创建project

project.png

module1.png
module2.png

设置jdk.png

配置javac.png

pom.xml.png

一定要保证依赖与es版本一致

依赖与es.png

配置ElasticSearchConfig

ElasticSearchConfig.png

至此,springboot集成es7.6.1项目基本搭建完成。(创建项目时忘记截图,部分图片可能对不上。)

2、基本配置

2.1 配置文件:
application.yml
server:
  port: 8073
spring:
  profiles:
    active: dev
  thymeleaf:
    cache: false
mybatis-plus:
  mapper-locations: classpath*:/mapper/*Mapper.xml
  typeAliasesPackage: com.ghj.demoes.pojo
logging:
  level:
    com.ghj.demoes.dao:
      debug
application-dev.yml
spring:
  datasource:
    url: jdbc:mysql://192.168.1.127:3306/demo_es?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: root
# es配置
elasticsearch:
  hostname: 127.0.0.1
  port: 9200
logging:
  level:
    org.springframework.cloud: debug
    org.springframework.boot: debug
    com.ghj.demoes.dao: debug
    com.ghj.demoes.service: debug

2.2 其他配置:
application.java
package com.ghj.demoes;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.cloud.openfeign.EnableFeignClients;

@EnableFeignClients
@MapperScan("com.ghj.demoes.dao")
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
public class SaasEsApplication {

    public static void main(String[] args) {
        SpringApplication.run(SaasEsApplication.class, args);
    }

}

3、关键代码

项目结构

项目结构.png

3.1 Controller:
package com.ghj.demoes.controller;

import com.alibaba.fastjson.JSON;
import com.ghj.demoes.aop.PreSaveLog;
import com.ghj.demoes.http.ResultBody;
import com.ghj.demoes.service.EsService;
import com.ghj.demoes.service.LibraryService;
import com.ghj.demoes.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @program: 
 * @description:
 * @author: Guanzi
 * @created: 2021/10/14 15:56
 */
@Slf4j
@RestController
@RequestMapping("/es")
public class EsController {

    @Autowired
    private LibraryService libraryService;

    @Autowired
    private EsService esService;
    
    /**
     * 数据库数据批量导入es库。
     */
    @GetMapping("/save")
    public ResultBody getEs() throws IOException {
        log.info(".............");
        Map<String,Object> map = libraryService.saveToEs();
        System.err.println(JSON.toJSONString(map));
        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String uri = request.getRequestURI();
        return ResultBody.ok().path(uri).data(libraryService.testEsRepo());
    }

    /**
     * 根据名字查询es库数据。
     */
    @GetMapping("/sel/{name}")
    public ResultBody selName(@PathVariable("name") String name) throws IOException {
        log.info(".............");

        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String uri = request.getRequestURI();
        return ResultBody.ok().path(uri).data(libraryService.selName(name));
    }

    /**
     * nested类型数据查询。
     */
    @GetMapping("/client")
    public ResultBody selClient() throws IOException {
        log.info(".............");

        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        String uri = request.getRequestURI();
        return ResultBody.ok().path(uri).data(esService.findByAannualRevenue());
    }
}
3.2 Service:
package com.ghj.demoes.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ghj.demoes.dao.LibraryEntityMapper;
import com.ghj.demoes.dao.LibraryMapper;
import com.ghj.demoes.form.TaxParam;
import com.ghj.demoes.pojo.Library;
import com.ghj.demoes.pojo.LibraryEntity;
import com.ghj.demoes.service.LibraryService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @program: 
 * @description: EsDemoServiceImpl
 * @author: Guanzi
 * @created: 2021/10/14 15:31
 */
@Slf4j
@Service
@Transactional(rollbackFor = Exception.class)
public class LibraryServiceImpl extends ServiceImpl<LibraryMapper,Library> implements LibraryService {

    @Autowired
    private LibraryMapper LibraryMapper;

    @Autowired
    private LibraryEntityMapper LibraryEntityMapper;

    @Autowired
    @Qualifier("restHighLevelClient")
    private RestHighLevelClient client;


   @Override
    public Map<String, Object> saveToEs() throws IOException {
        QueryWrapper<Library> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .isNotNull(Library::getId);
        List<Library> libraryList = libraryMapper.selectList(queryWrapper);
        System.err.println(JSON.toJSONString(libraryList));

        // 批量导入es库。
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.timeout("10s");

        // 批处理请求。
        for (int i = 0; i < libraryList.size(); i++) {
            LibraryEntity libraryEntity = new LibraryEntity();
            BeanUtils.copyProperties(libraryList.get(i),libraryEntity);
            libraryEntity.setAnnualRevenue(JSONArray.parseArray
                    (libraryList.get(i).getAnnualRevenue(), TaxParam.class));
            libraryEntity.setRdDeductible(JSONArray.parseArray
                    (libraryList.get(i).getRdDeductible(),TaxParam.class));
            bulkRequest.add(
                    new IndexRequest("demo_test")
                            .source(JSON.toJSONString(libraryEntity), XContentType.JSON)
            );
        }
        BulkResponse bulkResp = client.bulk(bulkRequest, RequestOptions.DEFAULT);
        System.err.println(bulkResp.hasFailures()); // 是否失败,返回false 代表成功。

        Map<String,Object> resMap = new HashMap<>();
        if (false == bulkResp.hasFailures()){
            resMap.put("mes","save to es succ...");
        }else {
            resMap.put("mes","save to es failed...");
        }
        return resMap;
    }

@Override
    public List<LibraryEntity> selName(String name) {
        Map<String,String> map = new HashMap<>();
        map.put("year",name);
        org.springframework.data.elasticsearch.core.SearchHits libraryEntities = libraryEntityMapper.selsss(map);
        System.err.println(JSON.toJSONString(LibraryEntities));
        List<LibraryEntity> re = libraryEntityMapper.findByName("派");
        System.err.println(JSON.toJSONString(re));

        //得到查询返回的内容
        List<org.springframework.data.elasticsearch.core.SearchHit> searchHits = libraryEntities.getSearchHits();
        //设置一个最后需要返回的实体类集合
        List<LibraryEntity> entities = new ArrayList<>();
        //遍历返回的内容进行处理
        for(org.springframework.data.elasticsearch.core.SearchHit searchHit:searchHits){
            System.out.println(JSON.toJSONString(searchHit.getContent()));
            entities.add(JSONObject.parseObject(JSON.toJSONString(
                    searchHit.getContent()), LibraryEntity.class));
            //高亮的内容
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
        }
        return entities;
    }

@Override
    public SearchResponse findByAannualRevenue() throws IOException {

        // 创建BoolQueryBuilder
        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
      
        // 子查询“且”关系
        BoolQueryBuilder childBoolQueryBuilder = new BoolQueryBuilder()
                .must(QueryBuilders.nestedQuery("annualRevenue",
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.matchQuery("annualRevenue.year","2019")), ScoreMode.None)
                );
        BoolQueryBuilder childBoolQueryBuilder2 = new BoolQueryBuilder()
                .must(QueryBuilders.nestedQuery("annualRevenue",
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.matchQuery("annualRevenue.val","73")), ScoreMode.None)
                );
        BoolQueryBuilder childBoolQueryBuilder3 = new BoolQueryBuilder()
                .must(QueryBuilders.nestedQuery("annualRevenue",
                        QueryBuilders.boolQuery()
                                .must(QueryBuilders.rangeQuery("annualRevenue.val").gt(30).lte(90)), ScoreMode.None)
                );
        boolQueryBuilder.must(childBoolQueryBuilder);
        boolQueryBuilder.must(childBoolQueryBuilder2);
        boolQueryBuilder.must(childBoolQueryBuilder3);
        // 创建SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 查询条件生成DSL语句
        searchSourceBuilder.query(boolQueryBuilder);
        // 从多少
        searchSourceBuilder.from(0);
        // 查多少条数据,如果设置“0”返回count数量
        searchSourceBuilder.size(50);
        // 排序规则
        searchSourceBuilder.sort("createTime", SortOrder.DESC);
        // 设置超时
        TimeValue t=new TimeValue(3000);
        searchSourceBuilder.timeout(t);
       
        SearchRequest searchRequest = new SearchRequest("demo_test");
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResp = client.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println("search total:" + searchResp.getHits().getTotalHits().value);

        return searchResp;
    }
}
3.3 Dao
Entity
package com.ghj.demoes.pojo;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.ghj.demoes.form.TaxParam;
import lombok.*;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

/**
 * @program: demo-test
 * @description: 
 * @author: Guanzi
 * @created: 2021/10/18 11:30
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
@Document(indexName = "demo_test")
public class LibraryEntity implements Serializable {

    @TableId(type = IdType.ID_WORKER_STR)
    private String id;
    // 企业名称
    @Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
    private String name;
   
    // 企业地址
    @Field(type = FieldType.Text,analyzer = "douhao",searchAnalyzer = "douhao")
    private String registerAddress;

    // 对应各表的主键id。
    @Field(type = FieldType.Keyword)
    private String uniqueId;
   
    // 年收
    @Field(type = FieldType.Nested)
    private List<TaxParam> annualRevenue;

    // 其他费用
    @Field(type = FieldType.Nested)
    private List<TaxParam> rdDeductible;
}

TaxParam.java
package com.ghj.demoes.form;

import lombok.*;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;

/**
 * @program: demo-test
 * @description: 
 * @author: Guanzi
 * @created: 2021/10/18 11:30
 */
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Data
public class TaxParam {

    @Field(type = FieldType.Keyword)
    private String year;
    // 区域,逗号分词。
    @Field(type = FieldType.Integer)
    private Integer val;


}
Dao
package com.ghj.demoes.dao;

import com.ghj.demoes.pojo.LibraryEntity;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.awt.print.Pageable;
import java.util.List;
import java.util.Map;

@Repository
public interface LibraryEntityMapper extends ElasticsearchRepository<LibraryEntity, String> {

    List<LibraryEntity> findByName(String name);

    List<LibraryEntity> findByRegisterAddress(String address);

    @Query("{\"bool\": {\"must\": [{\"nested\": {\"path\": \"annualRevenue\",\"query\": {\"bool\": {\n" +
            "                \"must\": [{\"match\": {\"annualRevenue.year\": \"?0\"}}],\n" +
            "                \"filter\":{\"script\":{\"script\":{\"source\":\"73 <= doc['annualRevenue.val'].value && doc['annualRevenue.val'].value < 75\"}}}}}}}]}}")
    SearchHits selOne(String year);

    @Query("{\"bool\": {\"must\": [{\"nested\": {\"path\": \"annualRevenue\",\"query\": {\"bool\": {\"must\": \n" +
            "[{\"match\": {\"annualRevenue.year\": \"?0\"}},\n" +
            "{\"range\":{\"annualRevenue.val\":{\"gte\":23,\"lte\":120}}}\n" +
            "]}}}}]}}")
    SearchHits selSecond(String year);

}

3.4 ES结构

{
    "demo_test": {
      "mappings": {
        "basic": {
          "properties":{
            "name":{
              "type": "text",
              "analyzer": "ik_max_word",
              "search_analyzer": "ik_max_word"
            },
            "registerAddress": {
              "type": "text",
              "store": true,
              "analyzer": "ik_max_word",
              "search_analyzer": "ik_max_word"
            },
            "uniqueId": {
              "type": "keyword",
              "store": true
            },
            "annualRevenue": {
              "type": "nested"
            },
            "rdDeductible": {
              "type": "nested"
            }
          }

        }
      }
    }
  }
4.启动项目,可测试。

API-1.png

API-2.png

测试1.png

测试2.png

备注:删除与更新自己写,随便用哪种方式。
over。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值