SpringBoot连接ElasticSearch有以下种方式,

  • TransportClient,9300端口,在 7.x 中已经被弃用,据说在8.x 中将完全删除
  • restClient,9200端口,
  • high level client,新推出的连接方式,基于restClient。使用的版本需要保持和ES服务端的版本一致。

Spring boot 2的spring-boot-starter-data-elasticsearch支持的Elasticsearch版本是2.X,

Elasticsearch已迭代到7.X.X版本,建议使用high-level-client进行链接。

pom.xml

需要指定版本号

  1. <!-- elasticsearch -->
  2. <dependency>
  3. <groupId>org.elasticsearch</groupId>
  4. <artifactId>elasticsearch</artifactId>
  5. <version>7.7.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>org.elasticsearch.client</groupId>
  9. <artifactId>elasticsearch-rest-high-level-client</artifactId>
  10. <version>7.7.0</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.alibaba</groupId>
  14. <artifactId>fastjson</artifactId>
  15. <version>1.2.56</version>
  16. </dependency>

存储的对象

  1. package com.ah.es.pojo;
  2. public class Book {
  3. private Integer bookId;
  4. private String name;
  5. public Book() {
  6. }
  7. public Book(Integer bookId, String name) {
  8. this.bookId = bookId;
  9. this.name = name;
  10. }
  11. @Override
  12. public String toString() {
  13. return "Book [bookId=" + bookId + ", name=" + name + "]";
  14. }
  15. public Integer getBookId() {
  16. return bookId;
  17. }
  18. public void setBookId(Integer bookId) {
  19. this.bookId = bookId;
  20. }
  21. public String getName() {
  22. return name;
  23. }
  24. public void setName(String name) {
  25. this.name = name;
  26. }
  27. }

EsEntity·Es保存的对象

  1. package com.ah.es.util;
  2. public final class EsEntity<T> {
  3. private String id;
  4. private T data;
  5. public EsEntity() {
  6. }
  7. public EsEntity(String id, T data) {
  8. this.data = data;
  9. this.id = id;
  10. }
  11. public String getId() {
  12. return id;
  13. }
  14. public void setId(String id) {
  15. this.id = id;
  16. }
  17. public T getData() {
  18. return data;
  19. }
  20. public void setData(T data) {
  21. this.data = data;
  22. }
  23. }

INDEX内容

src/main/resources/es.txt

  1. {
  2. "properties": {
  3. "id":{
  4. "type":"integer"
  5. },
  6. "bookId":{
  7. "type":"integer"
  8. },
  9. "name":{
  10. "type":"text",
  11. "analyzer": "ik_max_word",
  12. "search_analyzer": "ik_smart"
  13. }
  14. }
  15. }

