溫馨提示×

springboot和elasticsearch怎么整合

小億
82
2024-09-26 00:02:01
欄目: 編程語言

Spring Boot與Elasticsearch的整合主要包括以下幾個步驟:

  1. 添加依賴:在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>
    
  2. 配置Elasticsearch:在application.propertiesapplication.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
    
  3. 創(chuàng)建Elasticsearch配置類:創(chuàng)建一個配置類,用于初始化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();
        }
    }
    
  4. 使用ElasticsearchTemplate:在需要操作Elasticsearch的類中,注入ElasticsearchTemplate bean,并使用它執(zhí)行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集群。記得根據(jù)你的實際需求調(diào)整配置和代碼。

0