• ELK SpringData框架 Springboot集成elasticSearch (六)


    目录

    一、SpringData框架基本介绍

    二、集成案例

    1、引入依赖

    2、添加配置

    3、对应的实体类和操作

    4、添加单元测试

    5、文档操作

    6、文档的各种查询


    一、SpringData框架基本介绍

    二、集成案例

    1、引入依赖

    1. "1.0" encoding="UTF-8"?>
    2. <project xmlns="http://maven.apache.org/POM/4.0.0"
    3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    4. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    5. <modelVersion>4.0.0modelVersion>
    6. <parent>
    7. <groupId>org.springframework.bootgroupId>
    8. <version>2.3.2.RELEASEversion>
    9. <artifactId>spring-boot-starter-parentartifactId>
    10. <relativePath/>
    11. parent>
    12. <groupId>com.dragonwugroupId>
    13. <artifactId>ES-springartifactId>
    14. <version>1.0-SNAPSHOTversion>
    15. <properties>
    16. <maven.compiler.source>8maven.compiler.source>
    17. <maven.compiler.target>8maven.compiler.target>
    18. properties>
    19. <dependencies>
    20. <dependency>
    21. <groupId>org.projectlombokgroupId>
    22. <artifactId>lombokartifactId>
    23. dependency>
    24. <dependency>
    25. <groupId>org.springframework.bootgroupId>
    26. <artifactId>spring-boot-starter-data-elasticsearchartifactId>
    27. dependency>
    28. <dependency>
    29. <groupId>org.springframework.bootgroupId>
    30. <artifactId>spring-boot-devtoolsartifactId>
    31. <scope>runtimescope>
    32. <optional>trueoptional>
    33. dependency>
    34. <dependency>
    35. <groupId>org.springframework.bootgroupId>
    36. <artifactId>spring-boot-starter-testartifactId>
    37. <scope>testscope>
    38. dependency>
    39. <dependency>
    40. <groupId>org.springframework.bootgroupId>
    41. <artifactId>spring-boot-testartifactId>
    42. dependency>
    43. <dependency>
    44. <groupId>junitgroupId>
    45. <artifactId>junitartifactId>
    46. dependency>
    47. <dependency>
    48. <groupId>org.springframeworkgroupId>
    49. <artifactId>spring-testartifactId>
    50. dependency>
    51. dependencies>
    52. project>

    2、添加配置

    yam配置:

    1. elasticsearch:
    2. #es服务地址
    3. host: 127.0.0.1
    4. #es服务端口
    5. port: 9200
    6. #配置日志级别,开启debug日志
    7. logging:
    8. level:
    9. com:
    10. dragonwu:
    11. es: debug

    配置类:

    1. package com.dragonwu.es.config;
    2. import lombok.Data;
    3. import org.apache.http.HttpHost;
    4. import org.elasticsearch.client.RestClient;
    5. import org.elasticsearch.client.RestClientBuilder;
    6. import org.elasticsearch.client.RestHighLevelClient;
    7. import org.springframework.boot.context.properties.ConfigurationProperties;
    8. import org.springframework.context.annotation.Configuration;
    9. import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
    10. /**
    11. * @author DragonWu
    12. * @date 2022-09-18 15:52
    13. **/
    14. @ConfigurationProperties(prefix = "elasticsearch")
    15. @Configuration
    16. @Data
    17. public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
    18. private String host;
    19. private Integer port;
    20. @Override
    21. public RestHighLevelClient elasticsearchClient() {
    22. RestClientBuilder builder= RestClient.builder(new HttpHost(host,port));
    23. return new RestHighLevelClient(builder);
    24. }
    25. }

    3、对应的实体类和操作

    实体类:

    1. package com.dragonwu.es.domain;
    2. import lombok.AllArgsConstructor;
    3. import lombok.Data;
    4. import lombok.NoArgsConstructor;
    5. import lombok.ToString;
    6. import org.springframework.data.annotation.Id;
    7. import org.springframework.data.elasticsearch.annotations.Document;
    8. import org.springframework.data.elasticsearch.annotations.Field;
    9. import org.springframework.data.elasticsearch.annotations.FieldType;
    10. /**
    11. * @author DragonWu
    12. * @date 2022-09-18 15:45
    13. **/
    14. @Data
    15. @NoArgsConstructor
    16. @AllArgsConstructor
    17. @ToString
    18. @Document(indexName = "product",shards = 3,replicas = 1)
    19. public class Product {
    20. @Id
    21. private Long id;//商品唯一标识
    22. @Field(type= FieldType.Text)
    23. private String title;//商品名称
    24. @Field(type=FieldType.Keyword)
    25. private String catalog;//商品类别
    26. @Field(type=FieldType.Double)
    27. private Double price;//商品价格
    28. //keyword表示该字段不能被拆分,index=false表示该字段不能被当主键查询
    29. @Field(type = FieldType.Keyword,index = false)
    30. private String image;//图片地址
    31. }

    数据操作层:

    1. package com.dragonwu.es.mapper;
    2. import com.dragonwu.es.domain.Product;
    3. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    4. import org.springframework.stereotype.Repository;
    5. /**
    6. * @author DragonWu
    7. * @date 2022-09-18 16:03
    8. **/
    9. @Repository
    10. public interface ProductDao extends ElasticsearchRepository {
    11. }

    4、添加单元测试

    1. package com.dragonwu.es;
    2. import com.dragonwu.es.domain.Product;
    3. import org.junit.Test;
    4. import org.junit.runner.RunWith;
    5. import org.springframework.beans.factory.annotation.Autowired;
    6. import org.springframework.boot.test.context.SpringBootTest;
    7. import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
    8. import org.springframework.test.context.junit4.SpringRunner;
    9. /**
    10. * @author DragonWu
    11. * @date 2022-09-18 16:10
    12. **/
    13. @RunWith(SpringRunner.class)
    14. @SpringBootTest
    15. public class ElasticSearchSpringbootTest {
    16. @Autowired
    17. private ElasticsearchRestTemplate elasticsearchRestTemplate;
    18. @Test
    19. public void createIndex(){
    20. //创建索引,系统初始化会自动创建索引
    21. System.out.println("创建索引");
    22. }
    23. @Test
    24. public void deleteIndex(){
    25. boolean flg=elasticsearchRestTemplate.deleteIndex(Product.class);
    26. System.out.println("删除索引="+flg);
    27. }
    28. }

    目录结构:

    运行索引创建的单元测试:

     

     再次通过ApiPost查看索引

     可以看到product索引已创建。

    再运行删除的单元测试:

    查看索引 

     此时可以看到对应的product索引已经被删除了。

    5、文档操作

    上面我们对索引进行了操作,下面对文档进行操作。

    1. package com.dragonwu.es;
    2. import com.dragonwu.es.domain.Product;
    3. import com.dragonwu.es.mapper.ProductDao;
    4. import org.junit.Test;
    5. import org.junit.runner.RunWith;
    6. import org.springframework.beans.factory.annotation.Autowired;
    7. import org.springframework.boot.test.context.SpringBootTest;
    8. import org.springframework.data.domain.Page;
    9. import org.springframework.data.domain.PageRequest;
    10. import org.springframework.data.domain.Sort;
    11. import org.springframework.test.context.junit4.SpringRunner;
    12. import java.util.ArrayList;
    13. import java.util.List;
    14. /**
    15. * @author DragonWu
    16. * @date 2022-09-18 16:32
    17. **/
    18. @SpringBootTest
    19. @RunWith(SpringRunner.class)
    20. public class ElasticSearchDaoTest {
    21. @Autowired
    22. private ProductDao productDao;
    23. /*
    24. * 新增
    25. */
    26. @Test
    27. public void save(){
    28. Product product=new Product();
    29. product.setId(2L);
    30. product.setTitle("华为手机");
    31. product.setCatalog("手机");
    32. product.setPrice(2999.0);
    33. product.setImage("/upload/file/test.jpg");
    34. productDao.save(product);
    35. }
    36. @Test
    37. public void findById(){
    38. Product product=productDao.findById(2L).get();
    39. System.out.println(product);
    40. }
    41. //查询所有
    42. @Test
    43. public void findAll(){
    44. Iterable products=productDao.findAll();
    45. for(Product product:products){
    46. System.out.println(product);
    47. }
    48. }
    49. //删除
    50. @Test
    51. public void delete(){
    52. Product product=new Product();
    53. product.setId(2L);
    54. productDao.delete(product);
    55. }
    56. //批量新增
    57. @Test
    58. public void saveAll(){
    59. List productList=new ArrayList<>();
    60. for(int i=0;i<10;i++){
    61. Product product=new Product();
    62. product.setId((long) i);
    63. product.setTitle("["+i+"]小米手机");
    64. product.setCatalog("手机");
    65. product.setPrice(1999.0+i);
    66. product.setImage("/upload/file/img.jpg");
    67. productList.add(product);
    68. }
    69. productDao.saveAll(productList);
    70. }
    71. @Test
    72. public void findByPageable(){
    73. //设置排序
    74. Sort sort = Sort.by(Sort.Direction.DESC, "id");
    75. int from=0;//当前页
    76. int size=5;//每页显示多少条
    77. //设置查询分页
    78. PageRequest pageRequest=PageRequest.of(from,size,sort);
    79. //分页查询
    80. Page productPage=productDao.findAll(pageRequest);
    81. for(Product product:productPage.getContent()){
    82. System.out.println(product);
    83. }
    84. }
    85. }

    添加文档的单元测试

    更新同样使用save方法,只要id相同即代表更新;其他单元测试都已放到代码了,直接测试即可。

    6、文档的各种查询

    1. package com.dragonwu.es;
    2. import com.dragonwu.es.domain.Product;
    3. import com.dragonwu.es.mapper.ProductDao;
    4. import org.elasticsearch.index.query.QueryBuilders;
    5. import org.elasticsearch.index.query.TermQueryBuilder;
    6. import org.junit.Test;
    7. import org.junit.runner.RunWith;
    8. import org.springframework.beans.factory.annotation.Autowired;
    9. import org.springframework.boot.test.context.SpringBootTest;
    10. import org.springframework.data.domain.PageRequest;
    11. import org.springframework.test.context.junit4.SpringRunner;
    12. /**
    13. * @author DragonWu
    14. * @date 2022-09-18 17:54
    15. **/
    16. @SpringBootTest
    17. @RunWith(SpringRunner.class)
    18. public class ElasticSearchDocSearchTest {
    19. @Autowired
    20. private ProductDao productDao;
    21. /**
    22. * term 查询
    23. * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象
    24. */
    25. @Test
    26. public void termQuery(){
    27. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "华为手机");
    28. Iterable products = productDao.search(termQueryBuilder);
    29. for (Product product : products) {
    30. System.out.println(product);
    31. }
    32. }
    33. /**
    34. * term 查询加分页
    35. */
    36. @Test
    37. public void termQueryByPage(){
    38. int currentPage= 0 ;
    39. int pageSize = 5;
    40. //设置查询分页
    41. PageRequest pageRequest = PageRequest.of(currentPage, pageSize);
    42. TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "华为手机");
    43. Iterable products =
    44. productDao.search(termQueryBuilder,pageRequest);
    45. for (Product product : products) {
    46. System.out.println(product);
    47. }
    48. }
    49. }

    集成到此。

  • 相关阅读:
    入坑机器学习:五,多变量线性回归
    Solidity智能合约开发 — 3.5-库合约
    【学习教程】MCM箱模型建模方法及大气O3来源解析实践技术应用
    微分方程和线性代数(分离变量法开始)
    CAPL学习之路-诊断函数
    华为OD机试 - 矩形相交的面积 - 逻辑分析(Java 2023 B卷 100分)
    从一个APP启动另一个APP的activity的方式
    【电路笔记】-快速了解无源器件
    java毕业生设计宠物店管理系统计算机源码+系统+mysql+调试部署+lw
    【计算机毕业设计】java ssm网上宠物商店系统
  • 原文地址:https://blog.csdn.net/qq_50909707/article/details/126917222