温馨提示×

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. 创建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();
        }
    }
    
  4. 使用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集群。记得根据你的实际需求调整配置和代码。

0