赞
踩
- 主要引用 elasticsearch使用相关依赖
- 注意ES 服务端版本(7.4.0)要与客户端版本相容
- 注意 hutool的工具类 实体转map 版本
<!--引入springboot父工程依赖--> <!--引入依赖作用: 可以省去version标签来获得一些合理的默认配置 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.2.RELEASE</version> </parent> <dependencies> <!--elasticsearch使用相关依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-elasticsearch</artifactId> </dependency> <!--引入提供Web开发场景依赖--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--这里用到了类型转Map,这里用到hutool的工具类(版本高一些,低版本的 如果传的就是Map类型,在map转map时会报错)--> <dependency> <groupId>cn.hutool</groupId> <artifactId>hutool-core</artifactId> <version>5.7.13</version> </dependency> <!--用@Data 减少JavaBean get...set...方法--> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> <!--两个用来做测试的jar包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> </dependency> </dependencies>
spring:
elasticsearch:
rest:
uris: 127.0.0.1:9200 #---ES的连接地址,多个地址用逗号分隔
username: #---用户名
password: #---密码
connection-timeout: 1000 #---连接超时时间(默认1s)
read-timeout: 1000 #---读取超时时间(默认30s)
- 注解:@Document用来声明Java对象与ElasticSearch索引的关系
indexName 索引名称(是字母的话必须是小写字母)
type 索引类型
shards 主分区数量,默认5
replicas 副本分区数量,默认1
createIndex 索引不存在时,是否自动创建索引,默认true
不建议自动创建索引(自动创建的索引 是按着默认类型和默认分词器)- 注解:@Id 表示索引的主键
- 注解:@Field 用来描述字段的ES数据类型,是否分词等配置,等于Mapping描述
index 设置字段是否索引,默认是true,如果是false则该字段不能被查询
store 默认为no,被store标记的fields被存储在和index不同的fragment中,以便于快速检索。虽然store占用磁盘空间,但是减少了计算。
type 数据类型(text、keyword、date、object、geo等)
analyzer 对字段使用分词器,注意一般如果要使用分词器,字段的type一般是text。
format 定义日期时间格式,详细见 官方文档: https://www.elastic.co/guide/reference/mapping/date-format/.- 注解:@CompletionField 定义关键词索引 要完成补全搜索
analyzer 对字段使用分词器,注意一般如果要使用分词器,字段的type一般是text。
searchAnalyzer 显示指定搜索时分词器,默认是和索引是同一个,保证分词的一致性。
maxInputLength:设置单个输入的长度,默认为50 UTF-16 代码点
常用数据类型:
**
简单类型:**
字符串类型: - string(不再支持)可知string类型的field已经被移除了, 我们需要用text或keyword类型来代替string.
text:会分词,不支持聚合
keyword:不会分词,将全部内容作为一个词条,支持聚合数字类型: 尽可能选择范围小的数据类型, 字段的长度越短, 索引和搜索的效率越高;(优先考虑使用带缩放因子的浮点类型)
byte : 有符号的8位整数, 范围: [-128 ~ 127]
short : 有符号的16位整数, 范围: [-32768 ~ 32767]
integer : 有符号的32位整数, 范围: [231 ~ 231-1]
long : 有符号的64位整数, 范围: [263 ~ 263-1]
float : 32位单精度浮点数
double : 64位双精度浮点数
half_float : 16位半精度IEEE 754浮点类型
scaled_float : 缩放类型的的浮点数, 比如price字段只需精确到分, 57.34缩放因子为100, 存储结果为5734日期类型:date JSON没有日期数据类型, 所以在ES中, 日期可以是:
—包含格式化日期的字符串 “2018-10-01”, 或"2018/10/01 12:10:30" (可以通过 format属性 定义日期时间格式)DateFormat 官方文法.
—代表时间毫秒数的长整型数字.
—代表时间秒数的整数.布尔类型: boolean 可以接受表示真、假的字符串或数字:
— 真值: true, “true”, “on”, “yes”, “1”…
— 假值: false, “false”, “off”, “no”, “0”, “”(空字符串), 0.0, 0
复杂类型:
- 数组[]: 由数组中第一个非空值决定数组类型(type = FieldType.Keyword)
- List集合: 由数组中第一个非空值决定数组类型(type = FieldType.Keyword)
- 嵌套类型: list里泛型是object形式的或自定义对象(type = FieldType.Nested)
- 对象:{ }object for single JSON objects 单个JSON对象(type = FieldType.Object)
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; 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 java.util.Date; import java.util.List; /* * 学生 * */ @Data @AllArgsConstructor @NoArgsConstructor //indexName名字如果是字母那么必须是小写字母 @Document(indexName = "student", type = "_doc", replicas = 1, shards = 1, createIndex = true) public class Student { @Id @Field(index = true, store = true, type = FieldType.Keyword) private String sId; @Field(index = true, store = true, type = FieldType.Keyword) private String sName; @Field(index = true, store = true, type = FieldType.Text, analyzer = "ik_smart") //Text可以分词 ik_smart=粗粒度分词 ik_max_word 为细粒度分词 private String sAddress; @Field(index = false, store = true, type = FieldType.Integer) private Integer sAge; @Field(index = false, store = true, type = FieldType.Date, format = DateFormat.basic_date_time) private Date sCreateTime; @Field(index = false, store = true, type = FieldType.Object) private Headmaster sHeadmaster;//班主任 @Field(index = true, store = false, type = FieldType.Keyword) private String[] sCourseList; //数组类型 由数组中第一个非空值决定(这里数组和集合一个意思了) @Field(index = true, store = false, type = FieldType.Keyword) private List<String> sColorList; //集合类型 由数组中第一个非空值决定 @Field(index = true, store = false, type = FieldType.Nested)//嵌套类型list里泛型是object形式的或自定义对象 private List<Teacher> sTeacherList; //教所有科目的老师 }
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.*; import org.springframework.data.elasticsearch.core.completion.Completion; import java.util.Date; /* * 科目老师 * */ @Data @NoArgsConstructor @AllArgsConstructor @Document(indexName = "teacher", type = "_doc", replicas = 1, shards = 1, createIndex = true) public class Teacher { //主键id @Id @Field(index = true, store = true, type = FieldType.Keyword)//index:设置通过这个字段是否可以进行搜索 private String tId; //姓名 @Field(index = true, store = true, type = FieldType.Keyword) private String tName; //英文姓名 @Field(index = true, store = true, type = FieldType.Keyword) private String tEnglishName; //班级 @Field(index = true, store = true, type = FieldType.Keyword) private String tClassName; //地址 @Field(index = true, store = true, type = FieldType.Text, analyzer = "ik_smart") private String tAddress; //至理名言 @Field(index = true, store = true, type = FieldType.Keyword) private String tFamous; //年龄 @Field(index = true, store = true, type = FieldType.Integer) private Integer tAge; //日期 @Field(index = true, store = true, type = FieldType.Date, format = DateFormat.basic_date_time) private Date tCreateTime; //定义关键词索引 要完成补全搜索,必须要用到特殊的数据类型completion, //要汉字拼音都能补全,必须要使用自定义的ik+pinyin分词器 // maxInputLength:设置单个输入的长度,默认为50 UTF-16 代码点 @CompletionField(analyzer = "ik_smart", searchAnalyzer = "ik_smart", maxInputLength = 100) private Completion completion; public Teacher(String tId, String tName, String tEnglishName, String tClassName, String tAddress, Integer tAge, Date tCreateTime) { this.tId = tId; this.tName = tName; this.tEnglishName = tEnglishName; this.tClassName = tClassName; this.tAddress = tAddress; this.tAge = tAge; this.tCreateTime = tCreateTime; } }
import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.Date; import java.util.List; /* * 班主任 * */ @Data @NoArgsConstructor @AllArgsConstructor @Document(indexName = "headmaster", type = "_doc", replicas = 1, shards = 1, createIndex = true) public class Headmaster { @Field(index = true, store = false, type = FieldType.Keyword) private String hId; @Field(index = true, store = false, type = FieldType.Keyword) private String hName; @Field(index = true, store = false, type = FieldType.Keyword) private String hAddress; @Field(index = false, store = false, type = FieldType.Integer) private Integer hSalary; @Field(index = false, store = false, type = FieldType.Keyword) private List<String> hClass; @Field(index = true, store = true, type = FieldType.Date, format = DateFormat.basic_date_time) private Date hCreateTime; }
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*
* 搜索引擎客户端启动类
* */
@SpringBootApplication
public class ElasticsearchApplication {
public static void main(String[] args) {
SpringApplication.run(ElasticsearchApplication.class, args);
}
}
- createIndex :新增索引(数据库)
- putMapping :新增映射(表结构)
- 一定要通过这种方法创建,否则创建出来的映射都是默认的
createIndex && putMapping 创建索引及映射测试
- 入参classType : 对象是要被ES注解所引用的的(基于@Field和@Documen注解属性 创建索引和映射)
import com.it.mhh.elasticsearch.service.ElasticsearchSaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
@创建人: Mhh
@创建时间: 2021/12/10
@描述: 新增类
*/
@RestController
@RequestMapping(“/elasticSearch/save”)
public class ElasticsearchSaveController {
@Autowired
private ElasticsearchSaveService elasticsearchSaveService;
/**
}
/** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 新增 */ public interface ElasticsearchSaveService { /** * @param classType : 要创建es的索引及映射(一定要通过这种方法创建,否则都是创建出来的映射都是默认的)基于传入对象中的@Document注解 * @return boolean * @throws * @Author Mhh * @Date 2021/12/9 10:43 */ boolean createIndexAndMapping(Class<?> classType); }
import com.it.mhh.elasticsearch.service.ElasticsearchSaveService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.stereotype.Service; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 新增 */ @Service public class ElasticsearchSaveServiceImp implements ElasticsearchSaveService { @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; /** * @param classType : 要创建es的索引及映射(一定要通过这种方法创建,否则都是创建出来的映射都是默认的)基于传入对象中的@Document注解 * @return boolean * @throws * @Author Mhh * @Date 2021/12/9 10:43 */ @Override public boolean createIndexAndMapping(Class<?> classType) { if (elasticsearchRestTemplate.indexExists(classType)) return true; boolean index = elasticsearchRestTemplate.createIndex(classType); boolean mapping = elasticsearchRestTemplate.putMapping(classType); return index && mapping; } }
- 根据入参对象 ES注解 创建索引及映射
import com.it.mhh.elasticsearch.controller.ElasticsearchSaveController; import com.it.mhh.elasticsearch.entity.Headmaster; import com.it.mhh.elasticsearch.entity.Student; import com.it.mhh.elasticsearch.entity.Teacher; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.elasticsearch.core.completion.Completion; import org.springframework.test.context.junit4.SpringRunner; import java.util.*; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 测试 */ @SpringBootTest @RunWith(SpringRunner.class) public class ElasticsearchSaveControllerTest { @Autowired private ElasticsearchSaveController elasticsearchSaveController; /** * @param classType : 要创建es的索引及映射(一定要通过这种方法创建,否则都是创建出来的映射都是默认的)基于传入对象中的@Document注解 * @return boolean * @throws * @Author Mhh * @Date 2021/12/9 10:43 */ @Test public void createIndexAndMapping() { boolean indexAndMapping = elasticsearchSaveController.createIndexAndMapping(Student.class); System.err.println(indexAndMapping); } }
- save(Iterable entities):可传集合 批量添加(同种类对象集合)
- save(T entity) :单个对象
- save(T… entities) : 可变参
save 添加文档测试
- 入参entities :有重载 可传集合 单个 或者 可变参
import com.it.mhh.elasticsearch.service.ElasticsearchSaveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
/**
@创建人: Mhh
@创建时间: 2021/12/10
@描述: 新增类
*/
@RestController
@RequestMapping(“/elasticSearch/save”)
public class ElasticsearchSaveController {
@Autowired
private ElasticsearchSaveService elasticsearchSaveService;
/**
/**
}
/** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 新增 */ public interface ElasticsearchSaveService { /** * @param entities : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ public <T> Iterable<T> save(Iterable<T> entities); /** * @param t : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ public <T> T save(T t); }
import com.it.mhh.elasticsearch.service.ElasticsearchSaveService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.stereotype.Service; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 新增 */ @Service public class ElasticsearchSaveServiceImp implements ElasticsearchSaveService { @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; /** * @param entities : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ @Override public <T> Iterable<T> save(Iterable<T> entities) { return elasticsearchRestTemplate.save(entities); } /** * @param t : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ @Override public <T> T save(T t) { return elasticsearchRestTemplate.save(t); } }
- 根据被ES注解引用的入参对象存入相应索引中
import com.it.mhh.elasticsearch.controller.ElasticsearchSaveController; import com.it.mhh.elasticsearch.entity.Headmaster; import com.it.mhh.elasticsearch.entity.Student; import com.it.mhh.elasticsearch.entity.Teacher; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.elasticsearch.core.completion.Completion; import org.springframework.test.context.junit4.SpringRunner; import java.util.*; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 测试 */ @SpringBootTest @RunWith(SpringRunner.class) public class ElasticsearchSaveControllerTest { @Autowired private ElasticsearchSaveController elasticsearchSaveController; /** * @param entities : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ @Test public void savesStudentES() { Headmaster headmaster = new Headmaster("1", "小白主任", "山东", 7500, Arrays.asList("一班", "二班"), new Date());//班主任 List<String> colorList = new ArrayList<>();//颜色 colorList.add("red"); colorList.add("white"); colorList.add("black"); List<Teacher> teacherList = new ArrayList<>();//所有科目老师 teacherList.add(new Teacher("2", "小黑", "black", "一班", "山东省济南市历下区", 13, new Date())); teacherList.add(new Teacher("2", "小蓝", "blue", "二班", "山东省菏泽市单县", 14, new Date())); Student student = new Student("1", "mhh", "济南", 12, new Date(), headmaster, new String[]{"语文", "数学", "英语"}, colorList, teacherList); Student save = elasticsearchSaveController.save(student); System.out.println(save); } /** * @param entities : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ @Test public void savesTeacherES() { Teacher teacher = new Teacher("1", "小黑老师", "black", "一班", "河北省保定市莲池区", 14, new Date()); Teacher save = elasticsearchSaveController.save(teacher); System.out.println(save); } /** * @param entities : 入参对象(必须是被@Document注解注释的)【入参 可传单个 T,集合Iterable<T>,可变参 T... 】 * @return T 反参对象 * @explain : 添加文档 * @Author Mhh * @Date 2021/12/27 10:55 */ @Test public void savesTeacherListES() { List<Teacher> teacherList = new ArrayList<>(); teacherList.add(new Teacher("1", "小黑老师", "black", "一班", "山东省泰安市岱岳区","且随疾风前行,身后亦须留心", 15, new Date(), new Completion(new String[]{"山东省泰安市岱岳区"}))); teacherList.add(new Teacher("2", "小白老师", "white", "二班", "山东省济南市历下区", "此剑之势,愈斩愈烈",17, new Date(), new Completion(new String[]{"山东省济南市历下区"}))); teacherList.add(new Teacher("3", "小黄老师", "yellow", "二班", "河北省保定市莲池区", "荣耀存于心,而非流于形",18, new Date(), new Completion(new String[]{"河北省保定市莲池区"}))); teacherList.add(new Teacher("5", "小蓝教授", "blue", "二班", "山东省济南市高新区", "吾之初心,永世不忘",21, new Date(), new Completion(new String[]{"山东省济南市高新区"}))); teacherList.add(new Teacher("4", "小绿教授", "green", "一班", "山西省太原市杏花岭区", "有些失误无法犯两次",24, new Date(), new Completion(new String[]{"山西省太原市杏花岭区"}))); Iterable<Teacher> save = elasticsearchSaveController.save(teacherList); System.out.println(save); } }
- deleteIndex :删除索引(数据库)
deleteIndex 删除索引测试
- 入参classType : 删除的哪个索引(从传入对象中的@Document注解中indexName属性获取)
import com.it.mhh.elasticsearch.service.ElasticsearchDeleteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
@创建人: Mhh
@创建时间: 2021/12/10
@描述: 删除类
*/
@RestController
@RequestMapping(“/elasticSearch/delete”)
public class ElasticsearchDeleteController {
@Autowired
private ElasticsearchDeleteService elasticsearchDeleteService;
/**
import org.springframework.data.elasticsearch.core.query.Query; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 查询 */ public interface ElasticsearchDeleteService { /** * @param clazz : 删除的哪个索引(从传入对象中的@Document注解中indexName属性获取) * @return java.lang.Boolean * @explain : 删除索引 * @Author Mhh * @Date 2021/12/27 14:27 */ public Boolean deleteIndex(Class<?> clazz); }
import com.it.mhh.elasticsearch.service.ElasticsearchDeleteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.stereotype.Service; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: */ @Service public class ElasticsearchDeleteServiceImp implements ElasticsearchDeleteService { @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; /** * @param clazz : 删除的哪个索引(从传入对象中的@Document注解中indexName属性获取) * @return java.lang.Boolean * @explain : 删除索引 * @Author Mhh * @Date 2021/12/27 14:27 */ public Boolean deleteIndex(Class<?> clazz) { return elasticsearchRestTemplate.deleteIndex(clazz); } }
- 根据入参对象 ES@Document注解中indexName属性值删除索引
- 如果删除的 索引名不存在 返回false
import com.it.mhh.elasticsearch.controller.ElasticsearchDeleteController; import com.it.mhh.elasticsearch.entity.Teacher; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermsQueryBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.test.context.junit4.SpringRunner; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: */ @SpringBootTest @RunWith(SpringRunner.class) public class ElasticsearchDeleteControllerTest { @Autowired private ElasticsearchDeleteController elasticsearchDeleteController; /** * @param clazz : 删除的哪个索引(从传入对象中的@Document注解中indexName属性获取) * @return java.lang.Boolean * @explain : 删除索引 * @Author Mhh * @Date 2021/12/27 14:27 */ @Test public void deleteIndex() { Boolean aBoolean = elasticsearchDeleteController.deleteIndex(Teacher.class); System.err.println(aBoolean); } }
- delete(Object entity):通过入参对象主键删除
- delete(String id, Class<> entityType) id表示要删除的主键,entityType表示 被@Document注解且有indexName属性值(indexName属性值为索引名)
delete(通过主键删除) 删除文档测试
- 两种入参形式 都是通过主键id删除,即使入参对象其它属性设置了值也是通过主键id删除
import com.it.mhh.elasticsearch.service.ElasticsearchDeleteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
@创建人: Mhh
@创建时间: 2021/12/10
@描述: 删除类
*/
@RestController
@RequestMapping(“/elasticSearch/delete”)
public class ElasticsearchDeleteController {
@Autowired
private ElasticsearchDeleteService elasticsearchDeleteService;
/**
/**
}
import org.springframework.data.elasticsearch.core.query.Query; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 查询 */ public interface ElasticsearchDeleteService { /** * @param id : 要删除的主键id * @param entityType : 删除的哪个索引的数据(从传入对象中的@Document注解中indexName属性获取) * @return java.lang.Boolean * @throws * @Author Mhh * @Date 2021/12/9 10:40 */ Boolean delete(String id, Class<?> entityType); /** * @param entity : 这个实体对象必须是被@Document注解且有indexName属性值) 以及主键必须有值,其它参数有无都没关系(和用主键id删除没区别) * @return java.lang.Boolean * @throws * @Author Mhh * @Date 2021/12/9 10:40 */ public Boolean delete(Object entity); }
import com.it.mhh.elasticsearch.service.ElasticsearchDeleteService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate; import org.springframework.data.elasticsearch.core.query.Query; import org.springframework.stereotype.Service; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: */ @Service public class ElasticsearchDeleteServiceImp implements ElasticsearchDeleteService { @Autowired private ElasticsearchRestTemplate elasticsearchRestTemplate; /** * @param id : 要删除的主键id * @param entityType : 删除的哪个索引的数据(从传入对象中的@Document注解中indexName属性获取) * @return java.lang.Boolean * @throws * @Author Mhh * @Date 2021/12/9 10:40 */ @Override public Boolean delete(String id, Class<?> entityType) { String delete = elasticsearchRestTemplate.delete(id, entityType); return true; } /** * @param entity : 这个实体对象必须是被@Document注解且有indexName属性值) 以及主键必须有值,其它参数有无都没关系(和用主键id删除没区别) * @return java.lang.Boolean * @throws * @Author Mhh * @Date 2021/12/9 10:40 */ @Override public Boolean delete(Object entity) { String delete = elasticsearchRestTemplate.delete(entity); return true; } }
- 根据入参对象 ES@Document注解中indexName属性值查询删除哪哥索引中文档
- 如果删除的指定索引名中的文档 索引名不存在 报错
- 即使删除的文档不存在 ES依旧返回删除的主键
import com.it.mhh.elasticsearch.controller.ElasticsearchDeleteController; import com.it.mhh.elasticsearch.entity.Teacher; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.index.query.TermsQueryBuilder; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.elasticsearch.core.query.NativeSearchQuery; import org.springframework.test.context.junit4.SpringRunner; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: */ @SpringBootTest @RunWith(SpringRunner.class) public class ElasticsearchDeleteControllerTest { @Autowired private ElasticsearchDeleteController elasticsearchDeleteController; /** * @param entity : 这个实体对象必须是被@Document注解且有indexName属性值) 以及主键必须有值,其它参数有无都没关系(和用主键id删除没区别) * @return java.lang.Boolean * @throws * @Author Mhh * @Date 2021/12/9 10:40 */ @Test public void deleteByIdES() { Teacher teacher = new Teacher(); teacher.setTId("3"); teacher.setTName("mhh");//没有用处,根据主键删除 Boolean delete = elasticsearchDeleteController.delete(teacher); //== Boolean aBoolean = elasticsearchDeleteController.delete("3", Teacher.class); System.err.println(aBoolean);//true } }
- delete(Query query, Class<> clazz, IndexCoordinates index)
query:查询语法 包含(term查询、terms查询、match查询、范围查询、模糊查询…)
clazz: 来指定查询字段和结果后返回的实例对象
indx: 指定索引
delete(删除通过query所搜索到的所有数据) 删除文档测试
- 删除掉被query所搜索到的所有数据。
import com.it.mhh.elasticsearch.service.ElasticsearchDeleteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.Req
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。