本文使用的是springboot 2.2.x版本,elasticsearch使用的是6.8版本
官方文档参考:https://docs.spring.io/spring-data/elasticsearch/docs/4.2.7/reference/html/#new-features
对应版本
引入maven依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
springboot连接es的两种方式
方式一: 配置类
@Configuration
public class RestClientConfig {
/**
* 此配置在官网cv过来的,表示注册高级客户端RestHighLevelClient,它默认走的是9200端口
* transportClient客户端是基于tcp协议的,走的是es的9300端口,在es7版本后,已经不推荐使用transportClient客户端
* 可能还有人有疑问?注入的bean名字是client,那么注入时会不会有问题呢?这个无所谓,
* 当使用@Autowired注入bean时,会先按照类型进行注入,如果有且仅有一个此类型的bean,
* 那么就直接注入了,如果有多个同类型的bean,
* 那么就需要使用@Qualifier指定bean名字注入使用,此案例中这个RestHighLevelClient在容器中只有
* 一个,直接使用@Autowired就能注入使用了
* @return
*/
@Bean
RestHighLevelClient client() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo("填写es服务的ip+端口")
.build();
return RestClients.create(clientConfiguration).rest();
}
}
方式二:yml方式
spring:
elasticsearch:
rest:
uris: 106.52.98.231:19200
基于RestHighLevelClient 的入门例子
查询带高亮
更新
添加
删除
批量更新
自己编写的增删改查代码
/**
* 插入数据
* @throws IOException
*/
@Test
public void test2() throws IOException {
Student student = new Student();
student.setAge(13);
student.setBir(new Date());
student.setDetail("老师");
student.setHobby("网吧");
student.setId(UUID.randomUUID().toString());
student.setName("贺粪");
student.setRemark("男");
IndexRequest indexRequest = new