springboot 集成elasticsearch7.6.1,實現(xiàn)2種增刪改查方式

1、創(chuàng)建project

project.png
module1.png

module2.png
設置jdk.png
配置javac.png
pom.xml.png
一定要保證依賴與es版本一致
依賴與es.png
配置ElasticSearchConfig
ElasticSearchConfig.png
至此,springboot集成es7.6.1項目基本搭建完成。(創(chuàng)建項目時忘記截圖,部分圖片可能對不上。)

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;
    
    /**
     * 數(shù)據(jù)庫數(shù)據(jù)批量導入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());
    }

    /**
     * 根據(jù)名字查詢es庫數(shù)據(jù)。
     */
    @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類型數(shù)據(jù)查詢。
     */
    @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 {

        // 創(chuàng)建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);
        // 創(chuàng)建SearchSourceBuilder
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 查詢條件生成DSL語句
        searchSourceBuilder.query(boolQueryBuilder);
        // 從多少
        searchSourceBuilder.from(0);
        // 查多少條數(shù)據(jù),如果設置“0”返回count數(shù)量
        searchSourceBuilder.size(50);
        // 排序規(guī)則
        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;
    // 企業(yè)名稱
    @Field(type = FieldType.Text,analyzer = "ik_max_word",searchAnalyzer = "ik_max_word")
    private String name;
   
    // 企業(yè)地址
    @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。
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容