irpas技术客

SpringBoot之ElasticsearchRestTemplate常用示例_孟浩浩_elasticsearchresttemplate

大大的周 4645

目录 1.引入pom依赖2.application 配置3.JavaBean配置以及ES相关注解3.1 Student实体类3.2 Teacher实体类3.3 Headmaster 实体类 4. 启动类配置5.elasticsearchRestTemplate 新增==5.1 createIndex && putMapping 创建索引及映射==5.1.1 Controller层5.1.2 service层5.1.3 serviceimpl层createIndex && putMapping 创建索引及映射测试结果: ==5.2 save 添加文档==5.2.1 Controller层5.2.2 service层5.2.3 serviceimpl层save 添加文档测试结果: 6.elasticsearchRestTemplate 删除==6.1 deleteIndex 删除索引==6.1.1 Controller层6.1.2 service层6.1.3 serviceimpl层deleteIndex 删除索引测试结果: ==6.2 delete 删除文档(通过主键删除)==6.2.1 Controller层6.2.2 service层6.2.3 serviceimpl层delete(通过主键删除) 删除文档测试结果: ==6.3 delete 删除文档(删除通过query所搜索到的所有数据)==6.3.1 Controller层6.3.2 service层6.3.3 serviceimpl层delete(删除通过query所搜索到的所有数据) 删除文档测试结果: 7.elasticsearchRestTemplate 修改==7.1 update 修改文档(根据主键修改)==7.1.1 Controller层7.1.2 service层7.1.3 serviceimpl层update 修改文档(根据主键修改)测试结果: 8.elasticsearchRestTemplate 查询==8.1 get 查询文档(根据主键查询)==8.1.1 Controller层8.1.2 service层8.1.3 serviceimpl层get 查询文档(根据主键查询)测试结果: ==8.2 exists 查询文档(判断主键id是否存在)==8.2.1 Controller层8.2.2 service层8.2.3 serviceimpl层exists 查询文档(判断主键id是否存在)测试结果: ==8.3 queryForPage 查询文档(分页查询)==8.3.1 Controller层8.3.2 service层8.3.3 serviceimpl层queryForPage 查询文档(分页查询)测试结果: ==8.4 AnalyzeRequest (根据入参内容返回分词后结果)==8.4.1 Controller层8.4.2 service层8.4.3 serviceimpl层AnalyzeRequest (根据入参内容返回分词后结果)测试结果: ==8.5 termQuery 查询文档(入参不分词,精确匹配)==8.5.1 Controller层8.5.2 service层8.5.3 serviceimpl层termQuery 查询文档(入参不分词,精确匹配)测试结果: ==8.6 match 查询文档(会对查询条件进行分词)==8.6.1 Controller层8.6.2 service层8.6.3 serviceimpl层match 查询文档(会对查询条件进行分词)测试结果: ==8.7 matchAllQuery 查询文档(查询此索引下所有文档)==8.7.1 Controller层8.7.2 service层8.7.3 serviceimpl层matchAllQuery 查询文档(查询此索引下所有文档)测试结果: ==8.8 wildcardQuery 查询文档(模糊查询)==8.8.1 Controller层8.8.2 service层8.8.3 serviceimpl层wildcardQuery 查询文档(模糊查询)测试结果: ==8.9 prefixQuery 查询文档(前缀查询)==8.9.1 Controller层8.9.2 service层8.9.3 serviceimpl层prefixQuery 查询文档(前缀查询)测试结果: ==8.10 regexpQuery 查询文档(正则表达式查询)==8.10.1 Controller层8.10.2 service层8.10.3 serviceimpl层regexpQuery 查询文档(正则表达式查询) 测试结果: ==8.11 rangeQuery 查询文档(范围查询)==8.11.1 Controller层8.11.2 service层8.11.3 serviceimpl层rangeQuery 查询文档(范围查询) 测试结果: ==8.12 Sort 查询文档 (排序)==8.12.1 Controller层8.12.2 service层8.12.3 serviceimpl层Sort 查询文档 (排序) 测试结果: ==8.13 queryStringQuery 查询文档 (多条件查询 一值多域)==8.13.1 Controller层8.13.2 service层8.13.3 serviceimpl层queryStringQuery 查询文档 (多条件查询 一值多域) 测试结果: ==8.14 boolQuery 查询文档 (对多个查询条件连接。连接方式:must)==8.14.1 Controller层8.14.2 service层8.14.3 serviceimpl层boolQuery 查询文档 (对多个查询条件连接。连接方式:must) 测试结果: ==8.15 boolQuery 查询文档 (对多个查询条件连接。连接方式:filter)==8.15.1 Controller层8.15.2 service层8.15.3 serviceimpl层boolQuery 查询文档 (对多个查询条件连接。连接方式:filter) 测试结果: ==8.16 boolQuery 查询文档 (对多个查询条件连接。连接方式:must_not)==8.16.1 Controller层8.16.2 service层8.16.3 serviceimpl层boolQuery 查询文档 (对多个查询条件连接。连接方式:must_not) 测试结果: ==8.17 boolQuery 查询文档 (对多个查询条件连接。连接方式:should)==8.17.1 Controller层8.17.2 service层8.17.3 serviceimpl层boolQuery 查询文档 (对多个查询条件连接。连接方式:should) 测试结果: ==8.18 HighlightBuilder 查询文档 (高亮)==8.18.1 Controller层8.18.2 service层8.18.3 serviceimpl层HighlightBuilder 查询文档 (高亮) 测试结果: ==8.19 AggregationBuilders 查询文档 (聚合查询)==8.19.1 Controller层8.19.2 service层8.19.3 serviceimpl层AggregationBuilders 查询文档 (聚合查询) 测试结果: ==8.20 SuggestBuilders查询文档 (completionSuggestion---搜索建议补全)==8.20.1 Controller层8.20.2 service层8.20.3 serviceimpl层SuggestBuilders查询文档 (completionSuggestion---搜索建议补全) 测试结果: ==8.21 SuggestBuilders查询文档 (termSuggestion---纠错补全)==8.21.1 Controller层8.21.2 service层8.21.3 serviceimpl层SuggestBuilders查询文档 (termSuggestion---纠错补全) 测试结果: ==~~8.22 SuggestBuilders查询文档 (phraseSuggestion---纠错补全)~~==~~8.22.1 Controller层~~~~8.22.2 service层~~~~8.22.3 serviceimpl层~~~~SuggestBuilders查询文档 (termSuggestion---纠错补全) 测试结果:~~ 链接:[windows版本 Elasticsearch服务端-7.4.0以及kibana-7.4.0和ik分词器下载地址](https://mp.csdn.net/mp_download/manage/download/UpDetailed)链接:[SpringBoot之ElasticsearchRestTemplate常用示例 源代码下载地址](https://download.csdn.net/download/JAVA_MHH/72555390)

1.引入pom依赖 主要引用 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>
2.application 配置 spring: elasticsearch: rest: uris: 127.0.0.1:9200 #---ES的连接地址,多个地址用逗号分隔 username: #---用户名 password: #---密码 connection-timeout: 1000 #---连接超时时间(默认1s) read-timeout: 1000 #---读取超时时间(默认30s)
3.JavaBean配置以及ES相关注解 注解:@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://·blogs.com/Alexephor/p/11408446.html(Elasticsearch之建议器suggester)写的很详细 * 词条建议器(term suggester)对用户搜索的内容做纠正帮助用户搜索到精确度高的关键字 * * @param fieldName : 从fieldName字段中获取候选建议的字段。这是一个必需的选项,需要全局设置或根据建议设置。Keyword字段 * @param text : 建议文本,建议文本是必需的选项,可以通过全局(多个建议器中查询相同的内容)或者按照单个建议器的格式来。 * @param classType : 返回的list里的对象并且通过对象里面@Document注解indexName属性获取查询哪个索引 * @return java.util.List<java.lang.String> * @explain : 词条建议器(term suggester)主要做纠正 但是是短语就不能做了(Keyword字段) * // 用在查询用户中心查询人名上 * // 例如:查询 孟浩号 而在字段中是孟浩浩 则就建议返回了 孟浩浩 * @Author Mhh * @Date 2021/12/23 15:40 */ @PostMapping("termSuggestion") public List<String> termSuggestion(String fieldName, String text, Class<?> classType) { return elasticsearchSelectService.termSuggestion(fieldName, text, classType); } }
8.21.2 service层 import org.elasticsearch.client.indices.AnalyzeResponse; import org.elasticsearch.index.query.Operator; import org.springframework.data.domain.Sort; import java.io.IOException; import java.util.List; import java.util.Map; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 查询 */ public interface ElasticsearchSelectService { /** * https://·blogs.com/Alexephor/p/11408446.html(Elasticsearch之建议器suggester)写的很详细 * 词条建议器(term suggester)对用户搜索的内容做纠正帮助用户搜索到精确度高的关键字 * * @param fieldName : 从fieldName字段中获取候选建议的字段。这是一个必需的选项,需要全局设置或根据建议设置。Keyword字段 * @param text : 建议文本,建议文本是必需的选项,可以通过全局(多个建议器中查询相同的内容)或者按照单个建议器的格式来。 * @param classType : 返回的list里的对象并且通过对象里面@Document注解indexName属性获取查询哪个索引 * @return java.util.List<java.lang.String> * @explain : 词条建议器(term suggester)主要做纠正 但是是短语就不能做了(Keyword字段) * // 用在查询用户中心查询人名上 * // 例如:查询 孟浩号 而在字段中是孟浩浩 则就建议返回了 孟浩浩 * @Author Mhh * @Date 2021/12/23 15:40 */ public List<String> termSuggestion(String fieldName, String text, Class<?> classType) { //定义反参容器 List<String> stringList = new ArrayList<>(); // 构建纠正词条对象 词条建议器(只要是词,短的 比如姓名) TermSuggestionBuilder termSuggestionBuilder = SuggestBuilders.termSuggestion(fieldName).text(text); /* termSuggestionBuilder.suggestMode(TermSuggestionBuilder.SuggestMode.ALWAYS);/*建议模式(控制提供建议词的方式): 1. missing:默认方式,仅在‘要搜索词项’不在索引中存在时,才提供建议词; 2. popular:仅提供频率比‘要搜索词项’高的建议词; 3. always:总是提供建议词;*/ termSuggestionBuilder.sort(SortBy.SCORE); /*建议词的排序方式: 1. score:先按评分排序,再按文档频率、term顺序排; 2. frequency:先按文档频率排序,再按评分、term顺序排*/ //创建搜索提示对象 进行封装词条纠正 SuggestBuilder suggestBuilder = new SuggestBuilder(); // termSuggestionBuilder:随便起的搜索补全的名字(后面会用到) suggestBuilder.addSuggestion("termSuggestionBuilder", termSuggestionBuilder); //查询,获取查询结果 SearchResponse searchResponse = elasticsearchRestTemplate.suggest(suggestBuilder, IndexCoordinates.of(classType.getAnnotation(Document.class).indexName())); //获取反参中的词条纠正结果 Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestionBuilder = searchResponse.getSuggest().getSuggestion("termSuggestionBuilder"); // 处理返回 List<String> suggests = suggestionBuilder.getEntries().stream().map(x -> x.getOptions().stream().map(y -> y.getText().toString()).collect(Collectors.toList())).findFirst().get(); // 将词条纠正内容保存到容器返回 for (String suggest : suggests) { stringList.add(suggest); System.err.println("suggest = " + suggest); } return stringList; } }
SuggestBuilders查询文档 (termSuggestion—纠错补全) 测试结果: 对用户搜索的内容做纠正帮助用户搜索到精确度高的关键字 import com.it.mhh.elasticsearch.controller.ElasticsearchSelectController; import com.it.mhh.elasticsearch.entity.Student; import com.it.mhh.elasticsearch.entity.Teacher; import org.elasticsearch.client.indices.AnalyzeResponse; import org.elasticsearch.index.query.Operator; 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.domain.Sort; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.*; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: */ @SpringBootTest @RunWith(SpringRunner.class) public class ElasticsearchSelectControllerTest { @Autowired private ElasticsearchSelectController elasticsearchSelectController;//es的查询 /** * https://·blogs.com/Alexephor/p/11408446.html(Elasticsearch之建议器suggester)写的很详细 * 词组建议器(phraseSuggestion) * * @param fieldName : 从fieldName字段中获取候选建议的字段。这是一个必需的选项,需要全局设置或根据建议设置。Keyword字段 * @param text : 建议文本,建议文本是必需的选项,可以通过全局(多个建议器中查询相同的内容)或者按照单个建议器的格式来。 * @param classType : 返回的list里的对象并且通过对象里面@Document注解indexName属性获取查询哪个索引 * @return java.util.List<java.lang.String> * @explain : 词组建议器(phraseSuggestion)适合较长的字段,但是也不是万能的 做纠正(Keyword字段) * @Author Mhh * @Date 2021/12/23 15:40 */ @PostMapping("phraseSuggestion") public List<String> phraseSuggestion(String fieldName, String text, Class<?> classType) { return elasticsearchSelectService.phraseSuggestion(fieldName, text, classType); } }
8.22.2 service层 import org.elasticsearch.client.indices.AnalyzeResponse; import org.elasticsearch.index.query.Operator; import org.springframework.data.domain.Sort; import java.io.IOException; import java.util.List; import java.util.Map; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: 查询 */ public interface ElasticsearchSelectService { /** * https://·blogs.com/Alexephor/p/11408446.html(Elasticsearch之建议器suggester)写的很详细 * 词组建议器(phraseSuggestion) * * @param fieldName : 从fieldName字段中获取候选建议的字段。这是一个必需的选项,需要全局设置或根据建议设置。Keyword字段 * @param text : 建议文本,建议文本是必需的选项,可以通过全局(多个建议器中查询相同的内容)或者按照单个建议器的格式来。 * @param classType : 返回的list里的对象并且通过对象里面@Document注解indexName属性获取查询哪个索引 * @return java.util.List<java.lang.String> * @explain : 词组建议器(phraseSuggestion)适合较长的字段,但是也不是万能的 做纠正(Keyword字段) * @Author Mhh * @Date 2021/12/23 15:40 */ public List<String> phraseSuggestion(String fieldName, String text, Class<?> classType) { //定义反参容器 List<String> stringList = new ArrayList<>(); // 构建纠正词组对象 PhraseSuggestionBuilder phraseSuggestionBuilder = SuggestBuilders.phraseSuggestion(fieldName).text(text); //创建搜索提示对象 进行封装词条纠正 SuggestBuilder suggestBuilder = new SuggestBuilder(); // phraseSuggestionBuilder:随便起的搜索补全的名字(后面会用到) suggestBuilder.addSuggestion("phraseSuggestion", phraseSuggestionBuilder); //查询,获取查询结果 SearchResponse searchResponse = elasticsearchRestTemplate.suggest(suggestBuilder, IndexCoordinates.of(classType.getAnnotation(Document.class).indexName())); //获取反参中的词条纠正结果 Suggest.Suggestion<? extends Suggest.Suggestion.Entry<? extends Suggest.Suggestion.Entry.Option>> suggestionBuilder = searchResponse.getSuggest().getSuggestion("phraseSuggestion"); // 处理 返回 List<String> suggests = suggestionBuilder.getEntries().stream().map(x -> x.getOptions().stream().map(y -> y.getText().toString()).collect(Collectors.toList())).findFirst().get(); // 将词条纠正内容保存到容器返回 for (String suggest : suggests) { stringList.add(suggest); System.err.println("suggest = " + suggest); } return stringList; } }
SuggestBuilders查询文档 (termSuggestion—纠错补全) 测试结果: 适合较长的字段,但是也不是万能的 做纠正 import com.it.mhh.elasticsearch.controller.ElasticsearchSelectController; import com.it.mhh.elasticsearch.entity.Student; import com.it.mhh.elasticsearch.entity.Teacher; import org.elasticsearch.client.indices.AnalyzeResponse; import org.elasticsearch.index.query.Operator; 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.domain.Sort; import org.springframework.test.context.junit4.SpringRunner; import java.io.IOException; import java.util.*; /** * @创建人: Mhh * @创建时间: 2021/12/10 * @描述: */ @SpringBootTest @RunWith(SpringRunner.class) public class ElasticsearchSelectControllerTest { @Autowired private ElasticsearchSelectController elasticsearchSelectController;//es的查询 /** * https://·/Alexephor/p/11408446.html(Elasticsearch之建议器suggester)写的很详细 * 词组建议器(phraseSuggestion) * * @param fieldName : 从fieldName字段中获取候选建议的字段。这是一个必需的选项,需要全局设置或根据建议设置。Keyword字段 * @param text : 建议文本,建议文本是必需的选项,可以通过全局(多个建议器中查询相同的内容)或者按照单个建议器的格式来。 * @param classType : 返回的list里的对象并且通过对象里面@Document注解indexName属性获取查询哪个索引 * @return java.util.List<java.lang.String> * @explain : 词组建议器(phraseSuggestion)适合较长的字段,但是也不是万能的 做纠正(Keyword字段) * @Author Mhh * @Date 2021/12/23 15:40 */ @Test public void phraseSuggestion() { List<String> stringList = elasticsearchSelectController.phraseSuggestion( "tFamous", "吾之初心永世不完", Teacher.class); stringList.forEach(System.err::println); } }
链接:windows版本 Elasticsearch服务端-7.4.0以及kibana-7.4.0和ik分词器下载地址 链接:SpringBoot之ElasticsearchRestTemplate常用示例 源代码下载地址


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #Student实体类32 #Teacher实体类33 #Headmaster #实体类1引入pom依赖主要引用