spring boot 集成es 7.0的配置
时间: 2023-11-21 12:04:53 浏览: 101
在Spring Boot中,集成Elasticsearch 7.x版本的步骤如下:
1. 添加Elasticsearch的依赖
```xml
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.0.0</version>
</dependency>
```
2. 在application.properties文件中配置Elasticsearch的连接信息
```properties
spring.data.elasticsearch.cluster-nodes=localhost:9200
```
3. 创建Elasticsearch的配置类
```java
@Configuration
public class ElasticsearchConfig {
@Value("${spring.data.elasticsearch.cluster-nodes}")
private String clusterNodes;
@Bean
public RestHighLevelClient restHighLevelClient() {
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"));
RestHighLevelClient client = new RestHighLevelClient(builder);
return client;
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchRestTemplate(restHighLevelClient());
}
}
```
在该配置类中,我们使用`RestHighLevelClient`来和Elasticsearch进行交互,并配置了`ElasticsearchRestTemplate`来方便我们进行数据的操作。
4. 在代码中使用Elasticsearch
```java
@Autowired
private ElasticsearchOperations elasticsearchOperations;
...
// 创建索引
IndexOperations indexOps = elasticsearchOperations.indexOps(IndexCoordinates.of("indexName"));
indexOps.create();
// 存储文档
IndexQuery indexQuery = new IndexQueryBuilder()
.withObject(document)
.build();
elasticsearchOperations.index(indexQuery, IndexCoordinates.of("indexName"));
// 查询文档
SearchHits<Document> searchHits = elasticsearchOperations.search(
new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.matchQuery("title", "spring boot"))
.build(),
Document.class,
IndexCoordinates.of("indexName"));
List<Document> documents = searchHits.stream()
.map(SearchHit::getContent)
.collect(Collectors.toList());
```
以上代码演示了如何在Spring Boot中使用Elasticsearch进行索引的创建、文档的存储和查询。如果需要更多的操作,可以参考官方文档:https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html
阅读全文