EsUtil·工具类

  1. package com.ah.es.util;
  2. import com.alibaba.fastjson.JSON;
  3. import org.apache.http.HttpHost;
  4. import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
  5. import org.elasticsearch.action.bulk.*;
  6. import org.elasticsearch.action.delete.DeleteRequest;
  7. import org.elasticsearch.action.index.*;
  8. import org.elasticsearch.action.search.*;
  9. import org.elasticsearch.action.support.master.AcknowledgedResponse;
  10. import org.elasticsearch.client.*;
  11. import org.elasticsearch.client.indices.*;
  12. import org.elasticsearch.common.settings.Settings;
  13. import org.elasticsearch.common.xcontent.XContentType;
  14. import org.elasticsearch.index.query.QueryBuilder;
  15. import org.elasticsearch.index.reindex.*;
  16. import org.elasticsearch.search.*;
  17. import org.elasticsearch.search.builder.SearchSourceBuilder;
  18. import org.springframework.beans.factory.annotation.Value;
  19. import org.springframework.stereotype.Component;
  20. import javax.annotation.PostConstruct;
  21. import java.io.*;
  22. import java.util.*;
  23. @Component
  24. public class EsUtil {
  25. @Value("192.168.16.128")
  26. public String host;
  27. @Value("9200")
  28. public int port;
  29. @Value("http")
  30. public String scheme;
  31. public static final String INDEX_NAME = "book-index";
  32. public static String CREATE_INDEX;
  33. public static RestHighLevelClient restClient = null;
  34. private static String readFileToString(String filePath) {
  35. File file = new File(filePath);
  36. System.out.println(file.getAbsolutePath());
  37. try (FileReader reader = new FileReader(file)) {
  38. BufferedReader bReader = new BufferedReader(reader);
  39. StringBuilder sb = new StringBuilder();
  40. String s = "";
  41. while ((s = bReader.readLine()) != null) {
  42. sb.append(s + "\n");
  43. }
  44. return sb.toString();
  45. } catch (IOException e1) {
  46. e1.printStackTrace();
  47. }
  48. return "";
  49. }
  50. @PostConstruct
  51. public void init() {
  52. CREATE_INDEX = readFileToString("src/main/resources/es.txt");
  53. System.out.println("CREATE_INDEX = " + CREATE_INDEX);
  54. try {
  55. if (restClient != null) {
  56. restClient.close();
  57. }
  58. restClient = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, scheme)));
  59. if (this.indexExist(INDEX_NAME)) {
  60. return;
  61. }
  62. CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
  63. request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 2));
  64. request.mapping(CREATE_INDEX, XContentType.JSON);
  65. CreateIndexResponse res = restClient.indices().create(request, RequestOptions.DEFAULT);
  66. if (!res.isAcknowledged()) {
  67. throw new RuntimeException("初始化失败");
  68. }
  69. } catch (Exception e) {
  70. e.printStackTrace();
  71. System.exit(0);
  72. }
  73. }
  74. public boolean indexExist(String index) throws Exception {
  75. GetIndexRequest request = new GetIndexRequest(index);
  76. request.local(false);
  77. request.humanReadable(true);
  78. request.includeDefaults(false);
  79. return restClient.indices().exists(request, RequestOptions.DEFAULT);
  80. }
  81. public IndexResponse insertOrUpdateOne(String index, EsEntity entity) {
  82. IndexRequest request = new IndexRequest(index);
  83. request.id(entity.getId());
  84. request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
  85. try {
  86. return restClient.index(request, RequestOptions.DEFAULT);
  87. } catch (Exception e) {
  88. throw new RuntimeException(e);
  89. }
  90. }
  91. public BulkResponse insertBatch(String index, List<EsEntity> list) {
  92. BulkRequest request = new BulkRequest();
  93. for (EsEntity item : list) {
  94. String _json = JSON.toJSONString(item.getData());
  95. String _id = item.getId();
  96. IndexRequest indexRequest = new IndexRequest(index).id(_id).source(_json, XContentType.JSON);
  97. request.add(indexRequest);
  98. }
  99. try {
  100. return restClient.bulk(request, RequestOptions.DEFAULT);
  101. } catch (Exception e) {
  102. throw new RuntimeException(e);
  103. }
  104. }
  105. public <T> List<T> search(String index, SearchSourceBuilder searchSourceBuilder, Class<T> resultClass) {
  106. SearchRequest request = new SearchRequest(index);
  107. request.source(searchSourceBuilder);
  108. try {
  109. SearchResponse response = restClient.search(request, RequestOptions.DEFAULT);
  110. SearchHits hits1 = response.getHits();
  111. SearchHit[] hits2 = hits1.getHits();
  112. List<T> retList = new ArrayList<>(hits2.length);
  113. for (SearchHit hit : hits2) {
  114. String strJson = hit.getSourceAsString();
  115. retList.add(JSON.parseObject(strJson, resultClass));
  116. }
  117. return retList;
  118. } catch (Exception e) {
  119. e.printStackTrace();
  120. throw new RuntimeException(e);
  121. }
  122. }
  123. public AcknowledgedResponse deleteIndex(String index) {
  124. try {
  125. IndicesClient indicesClient = restClient.indices();
  126. DeleteIndexRequest request = new DeleteIndexRequest(index);
  127. AcknowledgedResponse response = indicesClient.delete(request, RequestOptions.DEFAULT);
  128. return response;
  129. } catch (Exception e) {
  130. throw new RuntimeException(e);
  131. }
  132. }
  133. public BulkByScrollResponse deleteByQuery(String index, QueryBuilder builder) {
  134. DeleteByQueryRequest request = new DeleteByQueryRequest(index);
  135. request.setQuery(builder);
  136. request.setBatchSize(10000);
  137. request.setConflicts("proceed");
  138. try {
  139. BulkByScrollResponse response = restClient.deleteByQuery(request, RequestOptions.DEFAULT);
  140. return response;
  141. } catch (Exception e) {
  142. throw new RuntimeException(e);
  143. }
  144. }
  145. public <T> BulkResponse deleteBatch(String index, Collection<T> idList) {
  146. BulkRequest request = new BulkRequest();
  147. for (T t : idList) {
  148. request.add(new DeleteRequest(index, t.toString()));
  149. }
  150. try {
  151. BulkResponse response = restClient.bulk(request, RequestOptions.DEFAULT);
  152. return response;
  153. } catch (Exception e) {
  154. throw new RuntimeException(e);
  155. }
  156. }
  157. }

