SpringBoot整合ElasticSearch7.6.2

SpringBoot整合ElasticSearch7.6.2

0、前置条件

之前使用SpringBoot整合过ES的低版本,ES各个大版本之间有较大的变化。

ES中值得注意的事项:

​ type逐渐移除,预计版本8中将消失

​ head插件在高等级的版本中,不支持直接安装,需要nodejs支持。

​ SpringBoot与Es的整合,需要注意版本支持,且在7.x的ES版本中客户端更新为 High Level REST Client,在 SpringBoot中的ElasticSearchTemplate过时,建议使用 High Level REST Client或者ElasticSearchRestTemplate。

版本如果不适配,也无法运行。

从Spring的官网可以看到版本的信息:

在这里插入图片描述

这次使用的版本是:

SpringBoot 2.3.0

ES7.6.2

这个SpringBoot版本中自带的是7.6.2版本的客户端,依赖如下:

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

ES数据如下:

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "boot",
        "_type" : "user",
        "_id" : "2",
        "_score" : 1.0,
        "_source" : {
          "name" : "Smish",
          "age" : 16,
          "gender" : "male",
          "desc" : [
            "产品经理",
            "艺术家"
          ]
        }
      },
      {
        "_index" : "boot",
        "_type" : "user",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "name" : "Jaskson",
          "age" : 18,
          "gender" : "male",
          "desc" : [
            "码农",
            "直男",
            "女装大佬"
          ]
        }
      }
    ]
  }
}

1、使用High Level REST Client

高级客户端是ES提供的客户端,支持多种语言。

在SpringBoot中使用只需要使用一个配置类设置好参数即可。

直接继承Springboot依赖中提供的配置类或者自建,保证有高级客户端对象即可。

@Configuration
public class RestClientConfig extends AbstractElasticsearchConfiguration {

    @Override
    public RestHighLevelClient elasticsearchClient() {

        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();

        return RestClients.create(clientConfiguration).rest();
    }
}

这个客户端提供了非常多的api供使用,测试如下:

//判断索引是否存在:

@SpringBootTest
@RunWith(SpringRunner.class)
public class ElasticTest {

    @Autowired
    RestHighLevelClient restHighLevelClient;

    @Test
    public void test() throws IOException {

        final GetIndexRequest indexRequest = new GetIndexRequest("boot");
        final boolean exists = restHighLevelClient.indices().exists(indexRequest,RequestOptions.DEFAULT)
        System.out.println(exists);
    }

 
}

//通过id或者索引查询数据:

@Test
public void test01() throws Exception {
        final GetRequest request = new GetRequest("boot", "1");
        final GetResponse response = restHighLevelClient.get(request, RequestOptions.DEFAULT);
        final String string = response.toString();
        System.out.println(string);
        System.out.println("-------------------------");
	
       
    }

{"_index":"boot","_type":"_doc","_id":"1","_version":2,"_seq_no":4,"_primary_term":3,"found":true,"_source":{"name":"Jaskson","age":18,"gender":"male","desc":["码农","直男","女装大佬"]}}

   
@Test
public void test02() throws Exception {
        SearchResponse search = restHighLevelClient.search(new SearchRequest("boot"), RequestOptions.DEFAULT);
        System.out.println(search);
    }


高级客户端内置api较多,这些操作也可以使用ElasticsearchRestTemplate操作。

2、ElasticsearchRestTemplate操作

ElasticsearchRestTemplate是使用高级 REST 客户端实现的接口,ElasticsearchTemplate自版本 4.0 开始弃用,不过其实操作差别不大。

首先需要一个实体类,加入注解。

@Document(indexName = "boot")
public class User {

    @Id
    private int id;
    @Field
    private String  name;
    @Field
    private Integer age;
    @Field
    private String gender;
    @Field
    private String desc;


    public User(int id, String name, Integer age, String gender, String desc) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.gender = gender;
        this.desc = desc;
    }

    public User(){};

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", desc='" + desc + '\'' +
                '}';
    }
}

测试查询:

    @Autowired
    ElasticsearchRestTemplate template;


    @Test
    public void test(){

        IndexOperations ops = template.indexOps(User.class);
        boolean exists = ops.exists();
        System.out.println(exists);
		
        //通过id查询,已经废弃
       	User user = template.queryForObject(GetQuery.getById("1"), User.class);
        System.out.println(user);
        
        //和上一样
        User user1 = template.get("1", User.class);
        System.out.println(user1);


        //查询所有
        final SearchHits<User> search = template.search(Query.findAll(), User.class);
        final Iterator<SearchHit<User>> iterator = search.iterator();
        while(iterator.hasNext()){
            System.out.println(iterator.next());
        }


    }
  • 2
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
好的,下面是SpringBoot整合Elasticsearch的步骤: 1. 添加Elasticsearch的依赖 在pom.xml文件中添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> ``` 2. 配置Elasticsearch连接 在application.yml或application.properties中添加以下配置: ``` spring: data: elasticsearch: cluster-name: elasticsearch # Elasticsearch集群名称 cluster-nodes: 127.0.0.1:9300 # Elasticsearch连接地址 ``` 3. 创建Elasticsearch实体类 创建一个Java类,使用@Document注解标记为Elasticsearch文档类型,并使用其他注解指定属性的映射关系,如下所示: ``` @Document(indexName = "my_index", type = "my_type") public class MyDocument { @Id private String id; private String title; private String content; // ... 省略getter和setter方法 } ``` 4. 创建Elasticsearch操作接口 创建一个接口,继承ElasticsearchRepository接口,并指定泛型为步骤3中创建的实体类,如下所示: ``` public interface MyDocumentRepository extends ElasticsearchRepository<MyDocument, String> { } ``` 5. 使用Elasticsearch操作数据 在需要使用Elasticsearch的地方注入MyDocumentRepository,即可使用其提供的方法进行数据的CRUD操作,如下所示: ``` @Autowired private MyDocumentRepository repository; public void save(MyDocument document) { repository.save(document); } public MyDocument findById(String id) { return repository.findById(id).orElse(null); } public void deleteById(String id) { repository.deleteById(id); } ``` 以上就是SpringBoot整合Elasticsearch的基本步骤,希望对你有帮助。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值