一、依赖下载
创建好一个springboot项目,需要集成es:
因为springboot默认集成了es,但是版本号需要与本地或者服务器es的版本号一致,我本地es版本是7.14.0,所以需要在<properties></properties>中指定es版本号(这块很关键,很多因为es版本号问题连不上es服务)
<dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
二、创建配置文件
1、下边的配置相当于一个kibana客户端,只不过现在用代码连接es服务
//ElasticSearchConfig.java
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
// 下边的bean在链接es服务的时候需要用到,所以提前配置好
@Configuration // 这个注解相当于之前的xml
public class ElasticSearchConfig {// 注入bean@Beanpublic RestHighLevelClient restHighLevelClient() {RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(// es的ip 端口new HttpHost("localhost", 9200, "http")));return restHighLevelClient;}
}
三、测试
1、创建索引库
下边先注入了之前配置好的es客户端,然后创建 lxc 索引库,完之后,使用客户端执行请求。
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
@SpringBootTest
class DemoApplicationTests {// 注入es客户端,相当于 kabana客户端@Autowiredprivate RestHighLevelClient restHighLevelClient;@Testvoid contextLoads() {// 创建索引库 lxcCreateIndexRequest createIndexRequest = new CreateIndexRequest("lxc");// 创建好了索引库,现在需要执行这个请求,才能在es中创建 lxc 索引库try {restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);} catch (IOException e) {throw new RuntimeException(e);}finally {try {restHighLevelClient.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}
2、判断索引库是否存在
@Test
void isEist() throws IOException {// 选获取索引库GetIndexRequest getIndexRequest = new GetIndexRequest("lxc");GetIndexRequest getIndexRequest1 = new GetIndexRequest("lxc1");// 判断是否存在boolean exists = restHighLevelClient.indices().exists(getIndexRequest, RequestOptions.DEFAULT);boolean exists1 = restHighLevelClient.indices().exists(getIndexRequest1, RequestOptions.DEFAULT);System.out.println(exists); // trueSystem.out.println(exists1); // false
}
3、删除索引库
@Test
void del() throws IOException {// 创建一个删除索引库请求DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("lxc");// 执行请求AcknowledgedResponse acknowledgedResponse = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);System.out.println(acknowledgedResponse.isAcknowledged());
}