Springboot2.x集成Elasticsearch实例讲解

女爷i 2022-12-05 10:28 264阅读 0赞

文章目录

    • 一、引用Elasticsearch依赖
    • 二、配置文件修改
    • 三、创建相关类
      • 3.1 主类
      • 3.2 实体类
    • 四、运行
      • 4.1、测试增加接口
      • 4.2、测试获取接口
    • 五、总结

一、引用Elasticsearch依赖

我们用的是Springboot2.2.5.RELEASE版本,下面我们引入了Elasticsearch的依赖。我们用了swagger,因此也加入的swagger的依赖。

  1. <dependency>
  2. <groupId>io.springfox</groupId>
  3. <artifactId>springfox-swagger2</artifactId>
  4. <version>2.9.2</version>
  5. </dependency>
  6. <dependency>
  7. <groupId>io.springfox</groupId>
  8. <artifactId>springfox-swagger-ui</artifactId>
  9. <version>2.9.2</version>
  10. </dependency>
  11. <dependency>
  12. <groupId>org.springframework.boot</groupId>
  13. <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  14. </dependency>

二、配置文件修改

application.yml增加elasticsearch的地址及开启swagger配置

  1. spring:
  2. elasticsearch:
  3. rest:
  4. uris: http://192.168.22.2:9200
  5. swagger:
  6. enabled: true
  7. jwt:
  8. header: Authorization

三、创建相关类

3.1 主类

  1. package com.test.es.estest;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. @SpringBootApplication
  5. public class EstestApplication {
  6. public static void main(String[] args) {
  7. SpringApplication.run(EstestApplication.class, args);
  8. }
  9. }

3.2 实体类

  1. package com.test.es.estest.entity;
  2. import lombok.Data;
  3. import lombok.NoArgsConstructor;
  4. import lombok.experimental.Accessors;
  5. import org.springframework.data.annotation.Id;
  6. import org.springframework.data.elasticsearch.annotations.Document;
  7. import org.springframework.data.elasticsearch.annotations.Field;
  8. import org.springframework.data.elasticsearch.annotations.FieldType;
  9. @Data
  10. @NoArgsConstructor
  11. @Accessors(chain = true)
  12. @Document(indexName = "ems",type = "_doc", shards = 1, replicas = 0)
  13. public class DocBean {
  14. @Id
  15. private Long id;
  16. @Field(type = FieldType.Keyword)
  17. private String firstCode;
  18. @Field(type = FieldType.Keyword)
  19. private String secordCode;
  20. @Field(type = FieldType.Text, analyzer = "ik_max_word")
  21. private String content;
  22. @Field(type = FieldType.Integer)
  23. private Integer type;
  24. public DocBean(Long id,String firstCode,String secordCode,String content,Integer type){
  25. this.id=id;
  26. this.firstCode=firstCode;
  27. this.secordCode=secordCode;
  28. this.content=content;
  29. this.type=type;
  30. }
  31. }

