springboot使用ElasticsearchRestTemplate
时间: 2023-07-01 15:08:26 浏览: 214
是的,Spring Boot可以使用ElasticsearchRestTemplate与Elasticsearch进行交互。以下是一些基本步骤:
1. 添加依赖
在pom.xml中添加以下依赖:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
```
2. 配置连接信息
在application.properties中添加Elasticsearch的连接信息:
```properties
spring.data.elasticsearch.cluster-nodes=127.0.0.1:9300
spring.data.elasticsearch.cluster-name=my-application
```
3. 创建ElasticsearchRestTemplate Bean
创建一个ElasticsearchRestTemplate的Bean,用于与Elasticsearch进行交互:
```java
@Configuration
public class ElasticsearchConfig {
@Value("${spring.data.elasticsearch.cluster-nodes}")
private String clusterNodes;
@Value("${spring.data.elasticsearch.cluster-name}")
private String clusterName;
@Bean
public RestHighLevelClient client() {
ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(clusterNodes)
.build();
return RestClients.create(clientConfiguration).rest();
}
@Bean
public ElasticsearchRestTemplate elasticsearchRestTemplate() {
return new ElasticsearchRestTemplate(client());
}
}
```
4. 使用ElasticsearchRestTemplate
现在你可以使用ElasticsearchRestTemplate与Elasticsearch进行交互,例如:
```java
@Autowired
private ElasticsearchRestTemplate elasticsearchRestTemplate;
public void indexDocument(String indexName, Object document) {
IndexQueryBuilder indexQueryBuilder = new IndexQueryBuilder().withObject(document);
IndexCoordinates indexCoordinates = IndexCoordinates.of(indexName);
String documentId = elasticsearchRestTemplate.index(indexQueryBuilder, indexCoordinates);
}
```
这里的elasticsearchRestTemplate是在配置文件中创建的ElasticsearchRestTemplate Bean。
阅读全文