Spring Boot與Elasticsearch的整合主要包括以下幾個步驟:
添加依賴:在pom.xml
文件中添加Elasticsearch的客戶端依賴和Spring Boot的Elasticsearch依賴。例如:
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.x.x</version> <!-- 使用與Elasticsearch集群版本相匹配的版本 -->
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
配置Elasticsearch:在application.properties
或application.yml
文件中配置Elasticsearch集群的連接信息。例如:
# application.properties
spring.elasticsearch.cluster-name=my-application
spring.elasticsearch.cluster-nodes=http://localhost:9200
或者使用YAML格式:
# application.yml
spring:
elasticsearch:
cluster-name: my-application
cluster-nodes: http://localhost:9200
創建Elasticsearch配置類:創建一個配置類,用于初始化RestHighLevelClient
bean。例如:
@Configuration
public class ElasticsearchConfig {
@Value("${spring.elasticsearch.cluster-nodes}")
private String clusterNodes;
@Bean
public RestHighLevelClient restHighLevelClient() {
final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
.connectedTo(clusterNodes)
.build();
return RestClient.builder(clientConfiguration).build();
}
}
使用ElasticsearchTemplate:在需要操作Elasticsearch的類中,注入ElasticsearchTemplate
bean,并使用它執行CRUD操作。例如:
@Service
public class MyService {
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
public void saveDocument(MyDocument document) {
elasticsearchTemplate.save(document);
}
public List<MyDocument> searchDocuments(String query) {
return (List<MyDocument>) elasticsearchTemplate.queryForList(
new NativeSearchQueryBuilder()
.withQuery(query)
.build(), MyDocument.class);
}
}
通過以上步驟,你可以將Spring Boot與Elasticsearch整合起來,并使用ElasticsearchTemplate
方便地操作Elasticsearch集群。記得根據你的實際需求調整配置和代碼。