1.依赖
<parent >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-parent</artifactId >
<version > 3.0.0</version >
<relativePath />
</parent >
<properties >
<java.version > 17</java.version >
</properties >
<dependencies >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-web</artifactId >
</dependency >
<dependency >
<groupId > org.projectlombok</groupId >
<artifactId > lombok</artifactId >
</dependency >
<dependency >
<groupId > org.springframework.boot</groupId >
<artifactId > spring-boot-starter-data-elasticsearch</artifactId >
</dependency >
</dependencies >
2.yaml
spring:
elasticsearch:
uris: http://10.43.119.175:9200
username: elastic
password: hXtO*Lzi2GGJ5wUmUA2c
3.索引类
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@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 (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;
}
}
4.测试类
@Service
public class EsTest {
@Autowired
private ElasticsearchTemplate restTemplate;
public void existsIndex () {
IndexOperations indexOperations = restTemplate.indexOps(VideoDTO.class);
boolean exists = indexOperations.exists();
System.out.println(exists);
}
public void createIndex () {
IndexOperations indexOperations = restTemplate.indexOps(VideoDTO.class);
if (indexOperations.exists()){
indexOperations.delete();
}
indexOperations.create();
restTemplate.indexOps(VideoDTO.class).putMapping();
}
public void deleteIndex () {
IndexOperations indexOperations = restTemplate.indexOps(VideoDTO.class);
boolean delete = indexOperations.delete();
System.out.println(delete);
}
public void insert () {
VideoDTO videoDTO = new VideoDTO ();
videoDTO.setId(1L );
videoDTO.setTitle("小滴课堂架构大课和Spring Cloud" );
videoDTO.setCreateTime(LocalDateTime.now());
videoDTO.setDuration(100 );
videoDTO.setCategory("后端" );
videoDTO.setDescription("这个是综合大型课程,包括了jvm,redis,新版spring boot3.x,架构,监控,性能优化,算法,高并发等多方面内容" );
VideoDTO saved = restTemplate.save(videoDTO);
System.out.println(saved);
}
public void update () {
VideoDTO videoDTO = new VideoDTO ();
videoDTO.setId(1L );
videoDTO.setTitle("小滴课堂架构大课和Spring Cloud V2" );
videoDTO.setCreateTime(LocalDateTime.now());
videoDTO.setDuration(102 );
videoDTO.setCategory("后端" );
videoDTO.setDescription("这个是综合大型课程,包括了jvm,redis,新版spring boot3.x,架构,监控,性能优化,算法,高并发等多方面内容" );
VideoDTO saved = restTemplate.save(videoDTO);
System.out.println(saved);
}
public void batchInsert () {
List<VideoDTO> list = new ArrayList <>();
list.add(new VideoDTO (2L , "老王录制的按摩课程" , "主要按摩和会所推荐" , 123 , "后端" ));
list.add(new VideoDTO (3L , "冰冰的前端性能优化" , "前端高手系列" , 100042 , "前端" ));
list.add(new VideoDTO (4L , "海量数据项目大课" , "D哥的后端+大数据综合课程" , 5432345 , "后端" ));
list.add(new VideoDTO (5L , "小滴课堂永久会员" , "可以看海量专题课程,IT技术持续充电平台" , 6542 , "后端" ));
list.add(new VideoDTO (6L , "大钊-前端低代码平台" , "高效开发底层基础平台,效能平台案例" , 53422 , "前端" ));
list.add(new VideoDTO (7L , "自动化测试平台大课" , "微服务架构下的spring cloud架构大课,包括jvm,效能平台" , 6542 , "后端" ));
Iterable<VideoDTO> result = restTemplate.save(list);
System.out.println(result);
}
public void searchById () {
VideoDTO videoDTO = restTemplate.get("3" , VideoDTO.class);
assert videoDTO != null ;
System.out.println(videoDTO);
}
public void deleteById () {
String delete = restTemplate.delete("2" , VideoDTO.class);
System.out.println(delete);
}
public void searchAll () {
SearchHits<VideoDTO> search = restTemplate.search(Query.findAll(), VideoDTO.class);
List<SearchHit<VideoDTO>> searchHits = search.getSearchHits();
List<VideoDTO> videoDTOS = new ArrayList <>();
searchHits.forEach(hit -> {
videoDTOS.add(hit.getContent());
});
System.out.println(videoDTOS);
}
public void matchQuery () {
Query query = NativeQuery.builder().withQuery(q -> q
.match(m -> m
.field("description" )
.query("spring" )
)).build();
SearchHits<VideoDTO> searchHits = restTemplate.search(query, VideoDTO.class);
List<VideoDTO> videoDTOS = new ArrayList <>();
searchHits.forEach(hit -> {
videoDTOS.add(hit.getContent());
});
System.out.println(videoDTOS);
}
public void pageSearch () {
Query query = NativeQuery.builder().withQuery((co.elastic.clients.elasticsearch._types.query_dsl.Query) Query.findAll())
.withPageable(Pageable.ofSize(3 ).withPage(0 )).build();
SearchHits<VideoDTO> searchHits = restTemplate.search(query, VideoDTO.class);
List<VideoDTO> videoDTOS = new ArrayList <>();
searchHits.forEach(hit -> {
videoDTOS.add(hit.getContent());
});
System.out.println(videoDTOS);
}
public void sortSearch () {
Query query = NativeQuery.builder().withQuery((co.elastic.clients.elasticsearch._types.query_dsl.Query) Query.findAll())
.withPageable(Pageable.ofSize(10 ).withPage(0 ))
.withSort(Sort.by("duration" ).descending()).build();
SearchHits<VideoDTO> searchHits = restTemplate.search(query, VideoDTO.class);
List<VideoDTO> videoDTOS = new ArrayList <>();
searchHits.forEach(hit -> {
videoDTOS.add(hit.getContent());
});
System.out.println(videoDTOS);
}
public void stringQuery () {
String dsl = """
{"bool":{"must":[{"match":{"title":"架构"}},{"match":{"description":"spring"}},{"range":{"duration":{"gte":10,"lte":6000}}}]}}
""" ;
Query query = new StringQuery (dsl);
List<SearchHit<VideoDTO>> searchHitList = restTemplate.search(query, VideoDTO.class).getSearchHits();
List<VideoDTO> videoDTOS = new ArrayList <>();
searchHitList.forEach(hit -> {
videoDTOS.add(hit.getContent());
});
System.out.println(videoDTOS);
}
void aggQuery () {
Query query = NativeQuery.builder()
.withAggregation("category_group" , Aggregation.of(a -> a
.terms(ta -> ta.field("category" ).size(2 ))))
.build();
SearchHits<VideoDTO> searchHits = restTemplate.search(query, VideoDTO.class);
ElasticsearchAggregations aggregationsContainer = (ElasticsearchAggregations) searchHits.getAggregations();
Map<String, ElasticsearchAggregation> aggregations = Objects.requireNonNull(aggregationsContainer).aggregationsAsMap();
ElasticsearchAggregation aggregation = aggregations.get("category_group" );
Buckets<StringTermsBucket> buckets = aggregation.aggregation().getAggregate().sterms().buckets();
buckets.array().forEach(bucket -> {
System.out.println("组名:" +bucket.key().stringValue() + ", 值" + bucket.docCount());
});
List<VideoDTO> videoDTOS = new ArrayList <>();
searchHits.forEach(hit -> {
videoDTOS.add(hit.getContent());
});
System.out.println(videoDTOS);
}
}
5.接口
@RestController
@RequestMapping("/test")
public class TestAPI {
@Autowired
private EsTest esTest;
@PostMapping("/test")
public String test () {
esTest.createIndex();
esTest.deleteIndex();
return "test" ;
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律