ES调用方

  1. package com.ah.es;
  2. import org.elasticsearch.action.bulk.BulkResponse;
  3. import org.elasticsearch.action.index.IndexResponse;
  4. import org.elasticsearch.index.query.*;
  5. import org.elasticsearch.index.reindex.BulkByScrollResponse;
  6. import org.elasticsearch.search.builder.SearchSourceBuilder;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.stereotype.Component;
  9. import com.ah.es.pojo.Book;
  10. import com.ah.es.util.*;
  11. import java.util.*;
  12. @Component
  13. public class EsService {
  14. @Autowired
  15. private EsUtil esUtil;
  16. public List<Book> getAll() {
  17. return esUtil.search(EsUtil.INDEX_NAME, new SearchSourceBuilder(), Book.class);
  18. }
  19. public Book getByBookId(int bookId) {
  20. SearchSourceBuilder builder = new SearchSourceBuilder();
  21. builder.query(new TermQueryBuilder("bookId", bookId));
  22. List<Book> res = esUtil.search(EsUtil.INDEX_NAME, builder, Book.class);
  23. if (res.size() > 0) {
  24. return res.get(0);
  25. } else {
  26. return null;
  27. }
  28. }
  29. public List<Book> searchByKey(String key) {
  30. BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
  31. boolQueryBuilder.must(QueryBuilders.matchQuery("name", key));
  32. SearchSourceBuilder builder = new SearchSourceBuilder();
  33. builder.size(10).query(boolQueryBuilder);
  34. return esUtil.search(EsUtil.INDEX_NAME, builder, Book.class);
  35. }
  36. public IndexResponse putOne(Book book) {
  37. EsEntity<Book> entity = new EsEntity<>(book.getBookId() + "", book);
  38. return esUtil.insertOrUpdateOne(EsUtil.INDEX_NAME, entity);
  39. }
  40. public BulkResponse putBatch(List<Book> books) {
  41. List<EsEntity> list = new ArrayList<>();
  42. books.forEach(item -> list.add(new EsEntity<>(item.getBookId() + "", item)));
  43. return esUtil.insertBatch(EsUtil.INDEX_NAME, list);
  44. }
  45. public BulkByScrollResponse deleteById(int id) {
  46. return esUtil.deleteByQuery(EsUtil.INDEX_NAME, new TermQueryBuilder("bookId", id));
  47. }
  48. public BulkResponse deleteBatch(List<Integer> list) {
  49. return esUtil.deleteBatch(EsUtil.INDEX_NAME, list);
  50. }
  51. }

