目录
一、集成Spring Boot
Java使用对应的rest风格调用ES是通过client依赖包进行操作的
配置需要的 maven 依赖
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.17.24</version>
</dependency>
1、创建项目
如果创建项目后拉取不到对应依赖,springboot 可以选用低一些的稳定版本例如 2.3.2.RELEASE 版本
2、pom文件 查看springboot集成的依赖
(当然也可自定义ES版本)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
3、增加es的config类
package com.example.elasticsearch_springboot_demo.config;
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;
@Configuration
public class ElasticSearchClientConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")));
return client;
}
}
二、索引相关API
1、创建索引
@SpringBootTest
class ElasticSearchSpringbootDemoApplicationTests {
@Autowired
@Qualifier("restHighLevelClient")
private RestHighLevelClient client;
/**
* 【索引相关】索引创建
*/
@Test
void testCreateIndex() throws IOException {
// 1、创建索引请求
CreateIndexRequest request = new CreateIndexRequest("m_index");
// 2、客户端执行请求 IndicesClient,执行创建请求 并获得响应结果
CreateIndexResponse createIndexResponse = client.indices().create