本文基于Java High Level REST Client 7.12
一、引入依赖
<!-- elasticsearch版本,保持与本地版本一致 -->
<elasticsearch.version>7.12.1</elasticsearch.version>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
二、配置 RestHighLevelClient
/**
* 配置 RestHighLevelClient
*/
@Configuration
public class ElasticSearchConfig {
@Bean
public RestHighLevelClient restHighLevelClient() {
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http")));
return client;
}
}
可以去配置文件中直接设置
三、实例
本文没有使用 ElasticSearchTemplate、ElasticSearchRestTemplate
索引操作
@Autowired
private RestHighLevelClient restHighLevelClient;
/**
* 创建索引
*/
@Test
public void createIndex() throws IOException {
// 创建索引请求
CreateIndexRequest indexRequest = new CreateIndexRequest("test4");
// 客户端执行请求,请求后获得响应
CreateIndexResponse indexResponse = restHighLevelClient.indices().create(indexRequest, RequestOptions.DEFAULT);
System.out.println(indexResponse.index()); //输出:test4
}
/**
* 获取索引,只能判断索引存不存在
*/
@Test
public void existIndex() throws IOException {
// 创建获取索引请求
GetIndexRequest request = new GetIndexRequest("test4");
boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
System.out.println(exists);
}
/**
* 删除索引
*/
@Test
public void deleteIndexTest() throws IOException {
DeleteIndexR