【ElasticSearch】04 Spring-Data-ElasticSearch
官方网站: https://spring.io/projects/spring-data-elasticsearch
对应 Elasticsearch7.6.2,Spring boot2.3.x 一般可以兼容 Elasticsearch7.x
一、环境搭建
SpringBoot工程依赖坐标:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | <? 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 http://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.3.6.RELEASE</ version > < relativePath /> </ parent > < groupId >cn.cloud9</ groupId > < artifactId >Spring-Data-ElasticSearch</ artifactId > < version >1.0-SNAPSHOT</ version > < properties > < maven.compiler.source >8</ maven.compiler.source > < maven.compiler.target >8</ maven.compiler.target > </ properties > < dependencies > < dependency > < groupId >org.projectlombok</ groupId > < artifactId >lombok</ artifactId > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-starter-data-elasticsearch</ 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-starter-test</ artifactId > < scope >test</ scope > </ dependency > < dependency > < groupId >org.springframework.boot</ groupId > < artifactId >spring-boot-test</ artifactId > </ dependency > < dependency > < groupId >junit</ groupId > < artifactId >junit</ artifactId > </ dependency > < dependency > < groupId >org.springframework</ groupId > < artifactId >spring-test</ artifactId > </ dependency > </ dependencies > </ project > |
application.properties配置文件,追加ES的连接地址
1 2 3 4 5 6 | # es 服务地址 elasticsearch.host= 127.0 . 0.1 # es 服务端口 elasticsearch.port= 9200 # 配置日志级别,开启 debug 日志 logging.level.com.atguigu.es=debug |
启动类代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | package cn.cloud9; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; /** * @projectName: SpringDataElasticSearch * @author: cloud9 * @date: 2022年09月06日 09:31 * @version: 1.0 */ @SpringBootApplication public class SpringDataEsApplication { public static void main(String[] args) { SpringApplication.run(SpringDataEsApplication. class , args); } } |
文档PO类代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | package cn.cloud9.po; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; /** * @projectName: SpringDataElasticSearch * @author: Cloud9 * @date: 2022年09月06日 09:33 * @version: 1.0 */ @Data @AllArgsConstructor @NoArgsConstructor @ToString @Document (indexName = "shopping" , shards = 3 , replicas = 1 ) public class Product { //必须有 id,这里的 id 是全局唯一的标识,等同于 es 中的"_id" @Id private Long id; //商品唯一标识 @Field (type = FieldType.Text, analyzer = "ik_max_word" ) private String title; //商品名称 @Field (type = FieldType.Keyword) private String category; //分类名称 @Field (type = FieldType.Double) private Double price; //商品价格 @Field (type = FieldType.Keyword, index = false ) private String images; //图片地址 } |
DAO接口继承SpringData的EsRepository接口
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package cn.cloud9.dao; import cn.cloud9.po.Product; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; /** * @projectName: SpringDataElasticSearch * @author: Cloud9 * @date: 2022年09月06日 09:37 * @version: 1.0 */ @Repository public interface ProductDAO extends ElasticsearchRepository<Product, Long> { } |
二、测试操作:
默认读取文档PO类加载到ES中,如果没有索引将默认创建
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | package cn.cloud9; import cn.cloud9.po.Product; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.test.context.junit4.SpringRunner; /** * @projectName: SpringDataElasticSearch * @author: cloud9 * @date: 2022年09月06日 09:38 * @version: 1.0 */ @RunWith (SpringRunner. class ) @SpringBootTest public class IndexTest { /* - - - - - 操作索引 - - - - - */ //注入 ElasticsearchRestTemplate @Autowired private ElasticsearchRestTemplate esRestTemplate; //创建索引并增加映射配置 @Test public void createIndex(){ //创建索引,系统初始化会自动创建索引 System.out.println( "创建索引" ); } @Test public void deleteIndex(){ //创建索引,系统初始化会自动创建索引 boolean flg = esRestTemplate.deleteIndex(Product. class ); System.out.println( "删除索引 = " + flg); } /* - - - - - 操作索引 - - - - - */ } |
文档CRUD操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | package cn.cloud9; import cn.cloud9.dao.ProductDAO; import cn.cloud9.po.Product; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; /** * @projectName: SpringDataElasticSearch * @author: Cloud9 * @date: 2022年09月06日 09:48 * @version: 1.0 */ @RunWith (SpringRunner. class ) @SpringBootTest public class DocumentTest { /* - - - - - 操作文档 - - - - - */ @Autowired private ProductDAO productDAO; /** * 新增 */ @Test public void save(){ Product product = new Product(); product.setId(2L); product.setTitle( "华为手机" ); product.setCategory( "手机" ); product.setPrice( 2999.0 ); product.setImages( "http://www.atguigu/hw.jpg" ); productDAO.save(product); } //修改 @Test public void update(){ Product product = new Product(); product.setId(1L); product.setTitle( "小米 2 手机" ); product.setCategory( "手机" ); product.setPrice( 9999.0 ); product.setImages( "http://www.atguigu/xm.jpg" ); productDAO.save(product); } //根据 id 查询 @Test public void findById(){ Product product = productDAO.findById(1L).get(); System.out.println(product); } //查询所有 @Test public void findAll(){ Iterable<Product> products = productDAO.findAll(); for (Product product : products) { System.out.println(product); } } //删除 @Test public void delete(){ Product product = new Product(); product.setId(1L); productDAO.delete(product); } //批量新增 @Test public void saveAll(){ List<Product> productList = new ArrayList<>(); for ( int i = 0 ; i < 10 ; i++) { Product product = new Product(); product.setId(Long.valueOf(i)); product.setTitle( "[" +i+ "]小米手机" ); product.setCategory( "手机" ); product.setPrice( 1999.0 +i); product.setImages( "http://www.atguigu/xm.jpg" ); productList.add(product); } productDAO.saveAll(productList); } //分页查询 @Test public void findByPageable(){ //设置排序(排序方式,正序还是倒序,排序的 id) Sort sort = Sort.by(Sort.Direction.DESC, "id" ); int currentPage= 0 ; //当前页,第一页从 0 开始,1 表示第二页 int pageSize = 5 ; //每页显示多少条 //设置查询分页 PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort); //分页查询 Page<Product> productPage = productDAO.findAll(pageRequest); for (Product Product : productPage.getContent()) { System.out.println(Product); } } /* - - - - - 操作文档 - - - - - */ } |
文档查询操作:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | package cn.cloud9; import cn.cloud9.dao.ProductDAO; import cn.cloud9.po.Product; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermQueryBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.domain.PageRequest; import org.springframework.test.context.junit4.SpringRunner; /** * @projectName: SpringDataElasticSearch * @author: cloud9 * @date: 2022年09月06日 09:50 * @version: 1.0 */ @RunWith (SpringRunner. class ) @SpringBootTest public class DocumentQueryTest { @Autowired private ProductDAO productDAO; /** * term 查询 * search(termQueryBuilder) 调用搜索方法,参数查询构建器对象 */ @Test public void termQuery(){ TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery( "title" , " 小米" ); Iterable<Product> products = productDAO.search(termQueryBuilder); for (Product product : products) { System.out.println(product); } } /** * term 查询加分页 */ @Test public void termQueryByPage(){ int currentPage= 0 ; int pageSize = 5 ; //设置查询分页 PageRequest pageRequest = PageRequest.of(currentPage, pageSize); TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery( "title" , " 小米" ); Iterable<Product> products = productDAO.search(termQueryBuilder,pageRequest); for (Product product : products) { System.out.println(product); } } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?