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熟悉的话,这一段可以直接 ...
随机推荐
- webpack学习遇到大坑(纯属自己记录)
分清webpack1与webpack2区别 1.webpack2的loader不能使用简写了,否则会报如下的错 正确如下: 2.node-sass安装失败,无法下载:Cannot download h ...
- Redis---07主从复制(哨兵模式)
一.什么是哨兵模式 基于主从复制的一般模式(一主二从)下,当发生主机发生宕机时,会通过流言协议判断主机是不是宕机,是的话则会通过投票协议自动把某一个从机转换成主机. 二.设置哨兵模式的配置文件 通过r ...
- 【转】Liunx常用命令详解
Liuux命令查询入口 Linux命令 - 系统信息 命令代码 注释说明 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 ...
- kubectl命令小妙招
kubectl命令使用大全 中文: http://docs.kubernetes.org.cn/683.html [root@master-test ~]# kubectl --help kube ...
- RocketMQ4.7.1双主双从集群搭建
导读 上一集我们已经学会了SpringBoot整合RocketMQ点我直达,今天我们来搭建双主双从高性能MQ服务集群. 简介 主从架构 Broker角色,Master提供读写,Slave只支持读,Co ...
- 4G DTU无线数据透明传输终端
4G DTU是基于4G网络的远程无线数据透明传输终端,是一种物联网无线数据传输设备,使用公用运营商的4G网络为用户提供无线远距离数据传输功能,使用工业级32位的高性能通信处理器和工业级无线模块,以嵌入 ...
- Scipy 学习第3篇:数字向量的距离计算
计算两个数字向量u和v之间的距离函数 1,欧氏距离(Euclidean distance) 在数学中,欧几里得距离或欧几里得度量是欧几里得空间中两点间"普通"(即直线)距离.使用这 ...
- Unity报错:xxx AnimationEvent has no function name specified!
参考:https://blog.csdn.net/register_man/article/details/54172778 在开发时出现了题目中的错误且有动画掉帧的情况,搜索后发现是在动画编辑器中我 ...
- C++语言学习之STL 的组成
STL有三大核心部分:容器(Container).算法(Algorithms).迭代器(Iterator),容器适配器(container adaptor),函数对象(functor),除此之外还有S ...
- SpringBoot第五集:整合Druid和MyBatis(2020最新最易懂)
SpringBoot第五集:整合Druid和MyBatis(2020最新最易懂) 1.SpringBoot整合Druid Druid是阿里巴巴的一个开源项目,是一个数据库连接池的实现,结合了C3P0. ...