测试类

  1. package com.ah.es;
  2. import org.elasticsearch.action.bulk.BulkResponse;
  3. import org.elasticsearch.action.index.IndexResponse;
  4. import org.elasticsearch.index.reindex.BulkByScrollResponse;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.boot.test.context.SpringBootTest;
  9. import org.springframework.test.context.junit4.SpringRunner;
  10. import com.ah.es.pojo.Book;
  11. import java.util.ArrayList;
  12. import java.util.List;
  13. @RunWith(SpringRunner.class)
  14. @SpringBootTest
  15. public class EsTest {
  16. @Autowired
  17. private EsService bookService;
  18. @Test
  19. public void testAll() throws InterruptedException {
  20. t1AddOne();
  21. t2AddBatch();
  22. Thread.sleep(1000);
  23. t3FindAll();
  24. t4search();
  25. t5deleteOne();
  26. t6deleteBatch();
  27. Thread.sleep(1000);
  28. t7FindAll();
  29. }
  30. @Test
  31. public void t1AddOne() {
  32. IndexResponse putOne = bookService.putOne(new Book(1, "西游记"));
  33. System.out.println("【1】putOne:" + putOne);
  34. }
  35. @Test
  36. public void t2AddBatch() {
  37. List<Book> list = new ArrayList<>();
  38. list.add(new Book(2, "水浒传"));
  39. list.add(new Book(3, "三国演义"));
  40. BulkResponse putBatch = bookService.putBatch(list);
  41. System.out.println("【2】putBatch:" + putBatch.status());
  42. }
  43. @Test
  44. public void t3FindAll() {
  45. System.out.println("【3】");
  46. List<Book> res = bookService.getAll();
  47. System.out.println("↓↓↓findAll");
  48. res.forEach(System.out::println);
  49. System.out.println("↑↑↑findAll");
  50. }
  51. @Test
  52. public void t4search() {
  53. System.out.println("【4】");
  54. List<Book> searchByKey = bookService.searchByKey("水传");
  55. searchByKey.forEach(System.out::println);
  56. Book book = bookService.getByBookId(2);
  57. System.out.println("【4】getByBookId:" + book);
  58. }
  59. @Test
  60. public void t5deleteOne() {
  61. BulkByScrollResponse deleteById = bookService.deleteById(1);
  62. System.out.println("【5】deleteById:" + deleteById.getStatus());
  63. }
  64. @Test
  65. public void t6deleteBatch() {
  66. List<Integer> ids = new ArrayList<>();
  67. ids.add(2);
  68. ids.add(3);
  69. BulkResponse deleteBatch = bookService.deleteBatch(ids);
  70. System.out.println("【6】deleteBatch:" + deleteBatch.status());
  71. }
  72. @Test
  73. public void t7FindAll() {
  74. System.out.println("【7】");
  75. List<Book> res = bookService.getAll();
  76. System.out.println("↓↓↓findAll");
  77. res.forEach(System.out::println);
  78. System.out.println("↑↑↑findAll");
  79. }
  80. }

运行结果:

  1. 1putOneIndexResponse[index=book-index,type=_doc,id=1,version=5,result=created,seqNo=51,primaryTerm=1,shards={"total":3,"successful":1,"failed":0}]
  2. 2putBatchOK
  3. 3
  4. ↓↓↓findAll
  5. Book [bookId=2, name=水浒传]
  6. Book [bookId=3, name=三国演义]
  7. Book [bookId=1, name=西游记]
  8. ↑↑↑findAll
  9. 4
  10. Book [bookId=2, name=水浒传]
  11. 4getByBookIdBook [bookId=2, name=水浒传]
  12. 5deleteByIdBulkIndexByScrollResponse[sliceId=null,updated=0,created=0,deleted=1,batches=1,versionConflicts=0,noops=0,retries=0,throttledUntil=0s]
  13. 6deleteBatchOK
  14. 7
  15. ↓↓↓findAll
  16. ↑↑↑findAll

