1、创建spring boot项目
2、在pom中添加引用:
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.5.6</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.yas</groupId> <artifactId>ESSpringData</artifactId> <version>0.0.1-SNAPSHOT</version> <name>ESSpringData</name> <description>Demo project for Spring Boot</description> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> <configuration> <excludes> <exclude> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </exclude> </excludes> </configuration> </plugin> </plugins> </build> </project>
3、配置文件:
# es 服务地址 elasticsearch.host=127.0.0.1 # es 服务端口 elasticsearch.port=9200 # 配置日志级别,开启 debug 日志 logging.level.com.atguigu.es=debug
4、实体类:
1 package com.yas.esspringdata.model; 2 3 import lombok.AllArgsConstructor; 4 import lombok.Data; 5 import lombok.NoArgsConstructor; 6 import lombok.ToString; 7 import org.springframework.data.annotation.Id; 8 import org.springframework.data.elasticsearch.annotations.Document; 9 import org.springframework.data.elasticsearch.annotations.Field; 10 import org.springframework.data.elasticsearch.annotations.FieldType; 11 12 @Data 13 @NoArgsConstructor 14 @AllArgsConstructor 15 @ToString 16 @Document(indexName = "product", shards = 3, replicas = 1) 17 public class Product { 18 //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id" 19 @Id 20 private Long id;//商品唯一标识 21 /** 22 * type : 字段数据类型 23 * analyzer : 分词器类型 24 * index : 是否索引(默认:true) 25 * Keyword : 短语,不进行分词 26 */ 27 @Field(type = FieldType.Text, analyzer = "ik_max_word") 28 private String title;//商品名称 29 @Field(type = FieldType.Keyword) 30 private String category;//分类名称 31 @Field(type = FieldType.Double) 32 private Double price;//商品价格 33 @Field(type = FieldType.Keyword, index = false) 34 private String images;//图片地址 35 }
5、配置类:
1 package com.yas.esspringdata.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 @ConfigurationProperties(prefix = "elasticsearch") 12 @Configuration 13 @Data 14 public class ElasticsearchConfig extends AbstractElasticsearchConfiguration { 15 private String host ; 16 private Integer port ; 17 //重写父类方法 18 @Override 19 public RestHighLevelClient elasticsearchClient() { 20 RestClientBuilder builder = RestClient.builder(new HttpHost(host, port)); 21 RestHighLevelClient restHighLevelClient = new 22 RestHighLevelClient(builder); 23 return restHighLevelClient; 24 } 25 }
6、DAO类:
1 package com.yas.esspringdata.dao; 2 import com.yas.esspringdata.model.Product; 3 import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 4 import org.springframework.stereotype.Repository; 5 6 import java.util.List; 7 8 @Repository 9 public interface ProductDao extends ElasticsearchRepository<Product,Long> { 10 11 //根据规则编写方法签名 12 List<Product> findProductByTitleContains(String title); 13 14 //根据规则编写方法签名 15 List<Product> findByTitleAndCategory(String title, String category); 16 }
7、测试:
1 package com.yas.esspringdata; 2 3 import com.yas.esspringdata.dao.ProductDao; 4 import com.yas.esspringdata.model.Product; 5 import org.elasticsearch.index.query.QueryBuilders; 6 import org.elasticsearch.index.query.TermQueryBuilder; 7 import org.junit.jupiter.api.Test; 8 import org.springframework.boot.test.context.SpringBootTest; 9 import org.springframework.beans.factory.annotation.Autowired; 10 import org.springframework.data.domain.Page; 11 import org.springframework.data.domain.PageRequest; 12 import org.springframework.data.domain.Sort; 13 import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; 14 15 import java.util.ArrayList; 16 import java.util.List; 17 18 @SpringBootTest 19 class EsSpringDataApplicationTests { 20 21 //注入 ElasticsearchRestTemplate 22 @Autowired 23 private ElasticsearchRestTemplate elasticsearchRestTemplate; 24 25 //创建索引并增加映射配置 26 @Test 27 public void createIndex() { 28 //创建索引,系统初始化会自动创建索引 29 //elasticsearchRestTemplate.indexOps(Product.class).create(); 30 System.out.println("创建索引"); 31 } 32 33 @Autowired 34 private ProductDao productDao; 35 36 /** 37 * 新增 38 */ 39 @Test 40 public void save() { 41 Product product = new Product(); 42 product.setId(2L); 43 product.setTitle("华为手机"); 44 product.setCategory("手机"); 45 product.setPrice(2999.0); 46 product.setImages("http://www.atguigu/hw.jpg"); 47 productDao.save(product); 48 } 49 50 //新增或修改 51 @Test 52 public void update() { 53 Product product = new Product(); 54 product.setId(1L); 55 product.setTitle("小米 2 手机"); 56 product.setCategory("手机"); 57 product.setPrice(9999.0); 58 product.setImages("http://www.atguigu/xm.jpg"); 59 productDao.save(product); 60 } 61 62 //根据 id 查询 63 @Test 64 public void findById() { 65 Product product = productDao.findById(1L).get(); 66 System.out.println(product); 67 } 68 69 //查询所有 70 @Test 71 public void findAll() { 72 Iterable<Product> products = productDao.findAll(); 73 for (Product product : products) { 74 System.out.println(product); 75 } 76 } 77 78 //删除 79 @Test 80 public void delete() { 81 Product product = new Product(); 82 product.setId(1L); 83 productDao.delete(product); 84 } 85 86 //批量新增 87 @Test 88 public void saveAll() { 89 List<Product> productList = new ArrayList<>(); 90 for (int i = 0; i < 10; i++) { 91 Product product = new Product(); 92 product.setId(Long.valueOf(i)); 93 product.setTitle("[" + i + "]小米手机"); 94 product.setCategory("手机"); 95 product.setPrice(1999.0 + i); 96 product.setImages("http://www.atguigu/xm.jpg"); 97 productList.add(product); 98 } 99 productDao.saveAll(productList); 100 } 101 102 //分页查询 103 @Test 104 public void findByPageable() { 105 //设置排序(排序方式,正序还是倒序,排序的 id) 106 Sort sort = Sort.by(Sort.Direction.DESC, "id"); 107 int currentPage = 0;//当前页,第一页从 0 开始,1 表示第二页 108 int pageSize = 5;//每页显示多少条 109 //设置查询分页 110 PageRequest pageRequest = PageRequest.of(currentPage, pageSize, sort); 111 //分页查询 112 Page<Product> productPage = productDao.findAll(pageRequest); 113 for (Product Product : productPage.getContent()) { 114 System.out.println(Product); 115 } 116 } 117 118 /** 119 * term 查询 120 * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象 121 */ 122 @Test 123 public void termTitleAndCategory() { 124 final List<Product> products = productDao.findByTitleAndCategory("小米", "电视"); 125 for(Product p : products){ 126 System.out.println(p); 127 } 128 } 129 130 @Test 131 public void termTitle(){ 132 final List<Product> products = productDao.findProductByTitleContains("5"); 133 for(Product p : products){ 134 System.out.println(p); 135 } 136 } 137 }