SpringBoot整合Elasticsearch7
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
需要指定版本号
<!-- elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>7.7.0</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>7.7.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
存储的对象
package com.ah.es.pojo;
public class Book {
private Integer bookId;
private String name;
public Book() {
}
public Book(Integer bookId, String name) {
this.bookId = bookId;
this.name = name;
}
@Override
public String toString() {
return "Book [bookId=" + bookId + ", name=" + name + "]";
}
public Integer getBookId() {
return bookId;
}
public void setBookId(Integer bookId) {
this.bookId = bookId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
EsEntity·Es保存的对象
package com.ah.es.util;
public final class EsEntity<T> {
private String id;
private T data;
public EsEntity() {
}
public EsEntity(String id, T data) {
this.data = data;
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
}
INDEX内容
src/main/resources/es.txt
{
"properties": {
"id":{
"type":"integer"
},
"bookId":{
"type":"integer"
},
"name":{
"type":"text",
"analyzer": "ik_max_word",
"search_analyzer": "ik_smart"
}
}
}
EsUtil·工具类
package com.ah.es.util;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.*;
import org.elasticsearch.action.search.*;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.*;
import org.elasticsearch.client.indices.*;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.reindex.*;
import org.elasticsearch.search.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.*;
import java.util.*;
@Component
public class EsUtil {
@Value("192.168.16.128")
public String host;
@Value("9200")
public int port;
@Value("http")
public String scheme;
public static final String INDEX_NAME = "book-index";
public static String CREATE_INDEX;
public static RestHighLevelClient restClient = null;
private static String readFileToString(String filePath) {
File file = new File(filePath);
System.out.println(file.getAbsolutePath());
try (FileReader reader = new FileReader(file)) {
BufferedReader bReader = new BufferedReader(reader);
StringBuilder sb = new StringBuilder();
String s = "";
while ((s = bReader.readLine()) != null) {
sb.append(s + "\n");
}
return sb.toString();
} catch (IOException e1) {
e1.printStackTrace();
}
return "";
}
@PostConstruct
public void init() {
CREATE_INDEX = readFileToString("src/main/resources/es.txt");
System.out.println("CREATE_INDEX = " + CREATE_INDEX);
try {
if (restClient != null) {
restClient.close();
}
restClient = new RestHighLevelClient(RestClient.builder(new HttpHost(host, port, scheme)));
if (this.indexExist(INDEX_NAME)) {
return;
}
CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 2));
request.mapping(CREATE_INDEX, XContentType.JSON);
CreateIndexResponse res = restClient.indices().create(request, RequestOptions.DEFAULT);
if (!res.isAcknowledged()) {
throw new RuntimeException("初始化失败");
}
} catch (Exception e) {
e.printStackTrace();
System.exit(0);
}
}
public boolean indexExist(String index) throws Exception {
GetIndexRequest request = new GetIndexRequest(index);
request.local(false);
request.humanReadable(true);
request.includeDefaults(false);
return restClient.indices().exists(request, RequestOptions.DEFAULT);
}
public IndexResponse insertOrUpdateOne(String index, EsEntity entity) {
IndexRequest request = new IndexRequest(index);
request.id(entity.getId());
request.source(JSON.toJSONString(entity.getData()), XContentType.JSON);
try {
return restClient.index(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public BulkResponse insertBatch(String index, List<EsEntity> list) {
BulkRequest request = new BulkRequest();
for (EsEntity item : list) {
String _json = JSON.toJSONString(item.getData());
String _id = item.getId();
IndexRequest indexRequest = new IndexRequest(index).id(_id).source(_json, XContentType.JSON);
request.add(indexRequest);
}
try {
return restClient.bulk(request, RequestOptions.DEFAULT);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T> List<T> search(String index, SearchSourceBuilder searchSourceBuilder, Class<T> resultClass) {
SearchRequest request = new SearchRequest(index);
request.source(searchSourceBuilder);
try {
SearchResponse response = restClient.search(request, RequestOptions.DEFAULT);
SearchHits hits1 = response.getHits();
SearchHit[] hits2 = hits1.getHits();
List<T> retList = new ArrayList<>(hits2.length);
for (SearchHit hit : hits2) {
String strJson = hit.getSourceAsString();
retList.add(JSON.parseObject(strJson, resultClass));
}
return retList;
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public AcknowledgedResponse deleteIndex(String index) {
try {
IndicesClient indicesClient = restClient.indices();
DeleteIndexRequest request = new DeleteIndexRequest(index);
AcknowledgedResponse response = indicesClient.delete(request, RequestOptions.DEFAULT);
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public BulkByScrollResponse deleteByQuery(String index, QueryBuilder builder) {
DeleteByQueryRequest request = new DeleteByQueryRequest(index);
request.setQuery(builder);
request.setBatchSize(10000);
request.setConflicts("proceed");
try {
BulkByScrollResponse response = restClient.deleteByQuery(request, RequestOptions.DEFAULT);
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public <T> BulkResponse deleteBatch(String index, Collection<T> idList) {
BulkRequest request = new BulkRequest();
for (T t : idList) {
request.add(new DeleteRequest(index, t.toString()));
}
try {
BulkResponse response = restClient.bulk(request, RequestOptions.DEFAULT);
return response;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
ES调用方
package com.ah.es;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.query.*;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.ah.es.pojo.Book;
import com.ah.es.util.*;
import java.util.*;
@Component
public class EsService {
@Autowired
private EsUtil esUtil;
public List<Book> getAll() {
return esUtil.search(EsUtil.INDEX_NAME, new SearchSourceBuilder(), Book.class);
}
public Book getByBookId(int bookId) {
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.query(new TermQueryBuilder("bookId", bookId));
List<Book> res = esUtil.search(EsUtil.INDEX_NAME, builder, Book.class);
if (res.size() > 0) {
return res.get(0);
} else {
return null;
}
}
public List<Book> searchByKey(String key) {
BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
boolQueryBuilder.must(QueryBuilders.matchQuery("name", key));
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.size(10).query(boolQueryBuilder);
return esUtil.search(EsUtil.INDEX_NAME, builder, Book.class);
}
public IndexResponse putOne(Book book) {
EsEntity<Book> entity = new EsEntity<>(book.getBookId() + "", book);
return esUtil.insertOrUpdateOne(EsUtil.INDEX_NAME, entity);
}
public BulkResponse putBatch(List<Book> books) {
List<EsEntity> list = new ArrayList<>();
books.forEach(item -> list.add(new EsEntity<>(item.getBookId() + "", item)));
return esUtil.insertBatch(EsUtil.INDEX_NAME, list);
}
public BulkByScrollResponse deleteById(int id) {
return esUtil.deleteByQuery(EsUtil.INDEX_NAME, new TermQueryBuilder("bookId", id));
}
public BulkResponse deleteBatch(List<Integer> list) {
return esUtil.deleteBatch(EsUtil.INDEX_NAME, list);
}
}
测试类
package com.ah.es;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
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.test.context.junit4.SpringRunner;
import com.ah.es.pojo.Book;
import java.util.ArrayList;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class EsTest {
@Autowired
private EsService bookService;
@Test
public void testAll() throws InterruptedException {
t1AddOne();
t2AddBatch();
Thread.sleep(1000);
t3FindAll();
t4search();
t5deleteOne();
t6deleteBatch();
Thread.sleep(1000);
t7FindAll();
}
@Test
public void t1AddOne() {
IndexResponse putOne = bookService.putOne(new Book(1, "西游记"));
System.out.println("【1】putOne:" + putOne);
}
@Test
public void t2AddBatch() {
List<Book> list = new ArrayList<>();
list.add(new Book(2, "水浒传"));
list.add(new Book(3, "三国演义"));
BulkResponse putBatch = bookService.putBatch(list);
System.out.println("【2】putBatch:" + putBatch.status());
}
@Test
public void t3FindAll() {
System.out.println("【3】");
List<Book> res = bookService.getAll();
System.out.println("↓↓↓findAll");
res.forEach(System.out::println);
System.out.println("↑↑↑findAll");
}
@Test
public void t4search() {
System.out.println("【4】");
List<Book> searchByKey = bookService.searchByKey("水传");
searchByKey.forEach(System.out::println);
Book book = bookService.getByBookId(2);
System.out.println("【4】getByBookId:" + book);
}
@Test
public void t5deleteOne() {
BulkByScrollResponse deleteById = bookService.deleteById(1);
System.out.println("【5】deleteById:" + deleteById.getStatus());
}
@Test
public void t6deleteBatch() {
List<Integer> ids = new ArrayList<>();
ids.add(2);
ids.add(3);
BulkResponse deleteBatch = bookService.deleteBatch(ids);
System.out.println("【6】deleteBatch:" + deleteBatch.status());
}
@Test
public void t7FindAll() {
System.out.println("【7】");
List<Book> res = bookService.getAll();
System.out.println("↓↓↓findAll");
res.forEach(System.out::println);
System.out.println("↑↑↑findAll");
}
}
运行结果:
【1】putOne:IndexResponse[index=book-index,type=_doc,id=1,version=5,result=created,seqNo=51,primaryTerm=1,shards={"total":3,"successful":1,"failed":0}]
【2】putBatch:OK
【3】
↓↓↓findAll
Book [bookId=2, name=水浒传]
Book [bookId=3, name=三国演义]
Book [bookId=1, name=西游记]
↑↑↑findAll
【4】
Book [bookId=2, name=水浒传]
【4】getByBookId:Book [bookId=2, name=水浒传]
【5】deleteById:BulkIndexByScrollResponse[sliceId=null,updated=0,created=0,deleted=1,batches=1,versionConflicts=0,noops=0,retries=0,throttledUntil=0s]
【6】deleteBatch:OK
【7】
↓↓↓findAll
↑↑↑findAll
SpringBoot整合Elasticsearch7的更多相关文章
- SpringBoot2.2.5整合ElasticSearch7.9.2
1:前言 为什么是SpringBoot2.2.5,不是其他的SpringBoot版本,原因有两个: 1:SpringBoot2.2.0以上才能支持ElasticSearch7.x版本. 2:Sprin ...
- Springboot整合ElasticSearch进行简单的测试及用Kibana进行查看
一.前言 搜索引擎还是在电商项目.百度.还有技术博客中广泛应用,使用最多的还是ElasticSearch,Solr在大数据量下检索性能不如ElasticSearch.今天和大家一起搭建一下,小编是看完 ...
- spring-boot整合mybatis(1)
sprig-boot是一个微服务架构,加快了spring工程快速开发,以及简便了配置.接下来开始spring-boot与mybatis的整合. 1.创建一个maven工程命名为spring-boot- ...
- SpringBoot整合Mybatis之项目结构、数据源
已经有好些日子没有总结了,不是变懒了,而是我一直在奋力学习springboot的路上,现在也算是完成了第一阶段的学习,今天给各位总结总结. 之前在网上找过不少关于springboot的教程,都是一些比 ...
- springboot整合mq接收消息队列
继上篇springboot整合mq发送消息队列 本篇主要在上篇基础上进行activiemq消息队列的接收springboot整合mq发送消息队列 第一步:新建marven项目,配置pom文件 < ...
- springboot整合mybaits注解开发
springboot整合mybaits注解开发时,返回json或者map对象时,如果一个字段的value为空,需要更改springboot的配置文件 mybatis: configuration: c ...
- SpringBoot整合Redis、ApachSolr和SpringSession
SpringBoot整合Redis.ApachSolr和SpringSession 一.简介 SpringBoot自从问世以来,以其方便的配置受到了广大开发者的青睐.它提供了各种starter简化很多 ...
- SpringBoot整合ElasticSearch实现多版本的兼容
前言 在上一篇学习SpringBoot中,整合了Mybatis.Druid和PageHelper并实现了多数据源的操作.本篇主要是介绍和使用目前最火的搜索引擎ElastiSearch,并和Spring ...
- SpringBoot整合Kafka和Storm
前言 本篇文章主要介绍的是SpringBoot整合kafka和storm以及在这过程遇到的一些问题和解决方案. kafka和storm的相关知识 如果你对kafka和storm熟悉的话,这一段可以直接 ...
随机推荐
- Ubuntu下创建apt源
1. 下载所需安装文件 sudo apt-get install soft name 安装并保存安装文件 或者 sudo apt-get source soft name 只下载安装文件 ...
- 排名靠前的几个JS框架发展趋势和前景
转载请注明出处:葡萄城官网,葡萄城为开发者提供专业的开发工具.解决方案和服务,赋能开发者.原文出处:https://blog.bitsrc.io/top-5-javascript-frameworks ...
- 《Head First 设计模式》:与设计模式相处
正文 一.设计原则 1.封装变化 找出应用中可能需要变化之处,把它们独立出来,不要和那些不需要变化的代码混在一起. 2.针对接口编程,不针对实现编程 "针对接口编程"真正的意思是& ...
- SourceTree安装及卸载
一.安装步骤 下载地址: 链接:https://pan.baidu.com/s/1K5ImZASuThJZoGLz6Ay_4g 提取码:hqkp 1. 点击安装包,点击下一步 2. 出现账户注册的页面 ...
- Java-GUI基础(一)
简介 首先,Java的学习就是不断学习一个个包与类的过程,对于GUI部分有两个核心包:java.awt与javax.swing, 这两个包可以说是涵盖了java的GUI部分所有的类(和他们的方法). ...
- Liquibase+SpringBoot的简单使用笔记!update+rollback
该笔记记录了springboot整合liquibase之后,如何根据liquibase ChangeLogFile对数据库进行修改以及回滚操作 参考: baeldung.com JHipster 1. ...
- MarkDown排版、多样的文本框
<战争与和平>一八一二年,俄.法两国再度交战,安德烈·保尔康斯基在战役中身受重伤,而俄军节节败退,眼见莫斯科将陷于敌人之手了.罗斯托夫将原本用来搬运家产的马车,改去运送伤兵,娜达莎方能于伤 ...
- PHP直播平台源码搭建教程
直播源码市场火爆,但是PHP直播平台源码的搭建过程较为复杂,本文就简单为大家概述一下直播的实现过程以及PHP直播平台源码是如何搭建的. 一.直播的定义 如今PHP直播平台源码绝大部分情况下是指在现场架 ...
- 记elementUI一个大坑
1. 表格中 用v-if 切换不同表字段时 表头字段顺序经常互换 解决方法:在table-column中加入:key="Math.random()"2. v-if控制的el-t ...
- Java工程师高薪训练营-第一阶段 开源框架源码解析-模块一 持久层框架涉及实现及MyBatis源码分析-任务一:自定义持久层框架
目录 任务一:自定义持久层框架 1.1 JDBC回顾及问题分析 1.2 自定义持久层框架思路分析 1.3 IPersistence_Test编写 1.3.1 XXXMapper.xml详解 1.3.2 ...