springboot 集成最新版Elasticsearch
时间: 2023-06-28 14:09:37 浏览: 97
要在 Spring Boot 中集成最新版 Elasticsearch,请按照以下步骤操作:
1. 添加 Elasticsearch 相关的依赖。在 pom.xml 文件中添加以下依赖:
```
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.10.1</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.10.1</version>
</dependency>
```
2. 配置 Elasticsearch。在 application.properties 文件中添加以下配置:
```
spring.elasticsearch.rest.uris=http://localhost:9200
```
3. 创建 Elasticsearch 客户端。在 Spring Boot 应用程序中,您可以使用 RestHighLevelClient 来与 Elasticsearch 进行交互。在您的应用程序中创建一个此类的 Bean:
```
@Configuration
public class ElasticsearchConfig {
@Value("${spring.elasticsearch.rest.uris}")
private String elasticsearchHost;
@Bean(destroyMethod = "close")
public RestHighLevelClient restHighLevelClient() {
return new RestHighLevelClient(
RestClient.builder(new HttpHost(elasticsearchHost, 9200, "http")));
}
}
```
4. 使用 Elasticsearch 客户端。您可以使用 RestHighLevelClient 对 Elasticsearch 进行各种操作,例如:
```
@Autowired
private RestHighLevelClient restHighLevelClient;
public void search() throws IOException {
SearchRequest searchRequest = new SearchRequest("your_index_name");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("your_field_name", "your_query"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
// 处理搜索结果
}
```
以上就是在 Spring Boot 中集成最新版 Elasticsearch 的步骤。
阅读全文