springboot整合High Level Client elasticsearch详细步骤
时间: 2023-07-22 12:17:10 浏览: 191
Spring Boot整合elasticsearch的详细步骤
好的,下面我来为你讲解如何在Spring Boot中整合Elasticsearch的High Level Client,具体步骤如下:
1. 添加Elasticsearch依赖
在`pom.xml`文件中添加以下依赖:
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.15.1</version>
</dependency>
```
2. 配置Elasticsearch
在`application.properties`文件中添加以下配置:
```properties
spring.elasticsearch.rest.uris=http://localhost:9200 # Elasticsearch的地址和端口
```
3. 创建Elasticsearch配置类
创建一个配置类,用于配置Elasticsearch的High Level Client。例如:
```java
@Configuration
public class ElasticsearchConfig {
@Value("${spring.elasticsearch.rest.uris}")
private String esUris;
@Bean
public RestHighLevelClient restHighLevelClient() {
String[] esUriArray = esUris.split(",");
HttpHost[] httpHosts = new HttpHost[esUriArray.length];
for (int i = 0; i < esUriArray.length; i++) {
httpHosts[i] = HttpHost.create(esUriArray[i]);
}
RestClientBuilder builder = RestClient.builder(httpHosts);
return new RestHighLevelClient(builder);
}
}
```
其中,`@Value`注解用于获取`application.properties`文件中的配置,`RestHighLevelClient`为Elasticsearch的High Level Client。
4. 使用Elasticsearch
在代码中使用Elasticsearch时,只需要注入`RestHighLevelClient`,即可进行CRUD操作。例如:
```java
@Autowired
private RestHighLevelClient restHighLevelClient;
public void save(String index, String id, String json) throws IOException {
IndexRequest request = new IndexRequest(index).id(id).source(json, XContentType.JSON);
restHighLevelClient.index(request, RequestOptions.DEFAULT);
}
public String findById(String index, String id) throws IOException {
GetRequest request = new GetRequest(index).id(id);
GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
return response.getSourceAsString();
}
public void update(String index, String id, String json) throws IOException {
UpdateRequest request = new UpdateRequest(index, id).doc(json, XContentType.JSON);
restHighLevelClient.update(request, RequestOptions.DEFAULT);
}
public void delete(String index, String id) throws IOException {
DeleteRequest request = new DeleteRequest(index, id);
restHighLevelClient.delete(request, RequestOptions.DEFAULT);
}
```
以上就是在Spring Boot中整合Elasticsearch的High Level Client的详细步骤,希望能对你有所帮助!
阅读全文