SpringBoot 3.x + ElasticsearchTemplate 索引库操作
什么是 ElasticsearchTemplate
- 是 Spring Data Elasticsearch 提供的一个核心类,是 ElasticsearchClient 的一个具体实现
- 用于在 Spring Boot 中操作 Elasticsearch 进行数据的存取和查询
- 提供了一组方法来执行各种操作,如保存、更新、删除和查询文档,执行聚合操作等
ElasticsearchTemplate 的一些常用方法
| 方法 | 描述 |
|---|---|
| save(Object) | 保存一个对象到 Elasticsearch 中。 |
| index(IndexQuery) | 使用 IndexQuery 对象执行索引操作。 |
| delete(String, String) | 删除指定索引和类型的文档。 |
| get(String, String) | 获取指定索引和类型的文档。 |
| update(UpdateQuery) | 使用 UpdateQuery 对象执行更新操作。 |
| search(SearchQuery, Class) | 执行搜索查询,并将结果映射为指定类型的对象。 |
| count(SearchQuery, Class) | 执行搜索查询,并返回结果的计数 |
ElasticsearchTemplate 常见注解配置(都是属于spring data elasticsearch)
- @Id 指定主键
- @Document 指定实体类和索引对应关系:
indexName:索引名称 - @Field 指定普通属性
| FieldType 属性值 | 描述 |
|---|---|
| type | 对应 Elasticsearch 中属性类型,使用 FiledType 枚举快速获取。 |
| text | 类型能被分词 |
| keywords | 不能被分词 |
| index | 是否创建索引,作为搜索条件时 index 必须为 true |
| analyzer | 指定分词器类型。 |
案例实战
创建DTO
java
@Document(indexName = "video")
public class VideoDTO {
@Id
@Field(type = FieldType.Text, index = false)
private Long id;
@Field(type = FieldType.Text)
private String title;
@Field(type = FieldType.Text)
private String description;
@Field(type = FieldType.Keyword)
private String category;
@Field(type = FieldType.Integer)
private Integer duration;
@Field(type = FieldType.Date, format = DateFormat.date_hour_minute_second)
private LocalDateTime createTime;
public VideoDTO(){}
public VideoDTO(Long id, String title, String description, Integer duration,String category) {
this.id = id;
this.title = title;
this.description = description;
this.duration = duration;
this.createTime = LocalDateTime.now();
this.category = category;
}
// 省略set get方法
}创建测试方法
java
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.client.elc.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.IndexOperations;
/**
* ElasticsearchTemplate 索引库操作
*
* @author 朔风
* @date 2026-03-25 10:59
*/
@SpringBootTest
class ElasticsearchTemplateTests {
@Autowired
private ElasticsearchTemplate restTemplate;
/**
* 判断索引是否存在索引
*/
@Test
void existsIndex() {
IndexOperations indexOperations = restTemplate.indexOps(VideoDTO.class);
boolean exists = indexOperations.exists();
System.out.println(exists);
}
/**
* 创建索引
*/
@Test
void createIndex() {
// spring data es所有索引操作都在这个接口
IndexOperations indexOperations = restTemplate.indexOps(VideoDTO.class);
// 是否存在,存在则删除
if(indexOperations.exists()){
indexOperations.delete();
}
// 创建索引
indexOperations.create();
//设置映射: 在正式开发中,几乎不会使用框架创建索引或设置映射,这是架构或者管理员的工作,不适合使用代码实现
restTemplate.indexOps(VideoDTO.class).putMapping();
}
/**
* 删除索引
*/
@Test
void deleteIndex() {
IndexOperations indexOperations = restTemplate.indexOps(VideoDTO.class);
boolean delete = indexOperations.delete();
System.out.println(delete);
}
}
朔风