SpringBoot整合Elasticsearch7的更多相关文章

  1. SpringBoot2.2.5整合ElasticSearch7.9.2

    1:前言 为什么是SpringBoot2.2.5,不是其他的SpringBoot版本,原因有两个: 1:SpringBoot2.2.0以上才能支持ElasticSearch7.x版本. 2:Sprin ...

  2. Springboot整合ElasticSearch进行简单的测试及用Kibana进行查看

    一.前言 搜索引擎还是在电商项目.百度.还有技术博客中广泛应用,使用最多的还是ElasticSearch,Solr在大数据量下检索性能不如ElasticSearch.今天和大家一起搭建一下,小编是看完 ...

  3. spring-boot整合mybatis(1)

    sprig-boot是一个微服务架构,加快了spring工程快速开发,以及简便了配置.接下来开始spring-boot与mybatis的整合. 1.创建一个maven工程命名为spring-boot- ...

  4. SpringBoot整合Mybatis之项目结构、数据源

    已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...

  5. springboot整合mq接收消息队列

    继上篇springboot整合mq发送消息队列 本篇主要在上篇基础上进行activiemq消息队列的接收springboot整合mq发送消息队列 第一步:新建marven项目,配置pom文件 < ...

  6. springboot整合mybaits注解开发

    springboot整合mybaits注解开发时,返回json或者map对象时,如果一个字段的value为空,需要更改springboot的配置文件 mybatis: configuration: c ...

  7. SpringBoot整合Redis、ApachSolr和SpringSession

    SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...

  8. SpringBoot整合ElasticSearch实现多版本的兼容

    前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...

  9. SpringBoot整合Kafka和Storm

    前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接 ...

随机推荐

  1. Ubuntu下创建apt源

    1. 下载所需安装文件 sudo apt-get install soft name  安装并保存安装文件 或者 sudo apt-get source soft name      只下载安装文件 ...

  2. 排名靠前的几个JS框架发展趋势和前景

    转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者.原文出处:https://blog.bitsrc.io/top-5-javascript-frameworks ...

  3. 《Head First 设计模式》:与设计模式相处

    正文 一.设计原则 1.封装变化 找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起. 2.针对接口编程,不针对实现编程 "针对接口编程"真正的意思是& ...

  4. SourceTree安装及卸载

    一.安装步骤 下载地址: 链接:https://pan.baidu.com/s/1K5ImZASuThJZoGLz6Ay_4g 提取码:hqkp 1. 点击安装包,点击下一步 2. 出现账户注册的页面 ...

  5. Java-GUI基础(一)

    简介 首先,Java的学习就是不断学习一个个包与类的过程,对于GUI部分有两个核心包:java.awt与javax.swing, 这两个包可以说是涵盖了java的GUI部分所有的类(和他们的方法). ...

  6. Liquibase+SpringBoot的简单使用笔记!update+rollback

    该笔记记录了springboot整合liquibase之后,如何根据liquibase ChangeLogFile对数据库进行修改以及回滚操作 参考: baeldung.com JHipster 1. ...

  7. MarkDown排版、多样的文本框

    <战争与和平>一八一二年,俄.法两国再度交战,安德烈·保尔康斯基在战役中身受重伤,而俄军节节败退,眼见莫斯科将陷于敌人之手了.罗斯托夫将原本用来搬运家产的马车,改去运送伤兵,娜达莎方能于伤 ...

  8. PHP直播平台源码搭建教程

    直播源码市场火爆,但是PHP直播平台源码的搭建过程较为复杂,本文就简单为大家概述一下直播的实现过程以及PHP直播平台源码是如何搭建的. 一.直播的定义 如今PHP直播平台源码绝大部分情况下是指在现场架 ...

  9. 记elementUI一个大坑

    1.  表格中 用v-if 切换不同表字段时  表头字段顺序经常互换 解决方法:在table-column中加入:key="Math.random()"2. v-if控制的el-t ...

  10. Java工程师高薪训练营-第一阶段 开源框架源码解析-模块一 持久层框架涉及实现及MyBatis源码分析-任务一:自定义持久层框架

    目录 任务一:自定义持久层框架 1.1 JDBC回顾及问题分析 1.2 自定义持久层框架思路分析 1.3 IPersistence_Test编写 1.3.1 XXXMapper.xml详解 1.3.2 ...