springboot整合elasticsearch4.3.6
时间: 2023-10-30 14:07:56 浏览: 139
要在Spring Boot项目中整合Elasticsearch 4.3.6,您可以按照以下步骤操作:
1. 添加Maven依赖项
在您的pom.xml文件中添加以下依赖项:
```xml
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>4.3.6</version>
</dependency>
```
2. 配置Elasticsearch客户端
在application.properties或application.yml文件中添加Elasticsearch客户端配置:
```properties
# Elasticsearch client
spring.elasticsearch.rest.uris=http://localhost:9200
```
或者
```yaml
# Elasticsearch client
spring:
elasticsearch:
rest:
uris: http://localhost:9200
```
3. 创建Elasticsearch客户端bean
在您的配置类中创建Elasticsearch客户端bean:
```java
@Configuration
public class ElasticsearchConfig {
@Value("${spring.elasticsearch.rest.uris}")
private String[] uris;
@Bean
public RestHighLevelClient elasticsearchClient() {
RestClientBuilder builder = RestClient.builder(HttpHost.create(uris[0]));
return new RestHighLevelClient(builder);
}
}
```
4. 创建Elasticsearch操作类
创建一个类来执行Elasticsearch操作,例如索引、搜索、删除等:
```java
@Component
public class ElasticsearchOperations {
private final RestHighLevelClient elasticsearchClient;
@Autowired
public ElasticsearchOperations(RestHighLevelClient elasticsearchClient) {
this.elasticsearchClient = elasticsearchClient;
}
public void indexDocument(String index, String id, Map<String, Object> document) throws IOException {
IndexRequest request = new IndexRequest(index).id(id).source(document);
elasticsearchClient.index(request, RequestOptions.DEFAULT);
}
public SearchHits searchDocuments(String index, QueryBuilder query) throws IOException {
SearchRequest request = new SearchRequest(index);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(query);
request.source(sourceBuilder);
SearchResponse response = elasticsearchClient.search(request, RequestOptions.DEFAULT);
return response.getHits();
}
public void deleteDocument(String index, String id) throws IOException {
DeleteRequest request = new DeleteRequest(index, id);
elasticsearchClient.delete(request, RequestOptions.DEFAULT);
}
}
```
现在,您可以在您的应用程序中使用Elasticsearch操作类来执行Elasticsearch操作。例如,您可以将以下代码添加到您的控制器类中,以索引一个文档:
```java
@RestController
public class MyController {
private final ElasticsearchOperations elasticsearchOperations;
@Autowired
public MyController(ElasticsearchOperations elasticsearchOperations) {
this.elasticsearchOperations = elasticsearchOperations;
}
@PostMapping("/index")
public void indexDocument(@RequestParam String index, @RequestParam String id, @RequestBody Map<String, Object> document) throws IOException {
elasticsearchOperations.indexDocument(index, id, document);
}
}
```
这就是整合Elasticsearch 4.3.6的基本步骤。您可以按照需要进行更改和扩展。
阅读全文