spring boot 集成es 7.0
时间: 2023-07-24 16:06:10 浏览: 67
要在 Spring Boot 中集成 Elasticsearch 7.0,可以按照以下步骤操作:
1. 在 pom.xml 文件中添加 Elasticsearch 相关依赖:
```xml
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.0.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.0.0</version>
</dependency>
```
2. 创建 Elasticsearch 配置类 ElasticsearchConfig.java,用于配置 Elasticsearch 连接参数,例如:
```java
@Configuration
public class ElasticsearchConfig {
private static final String HOST = "localhost";
private static final int PORT = 9200;
private static final String SCHEME = "http";
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(
new HttpHost(HOST, PORT, SCHEME));
return new RestHighLevelClient(builder);
}
}
```
3. 在需要使用 Elasticsearch 的 Service 类中注入 RestHighLevelClient:
```java
@Service
public class MyService {
@Autowired
private RestHighLevelClient restHighLevelClient;
// ...
}
```
4. 在 Service 类中使用 RestHighLevelClient 调用 Elasticsearch API,例如:
```java
public void search() throws IOException {
SearchRequest searchRequest = new SearchRequest("my-index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("title", "java"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
SearchHits hits = searchResponse.getHits();
// ...
}
```
以上就是在 Spring Boot 中集成 Elasticsearch 7.0 的基本步骤,具体使用可以根据自己的需求进行调整。
阅读全文