indexName = “ems”,type = “_doc” :设置索引名称及类型。

  • 前端返回数据结构:

    package com.test.es.estest.entity;

    /**

    Title: PersonService

    • Description: 通用Rest请求返回结构


      *
    • @author bingge
    • @date 2020-2-20 下午7:15:30
    • @version V1.0
      */
      public class Result {
      //服务器返回的状态码(主要给程序员看)。例如 : 200 : 请求成功, 500 : 服务器内部错误,400 : 未知错误
      private Integer code;

      //返回码 1:成功 10000:系统错误 10001:参数错误 …
      private Integer status;

      // 服务器的错误信息 ,主要返回给用户看
      private String msg;

      // 服务器返回的数据
      private Object data;

      public Result() {
      }

      //返回操作成功
      public static Result ok() {

      1. return ok(null);

      }

      //返回操作成功
      public static Result ok(Object data) {

      1. Result result = new Result();
      2. result.setCode(200);
      3. result.setStatus(1);
      4. result.setMsg("请求成功");
      5. result.setData(data);
      6. return result;

      }

      //返回操作成功
      public static Result error() {

      1. return error("请求失败");

      }

      //返回操作成功
      public static Result error(Integer code, Integer status, String msg) {

      1. Result result = new Result();
      2. result.setCode(code);
      3. result.setStatus(status);
      4. result.setMsg(msg);
      5. return result;

      }

      //返回操作成功
      public static Result error(String msg) {

      1. return error(500,0, msg);

      }

      //返回操作成功
      public static Result error(ErrorStatus errorStatus) {

      1. return error(500,errorStatus.value(), errorStatus.getMessage());

      }

      public Integer getCode() {

      1. return code;

      }

      public void setCode(Integer code) {

      1. this.code = code;

      }

      public Integer getStatus() {

      1. return status;

      }

      public void setStatus(Integer status) {

      1. this.status = status;

      }

      public String getMsg() {

      1. return msg;

      }

      public void setMsg(String msg) {

      1. this.msg = msg;

      }

      public Object getData() {

      1. return data;

      }

      public void setData(Object data) {

      1. this.data = data;

      }
      }

  • Swagger配置类:

    package com.test.es.estest.config;

    import com.google.common.base.Predicates;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Parameter;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;

    import java.util.ArrayList;
    import java.util.List;

    /**

    • api页面 /swagger-ui.html
      *
    • @author jie
    • @date 2018-11-23
      */

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {

    1. @Value("${jwt.header}")
    2. private String tokenHeader;
    3. @Value("${swagger.enabled}")
    4. private Boolean enabled;
    5. @Bean
    6. public Docket createRestApi() {
    7. ParameterBuilder ticketPar = new ParameterBuilder();
    8. List<Parameter> pars = new ArrayList<Parameter>();
    9. ticketPar.name(tokenHeader).description("token")
    10. .modelRef(new ModelRef("string"))
    11. .parameterType("header")
    12. .defaultValue("Bearer ")
    13. .required(true)
    14. .build();
    15. pars.add(ticketPar.build());
    16. System.out.println("----------SwaggerConfig end------------");
    17. return new Docket(DocumentationType.SWAGGER_2)
    18. .enable(enabled)
    19. .apiInfo(apiInfo())
    20. .select()
    21. .paths(Predicates.not(PathSelectors.regex("/error.*")))
    22. .build()
    23. .globalOperationParameters(pars);
    24. }
    25. private ApiInfo apiInfo() {
    26. return new ApiInfoBuilder()
    27. .title("平台-接口文档")
    28. .version("1.0")
    29. .build();
    30. }

    }

  1. package com.test.es.estest.config;
  2. import com.fasterxml.classmate.TypeResolver;
  3. import io.swagger.annotations.ApiModel;
  4. import io.swagger.annotations.ApiModelProperty;
  5. import org.springframework.context.annotation.Bean;
  6. import org.springframework.context.annotation.Configuration;
  7. import org.springframework.core.Ordered;
  8. import springfox.documentation.schema.AlternateTypeRule;
  9. import springfox.documentation.schema.AlternateTypeRuleConvention;
  10. import java.awt.print.Pageable;
  11. import java.util.List;
  12. import static com.google.common.collect.Lists.newArrayList;
  13. import static springfox.documentation.schema.AlternateTypeRules.newRule;
  14. /**
  15. * 将Pageable转换展示在swagger中
  16. */
  17. @Configuration
  18. public class SwaggerDataConfig {
  19. @Bean
  20. public AlternateTypeRuleConvention pageableConvention(final TypeResolver resolver) {
  21. return new AlternateTypeRuleConvention() {
  22. @Override
  23. public int getOrder() {
  24. return Ordered.HIGHEST_PRECEDENCE;
  25. }
  26. @Override
  27. public List<AlternateTypeRule> rules() {
  28. return newArrayList(newRule(resolver.resolve(Pageable.class), resolver.resolve(Page.class)));
  29. }
  30. };
  31. }
  32. @ApiModel
  33. static class Page {
  34. @ApiModelProperty("页码 (0..N)")
  35. private Integer page;
  36. @ApiModelProperty("每页显示的数目")
  37. private Integer size;
  38. @ApiModelProperty("以下列格式排序标准:property[,asc | desc]。 默认排序顺序为升序。 支持多种排序条件:如:id,asc")
  39. private List<String> sort;
  40. public Integer getPage() {
  41. return page;
  42. }
  43. public void setPage(Integer page) {
  44. this.page = page;
  45. }
  46. public Integer getSize() {
  47. return size;
  48. }
  49. public void setSize(Integer size) {
  50. this.size = size;
  51. }
  52. public List<String> getSort() {
  53. return sort;
  54. }
  55. public void setSort(List<String> sort) {
  56. this.sort = sort;
  57. }
  58. }
  59. }
  • dac层接口类:

    package com.test.es.estest.dao;

    import com.test.es.estest.entity.DocBean;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.elasticsearch.annotations.Query;
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    public interface ElasticRepository extends ElasticsearchRepository {

    1. //默认的注释
    2. //@Query("{\"bool\" : {\"must\" : {\"field\" : {\"content\" : \"?\"}}}}")
    3. Page<DocBean> findByContent(String content, Pageable pageable);
    4. @Query("{\"bool\" : {\"must\" : {\"field\" : {\"firstCode.keyword\" : \"?\"}}}}")
    5. Page<DocBean> findByFirstCode(String firstCode, Pageable pageable);
    6. @Query("{\"bool\" : {\"must\" : {\"field\" : {\"secordCode.keyword\" : \"?\"}}}}")
    7. Page<DocBean> findBySecordCode(String secordCode, Pageable pageable);
  1. }
  • service层接口类及实现类:

    package com.test.es.estest.service;

    import com.test.es.estest.dao.ElasticRepository;
    import com.test.es.estest.entity.DocBean;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.data.domain.Page;
    import org.springframework.data.domain.PageRequest;
    import org.springframework.data.domain.Pageable;
    import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
    import org.springframework.stereotype.Service;
    import java.util.Iterator;
    import java.util.List;

    @Service(“elasticService”)
    public class ElasticServiceImpl implements IElasticService {

    1. @Autowired
    2. private ElasticsearchRestTemplate elasticsearchTemplate;
    3. @Autowired
    4. private ElasticRepository elasticRepository;
    5. private Pageable pageable = PageRequest.of(0,10);
    6. @Override
    7. public void createIndex() {
    8. elasticsearchTemplate.createIndex(DocBean.class);
    9. }
    10. @Override
    11. public void deleteIndex(String index) {
    12. elasticsearchTemplate.deleteIndex(index);
    13. }
    14. @Override
    15. public void save(DocBean docBean) {
    16. elasticRepository.save(docBean);
    17. }
    18. @Override
    19. public void saveAll(List<DocBean> list) {
    20. elasticRepository.saveAll(list);
    21. }
    22. @Override
    23. public Iterator<DocBean> findAll() {
    24. return elasticRepository.findAll().iterator();
    25. }
    26. @Override
    27. public Page<DocBean> findByContent(String content) {
    28. return elasticRepository.findByContent(content,pageable);
    29. }
    30. @Override
    31. public Page<DocBean> findByFirstCode(String firstCode) {
    32. return elasticRepository.findByFirstCode(firstCode,pageable);
    33. }
    34. @Override
    35. public Page<DocBean> findBySecordCode(String secordCode) {
    36. return elasticRepository.findBySecordCode(secordCode,pageable);
    37. }
    38. @Override
    39. public Page<DocBean> query(String key) {
    40. return elasticRepository.findByContent(key,pageable);
    41. }

    }

  1. package com.test.es.estest.service;
  2. import com.test.es.estest.entity.DocBean;
  3. import org.springframework.data.domain.Page;
  4. import java.util.Iterator;
  5. import java.util.List;
  6. public interface IElasticService {
  7. void createIndex();
  8. void deleteIndex(String index);
  9. void save(DocBean docBean);
  10. void saveAll(List<DocBean> list);
  11. Iterator<DocBean> findAll();
  12. Page<DocBean> findByContent(String content);
  13. Page<DocBean> findByFirstCode(String firstCode);
  14. Page<DocBean> findBySecordCode(String secordCode);
  15. Page<DocBean> query(String key);
  16. }
  • Controller类:

    package com.test.es.estest.controller;

    import com.test.es.estest.dao.ElasticRepository;
    import com.test.es.estest.entity.DocBean;
    import com.test.es.estest.entity.Result;
    import com.test.es.estest.service.IElasticService;
    import io.swagger.annotations.;
    import lombok.extern.slf4j.Slf4j;
    import org.elasticsearch.index.query.BoolQueryBuilder;
    import org.elasticsearch.index.query.QueryBuilders;
    import org.elasticsearch.index.query.RangeQueryBuilder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    import java.util.
    ;

    /**

    Title: TestController2

    • Description: 测试Memcache


      *
    • @author binge
    • @date 2020-2-20 下午7:15:30
    • @version V1.0
      */
      @RestController
      @Slf4j
      @Api(tags=”elasticsearch性能测试”)
      public class TestController {
      @Autowired
      private IElasticService elasticService;
      @Autowired
      private ElasticRepository elasticRepository;
      @RequestMapping(“/put”)
      @ApiOperation(value=”批量数据插入es数据库”,notes=”批量数据插入es数据库”)
      @ApiImplicitParams({

      1. @ApiImplicitParam(name = "index", value = "索引", required = true, dataType = "String", paramType="query"),
      2. @ApiImplicitParam(name = "type", value = "类型", required = true, dataType = "String", paramType="query"),
      3. @ApiImplicitParam(name = "ids", value = "id开始序号", required = true, dataType = "Long", paramType="query"),
      4. @ApiImplicitParam(name = "ide", value = "id结束序号", required = true, dataType = "Long", paramType="query")

      })
      public Result putEsdata(String index,String type, Long ids, Long ide) throws InterruptedException {

      1. elasticService.createIndex();
      2. List<DocBean> list =new ArrayList<>();
      3. for (Long i=ids; i<ide; ++i){
      4. list.add(new DocBean(i,"XX3713"+i,"XX01"+i,"xxxxxx"+i,1));
      5. }
      6. elasticService.saveAll(list);
      7. return Result.ok();

      }

      @RequestMapping(“/get”)
      @ApiOperation(value=”根据id范围获取数据”,notes=”根据id范围获取数据”)
      @ApiImplicitParams({

      1. @ApiImplicitParam(name = "s", value = "起始ID", required = true, dataType = "Int", paramType="query"),
      2. @ApiImplicitParam(name = "e", value = "终止ID", required = true, dataType = "Int", paramType="query")

      })
      public Result getEsdata(int s, int e) throws InterruptedException {

      1. /**
      2. * 创建查询体
      3. */
      4. BoolQueryBuilder builder = QueryBuilders.boolQuery();
      5. /**
      6. * 设置聚合条件
      7. */
      8. RangeQueryBuilder query = QueryBuilders.rangeQuery("id").from(s).to(e);
      9. /**
      10. * 将聚合条件设置入查询体之中
      11. */
      12. builder.must(query);
      13. Iterable<DocBean> data = elasticRepository.search(builder);
      14. return Result.ok(data);

      }
      }

四、运行

运行后,访问:http://localhost:8080/swagger-ui.html

4.1、测试增加接口

在这里插入图片描述

执行后,大概1s左右,写入10000条数据。

4.2、测试获取接口

在这里插入图片描述
执行后的结果截图如下:
在这里插入图片描述

Response body中的内容即为查询结果。

五、总结

初步进行了Elasticsearch和Springboot2.x及集成操作,对Elasticsearch的复合查询没有过多介绍,后续会有专门章节进行详解。

发表评论

表情:
评论列表 (有 0 条评论,264人围观)

还没有评论,来说两句吧...

相关阅读