前言
spring-boot-starter-data-elasticsearch
是 Spring Boot 提供的一个起始依赖,旨在简化与 Elasticsearch 交互的开发过程。它集成了 Spring Data Elasticsearch,提供了一套完整的 API,用于与 Elasticsearch 进行 CRUD 操作、查询、索引等
相对于es原生依赖的话,进行了一下封装,在使用过程中相对便捷
项目源码
项目源码:https://gitee.com/shen-chuhao/walker_open_java.git
elasticsearch和springboot版本要求
在使用 spring-boot-starter-data-elasticsearch
时,Spring Boot 版本和 Elasticsearch 版本不一致可能导致以下问题:
- 兼容性问题:
- Spring Data Elasticsearch 依赖于特定版本的 Elasticsearch 客户端库。如果版本不兼容,可能会导致运行时异常或方法未找到的错误。
- 功能缺失或错误:
- 一些新功能可能在不兼容的版本中不可用,或者可能会存在实现上的差异,导致某些功能无法正常工作。
- 配置问题:
- 某些配置选项可能会因版本不一致而有所不同。例如,某些配置参数在新版本中可能被弃用,或者在旧版本中可能不可用。
- 序列化和反序列化问题:
- 数据模型的变化可能导致在 Elasticsearch 中存储的数据格式与预期不符,从而引发解析错误。
- 性能问题:
- 不兼容的版本可能导致性能下降或不稳定,尤其是在高并发环境下。
相关版本的要求
我的es是7.3.2的,介于6.8.127.6.2之间,所以springboot版本为2.2.x2.3.x即可
所以在使用spring-boot-starter-data-elasticsearch的过程中,还是要保持版本一致
整合步骤
依赖添加
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
yaml配置添加
spring:
elasticsearch:
rest:
uris: localhost:19200
# 账号密码配置,如果没有则不需要
password: elastic
username: elastic
实体类添加
package com.walker.es.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.annotation.TypeAlias;
import org.springframework.data.elasticsearch.annotations.DateFormat;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import org.springframework.format.annotation.DateTimeFormat;
import java.util.Date;
@Data
//索引
// boolean createIndex() default true; 默认会创建索引
@Document(indexName = "alarm_record", shards = 2, replicas = 2,createIndex = true)
public class AlarmRecordEntity {
// 配置使用的id
@Id
private Long id;
// 事件
// 配置属性,分词器
@Field(type = FieldType.Text, analyzer = "ik_max_word")
private String title;
// 设备
@Field(type = FieldType.Keyword)
private String deviceCode;
// 时间 需要使用keyword,否则无法实现范围查询
@Field(type = FieldType.Keyword)
private String time;
// 在es中进行忽略的
@Transient
private String msg;
}
- @Document注解:可以设置索引的名称,分片、副本,是否自动创建索引等
- @Id:指定文档的id
- @Field(type = FieldType.Text, analyzer = “ik_max_word”) 属性配置,可以用于配置字段的类型,分词器等等,具体的可以查看后面的
相关注解
Repository类
package com.walker.es.repository;
import com.walker.es.entity.AlarmRecordEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository