目录
- 5.1 Spring Data 框架集成
- 5.1.1 Spring Data 框架介绍
- 5.1.2 Spring Data Elasticsearch 介绍
- 5.1.3 Spring Data Elasticsearch 版本对比
- 5.1.4 集成步骤
5.1 Spring Data 框架集成
5.1.1 Spring Data 框架介绍
Spring Data 是一个用于简化数据库开发的开源框架。其主要目标是使得对数据的访问变得方便快捷,
Spring Data 可以极大的简化操作数据库的写法,可以在几乎不用写实现的情况下,实现对数据的访问和操作。除了 CRUD 外,还包括如分页、排序等一些常用的功能。
Spring Data 的官网:https://spring.io/projects/spring-data
5.1.2 Spring Data Elasticsearch 介绍
Spring Data Elasticsearch 基于 spring data API 简化 Elasticsearch 操作,将原始操作Elasticsearch 的客户端 API 进行封装。
官方网站: https://spring.io/projects/spring-data-elasticsearch
5.1.3 Spring Data Elasticsearch 版本对比
5.1.4 集成步骤
1、创建 Maven 项目
2、添加 pom 文件
<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>
3、增加配置文件
# es 服务地址
elasticsearch.host=127.0.0.1
# es 服务端口
elasticsearch.port=9200
# 配置日志级别,开启 debug 日志
logging.level.com.houchen=debug
4、SpringBoot 主程序
@SpringBootApplication
public class SpringDataElasticSearchMainApplication {public static void main(String[] args) {SpringApplication.run(SpringDataElasticSearchMainApplication.class,args);}
}
5、数据实体类
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
public class Product {private Long id;//商品唯一标识private String title;//商品名称private String category;//分类名称private Double price;//商品价格private String images;//图片地址
}
6、Es配置类
- ElasticsearchRestTemplate 是 spring-data-elasticsearch 项目中的一个类,和其他 spring 项目中的 template类似。
- 在新版的 spring-data-elasticsearch 中,ElasticsearchRestTemplate 代替了原来的 ElasticsearchTemplate。原因是 ElasticsearchTemplate 基于 TransportClient,TransportClient 即将在 8.x 以后的版本中移除。所以,我们推荐使用 ElasticsearchRestTemplate。
- ElasticsearchRestTemplate 基 于 RestHighLevelClient 客户端的。需要自定义配置类,继承
AbstractElasticsearchConfiguration,并实现 elasticsearchClient()抽象方法,创建 RestHighLevelClient 对
象
@Configuration
@ConfigurationProperties(prefix = "elasticsearch")
@Data
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {private String host;private Integer port;@Overridepublic RestHighLevelClient elasticsearchClient() {RestClientBuilder builder = RestClient.builder(new HttpHost(host, port));RestHighLevelClient restHighLevelClient = newRestHighLevelClient(builder);return restHighLevelClient;}
}
7、DAO 数据访问对象
@Repository
public interface ProductDao extends ElasticsearchRepository<Product,Long> {
}
8、实体类映射操作
@Data
@NoArgsConstructor
@AllArgsConstructor
@ToString
@Document(indexName = "product",shards = 3, replicas = 1)
public class Product {@Idprivate 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;//图片地址}
9、索引操作
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDateEsIndexTest {@Autowiredprivate ElasticsearchRestTemplate elasticSearchRestTemplate;@Autowiredprivate ProductDao productDao;//创建索引并增加映射配置@Testpublic void createIndex(){//创建索引,系统初始化会自动创建索引System.out.println("创建索引");}public void deleteIndex(){//创建索引,系统初始化会自动创建索引boolean flg = elasticSearchRestTemplate.deleteIndex(Product.class);System.out.println("删除索引 = " + flg);}}
10、文档操作
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDataESProductDaoTest {@Autowiredprivate ProductDao productDao;/*** 新增*/@Testpublic 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);}//修改@Testpublic 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 查询@Testpublic void findById() {Product product = productDao.findById(1L).get();System.out.println(product);}//查询所有@Testpublic void findAll() {Iterable<Product> products = productDao.findAll();for (Product product : products) {System.out.println(product);}}//删除@Testpublic void delete() {Product product = new Product();product.setId(1L);productDao.delete(product);}//批量新增@Testpublic 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);}//分页查询@Testpublic 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);}}
}
11、文档搜索
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringDateEsIndexTest {@Autowiredprivate ElasticsearchRestTemplate elasticSearchRestTemplate;@Autowiredprivate ProductDao productDao;/*** term 查询* search(termQueryBuilder) 调用搜索方法,参数查询构建器对象*/@Testpublic void termQuery(){TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", "小米");Iterable<Product> products = productDao.search(termQueryBuilder);for (Product product : products) {System.out.println(product);}}/*** term 查询加分页*/@Testpublic 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);}}}