SpringBoot2.0之整合ElasticSearch

本文详细介绍如何使用SpringBoot2.0整合ElasticSearch,包括配置集群、项目结构搭建、实体类定义、DAO接口实现及控制器编写,通过实例演示添加和查询文档的具体操作。

SpringBoot2.0之整合ElasticSearch

就类比数据库到时候去实现

服务器端配置 集群名字  与yml名字一致

pom:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.toov5</groupId>
  <artifactId>springboot-es</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
      <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- springboot 整合es -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
  
</project>

项目结构:

Entity:

package com.toov5.entity;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

import lombok.Data;
  
 @Document(indexName="toov5",type="user")   //索引的名字  类型
 @Data 
public class UserEntity {
  @Id    
  private String id;
  private String name;
  private Integer age;
  private Integer sex;
}

Dao:

package com.toov5.dao;

import org.springframework.data.repository.CrudRepository;

import com.toov5.entity.UserEntity;

public interface UserDao extends CrudRepository<UserEntity, String> {

    
    
}

Controller:

package com.toov5.controller;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.toov5.dao.UserDao;
import com.toov5.entity.UserEntity;

@RestController
public class EsController {
    
    @Autowired
    private UserDao userDao;
    
    //添加文档
    @RequestMapping("/addUser")
    public UserEntity addUser(@RequestBody UserEntity userEntity) {
      return userDao.save(userEntity);    
    } 
    
    //查询文档
    @RequestMapping("/findById")
    public Optional<UserEntity> findById(String id) {
       return userDao.findById(id);    
    }
    
}

 

成功:

查看:

 

 

 查询:

 

<think>好的,我现在需要帮助用户解决在Spring Boot 2.0中集成Elasticsearch 7.x的问题。首先,我需要确认用户的需求。他们想要一个教程或解决方案,所以应该提供详细的步骤和可能的代码示例。 首先,我应该回想一下Spring Boot和Elasticsearch的版本兼容性。Spring Boot 2.0对应的Spring Data版本可能不是直接支持Elasticsearch 7.x的,因为通常Spring Data的版本和Elasticsearch的版本有对应关系。比如,Spring Boot 2.1.x之后才支持Elasticsearch 6.x,而更高的版本可能需要更高级的Spring Data。但用户想用Spring Boot 2.0,可能对应的Spring Data版本较旧,可能需要调整依赖或使用其他方法。 接下来,我需要考虑如何让Spring Boot 2.0兼容Elasticsearch 7.x。可能的解决方案包括使用Elasticsearch的Java客户端,比如RestHighLevelClient,或者通过覆盖依赖版本,使用与Elasticsearch 7.x兼容的Spring Data Elasticsearch版本。 另外,用户可能需要配置Elasticsearch的连接信息,比如主机和端口。在配置文件中设置spring.elasticsearch.rest.uris应该是一个步骤。 然后,可能需要创建实体类,使用@Document注解,以及定义Repository接口。这部分需要确保注解和Spring Data的版本兼容。如果Spring Boot 2.0的默认Spring Data版本不支持Elasticsearch 7.x的注解,可能需要手动调整或使用不同的注解方式。 还可能涉及排除掉旧版的Elasticsearch客户端,比如TransportClient,并引入新的RestClient。这可以通过在Maven或Gradle中排除依赖并添加新的依赖项来实现。 测试部分,编写一个测试用例来验证连接是否成功,以及能否进行基本的CRUD操作,这也是用户需要的。 此外,需要注意版本冲突的问题,比如Jackson库或其他依赖项的版本是否兼容。可能需要调整依赖版本以避免冲突。 最后,生成相关问题,比如兼容性问题、配置方法、版本差异、高级功能使用等,帮助用户进一步了解可能遇到的问题。 现在整理这些思路,形成结构化的回答,分步骤说明,并提供代码示例和配置示例。同时,确保引用之前的参考内容,虽然之前的引用是关于Spark的,但可能用户有其他相关问题,所以这里可能需要忽略无关引用,专注于当前问题。</think>### Spring Boot 2.0集成Elasticsearch 7.x的解决方案 #### 1. 版本兼容性调整 Spring Boot 2.0默认集成的Spring Data Elasticsearch版本较旧(通常为3.x),与Elasticsearch 7.x存在兼容性问题。需要通过Maven/Gradle手动指定兼容版本: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> <exclusions> <exclusion> <groupId>org.elasticsearch.client</groupId> <artifactId>transport</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>7.17.3</version> <!-- 与ES服务端版本一致 --> </dependency> ``` #### 2. 配置客户端连接 在`application.properties`中配置: ```properties spring.elasticsearch.rest.uris=http://localhost:9200 spring.elasticsearch.rest.connection-timeout=5s spring.elasticsearch.rest.read-timeout=60s ``` 或通过Java Config定义Bean: ```java @Configuration public class EsConfig { @Bean public RestHighLevelClient elasticsearchClient() { return new RestHighLevelClient( RestClient.builder(HttpHost.create("localhost:9200")) ); } } ``` #### 3. 实体映射 使用`@Document`注解定义索引映射: ```java @Document(indexName = "products", createIndex = false) public class Product { @Id private String id; @Field(type = FieldType.Text, analyzer = "ik_max_word") private String name; @Field(type = FieldType.Double) private Double price; // getters/setters } ``` #### 4. 仓库接口 继承`ElasticsearchRepository`: ```java public interface ProductRepository extends ElasticsearchRepository<Product, String> { List<Product> findByPriceBetween(Double min, Double max); } ``` #### 5. 自定义操作 通过`RestHighLevelClient`实现复杂查询: ```java @Autowired private RestHighLevelClient client; public SearchResponse searchByKeyword(String keyword) throws IOException { SearchRequest request = new SearchRequest("products"); SearchSourceBuilder sourceBuilder = new SearchSourceBuilder(); sourceBuilder.query(QueryBuilders.matchQuery("name", keyword)); request.source(sourceBuilder); return client.search(request, RequestOptions.DEFAULT); } ``` #### 6. 测试验证 ```java @SpringBootTest class EsIntegrationTest { @Autowired private ProductRepository repository; @Test void testSaveDocument() { Product product = new Product(); product.setName("Spring Boot实战"); product.setPrice(59.99); Product saved = repository.save(product); assertNotNull(saved.getId()); } } ``` ### 关键注意事项 1. **版本矩阵**:需确保Spring Data ElasticsearchElasticsearch版本匹配[^1] 2. **类型映射**:ES 7.x已移除`_type`字段,需设置`@Document(indexName = "index")` 3. **分词器配置**:建议通过`@Setting`注解指定自定义分词器 4. **健康检查**:可通过`/actuator/health`端点监控ES连接状态
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值