<!-- 使用SpringDataElasticSearch实现操作 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
/**
* @author huidou
* @date 2022/7/8
* @deprecated 该实体类与ElasticSearch的索引实现关联
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "product",createIndex = true)
public class Product {
@Id
@Field(type = FieldType.Integer,store = true,index = true)
private Integer id;
@Field(type = FieldType.Text,store = true,index = true)
private String name;
@Field(type = FieldType.Text,store = true,index = true)
private String desc;
}
-
创建Repository接口,继承ES的Repository接口实现对ES的操作
/**
* @author huidou
* @date 2022/7/8
*/
public interface ProductRepository extends ElasticsearchRepository<Product,Integer> {
}
/**
* 将Repository注入进来
*/
@Autowired
private ProductRepository repository;
/**
* 添加单个文档
*/
@Test
public void addOneDocument() {
Product product = new Product(1, "iphone30", "iphone30是苹果最新手机");
repository.save(product);
}
/**
* 添加多个文档
*/
@Test
public void addMultipleDocument() {
Product product1 = new Product(4, "iphone33", "iphone33是苹果最新手机");
Product product2 = new Product(5, "iphone34", "iphone34是苹果最新手机");
Product product3 = new Product(6, "iphone35", "iphone35是苹果最新手机");
List<Product> list = new ArrayList<>();
list.add(product1);
list.add(product2);
list.add(product3);
repository.saveAll(list);
}
/**
* 更新文档内容
*/
@Test
public void updateDocument() {
Product product = new Product(4, "iphone33", "iphone33是苹果最新手机是更新之后的值");
repository.save(product);
}
/**
* 查询所有的文档
*/
@Test
public void findAllDocument() {
Iterable<Product> products = repository.findAll();
for (Product product : products) {
System.out.println(product);
}
}
/**
* 根据文档的ID查询文档信息
*/
@Test
public void findDocumentByID() {
Optional<Product> product = repository.findById(1);
System.out.println(product);
}
/**
* 删除文档信息
*/
@Test
public void deleteDocument() {
repository.deleteById(4);
}
/**
* 分页查询文档信息
*/
@Test
public void findDocumentByPage() {
// 1、创建分页对象
Pageable pageable = PageRequest.of(1, 2);
// 2、通过分页对象条件查询文档信息
Page<Product> page = repository.findAll(pageable);
// 3、遍历文档结果
for (Product product : page) {
System.out.println(product);
}
// 4、输出分页的属性信息
System.out.println(page.getTotalElements());
System.out.println(page.getTotalPages());
System.out.println(page.getContent());
System.out.println(page.getNumber());
}
/**
* 排序测试
*/
@Test
public void SortDocumentByID() {
Sort sort = Sort.by(Sort.Direction.DESC, "id");
Iterable<Product> products = repository.findAll(sort);
for (Product product : products) {
System.out.println(product);
}
}
/**
* 分页加排序
*/
@Test
public void SortAndPage() {
Sort sort = Sort.by(Sort.Direction.DESC, "id");
Pageable pageable = PageRequest.of(0, 3, sort);
Page<Product> products = repository.findAll(pageable);
for (Product product : products) {
System.out.println(product);
}
}