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

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。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 160,277评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,777评论 1 298
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,946评论 0 245
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,271评论 0 213
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,636评论 3 288
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,767评论 1 221
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,989评论 2 315
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,733评论 0 204
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,457评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,674评论 2 249
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,155评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,518评论 3 258
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,160评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,114评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,898评论 0 198
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,822评论 2 280
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,705评论 2 273

推荐阅读更多精彩内容