ElasticSearch7.3.2-RestHighLevelClient实战

2023-12-03 12:58

本文主要是介绍ElasticSearch7.3.2-RestHighLevelClient实战,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

一、项目依赖

既然我们server安装7.3.2,那么我们客户端选择同样版本,高版本提供了更高层的api抽象封装。

<!--引入es -->
<dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.3.2</version>
</dependency><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.3.2</version>
</dependency>

二、项目配置

  • application.properties配置
spring.elasticsearch.nodes=10.143.228.25:9200,10.143.228.26:9200,10.143.228.128:9200
spring.elasticsearch.username=elastic
spring.elasticsearch.password=elastic
  • config bean 配置
import com.google.common.collect.Lists;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;import java.util.Arrays;
import java.util.List;/*** @description: elasticSearch配置* @Date : 2020/5/14 上午11:37* @Author : 石冬冬-Seig Heil*/
@Configuration
public class ElasticSearchConfig{/*** 使用的协议*/final static String schema = "http";/*** 连接超时时间*/final static int connectTimeOut = 1000;/*** 连接超时时间*/final static int socketTimeOut = 30000;/*** 获取连接的超时时间*/final static int connectionRequestTimeOut = 500;/*** 最大连接数*/final static int maxConnectNum = 100;/*** 最大路由连接数*/final static int maxConnectPerRoute = 100;@Value("${spring.elasticsearch.nodes}")String[] nodes;@Value("${spring.elasticsearch.username}")String username;@Value("${spring.elasticsearch.password}")String password;@Bean(name = "restHighLevelClient")public RestHighLevelClient client() {RestClientBuilder builder = RestClient.builder(hostList().toArray(new HttpHost[0]));final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials(username, password));builder.setHttpClientConfigCallback(httpClientBuilder -> {httpClientBuilder.disableAuthCaching();return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);});// 异步httpclient连接延时配置builder.setRequestConfigCallback(requestConfigBuilder -> {requestConfigBuilder.setConnectTimeout(connectTimeOut);requestConfigBuilder.setSocketTimeout(socketTimeOut);requestConfigBuilder.setConnectionRequestTimeout(connectionRequestTimeOut);return requestConfigBuilder;});// 异步httpclient连接数配置builder.setHttpClientConfigCallback(httpClientBuilder -> {httpClientBuilder.setMaxConnTotal(maxConnectNum);httpClientBuilder.setMaxConnPerRoute(maxConnectPerRoute);return httpClientBuilder;});return new RestHighLevelClient(builder);}List<HttpHost> hostList(){List<HttpHost> nodeList = Lists.newArrayList();Arrays.asList(nodes).stream().forEach(each -> {String[] array = each.split(":");nodeList.add(new HttpHost(array[0],Integer.valueOf(array[1]),schema));});return nodeList;}
}

三、示例介绍

3.1、创建索引

settings是修改分片和副本数的,mappings是修改字段和类型的。

@ApiOperation(value = "createIndex", notes = "createIndex")
@PostMapping("/createIndex/{indexName}")
public Result createIndex(@PathVariable String indexName, @RequestBody Map<String,Map<String,Object>> config) {try {CreateIndexRequest createIndexRequest = new CreateIndexRequest(indexName);createIndexRequest.settings(config.get("settings"));createIndexRequest.mapping(config.get("mapping"));CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);return Result.suc(JSONObject.toJSON(createIndexResponse));} catch (IOException e) {log.error("[createIndex]",e);return Result.fail(e);}
}

3.2、判断索引是否存在

public boolean exists(String index) {boolean exists;try {GetIndexRequest getIndexRequest = new GetIndexRequest(index);getIndexRequest.humanReadable(true);exists = client.indices().exists(getIndexRequest, DEFAULT);} catch (IOException e) {log.error("[ElasticSearch]exists,index={}",index, e);throw new RuntimeException("[ElasticSearch]exists异常");}return exists;
}

3.3、删除索引

public boolean deleteIndex(String... indices) {boolean acknowledged;try {DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(indices);AcknowledgedResponse delete = client.indices().delete(deleteIndexRequest,DEFAULT);acknowledged = delete.isAcknowledged();} catch (IOException e) {log.error("[ElasticSearch]deleteIndex,indices={}", JSON.toJSONString(indices), e);throw new RuntimeException("[ElasticSearch]deleteIndex异常");}return acknowledged;
}

3.4、插入文档

@ApiOperation(value = "insertRecord", notes = "insertRecord")
@PostMapping("/insertRecord/{indexName}")
public Result insertRecord(@RequestBody Map<String,Object> param, @PathVariable String indexName) {IndexRequest indexRequest = new IndexRequest(indexName);String userJson = JSONObject.toJSONString(param);indexRequest.source(userJson, XContentType.JSON);try {IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);if (response != null) {ReplicationResponse.ShardInfo shardInfo = response.getShardInfo();if (shardInfo.getTotal() != shardInfo.getSuccessful()) {log.info("shardInfo={}", JSONObject.toJSON(shardInfo));}// 如果有分片副本失败,可以获得失败原因信息if (shardInfo.getFailed() > 0) {for (ReplicationResponse.ShardInfo.Failure failure : shardInfo.getFailures()) {String reason = failure.reason();log.info("副本失败原因,reason={}",reason);}}}return Result.suc(JSONObject.toJSON(response));} catch (IOException e) {log.info("[insertRecord]",e);return Result.fail(e);}
}

3.5、批量插入文档

@ApiOperation(value = "bulkInsertRecord", notes = "bulkInsertRecord")
@PostMapping("/bulkInsertRecord/{indexName}")
public Result bulkInsertRecord(@RequestBody List<Map<String,Object>> batch, @PathVariable String indexName) {BulkRequest bulkRequest = new BulkRequest();batch.forEach(each -> {IndexRequest indexRequest = new IndexRequest(indexName).source(each, XContentType.JSON);bulkRequest.add(indexRequest);});//同步try {BulkResponse response = client.bulk(bulkRequest,RequestOptions.DEFAULT);return Result.suc(JSONObject.toJSON(response));} catch (IOException e) {log.info("[updateRecord]",e);return Result.fail(e);}
}

3.6、更新文档

@ApiOperation(value = "updateRecord", notes = "updateRecord")
@PostMapping("/updateRecord/{indexName}")
public Result updateRecord(@PathVariable String indexName, @RequestParam String id,@RequestBody Map<String,Object> param) {UpdateRequest updateRequest = new UpdateRequest(indexName,id);updateRequest.doc(param);try {UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);return Result.suc(JSONObject.toJSON(response));} catch (IOException e) {log.info("[updateRecord]",e);return Result.fail(e);}
}

3.7、删除文档

@ApiOperation(value = "deleteRecord", notes = "deleteRecord")
@GetMapping("deleteRecord/{indexName}")
public Result deleteRecord(@RequestParam String id, @PathVariable String indexName) {DeleteRequest deleteRequest = new DeleteRequest(indexName);deleteRequest.id(id);try {DeleteResponse response = client.delete(deleteRequest, RequestOptions.DEFAULT);return Result.suc(JSONObject.toJSON(response));} catch (IOException e) {log.info("[updateRecord]",e);return Result.fail(e);}
}

3.8、查询文档

ApiOperation(value = "queryRecord", notes = "queryRecord")
@GetMapping("/queryRecord/{indexName}")
public Result queryRecord(@PathVariable String indexName) {SearchRequest searchRequest = new SearchRequest(indexName);SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();//如果用name直接查询,其实是匹配name分词过后的索引查到的记录(倒排索引);如果用name.keyword查询则是不分词的查询,正常查询到的记录RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("birthday").from("1991-01-01").to("2010-10-10").format("yyyy-MM-dd");//范围查询
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("name.keyword", name);//精准查询PrefixQueryBuilder prefixQueryBuilder = QueryBuilders.prefixQuery("name.keyword", "张");//前缀查询
//        WildcardQueryBuilder wildcardQueryBuilder = QueryBuilders.wildcardQuery("name.keyword", "*三");//通配符查询
//        FuzzyQueryBuilder fuzzyQueryBuilder = QueryBuilders.fuzzyQuery("name", "三");//模糊查询FieldSortBuilder fieldSortBuilder = SortBuilders.fieldSort("age");//按照年龄排序fieldSortBuilder.sortMode(SortMode.MIN);//从小到大排序BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();boolQueryBuilder.must(rangeQueryBuilder).should(prefixQueryBuilder);//and or  查询sourceBuilder.query(boolQueryBuilder).sort(fieldSortBuilder);//多条件查询sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));searchRequest.source(sourceBuilder);try {SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);SearchHits hits = response.getHits();JSONArray jsonArray = new JSONArray();for (SearchHit hit : hits) {String sourceAsString = hit.getSourceAsString();JSONObject jsonObject = JSON.parseObject(sourceAsString);jsonArray.add(jsonObject);}return Result.suc();} catch (IOException e) {e.printStackTrace();return Result.suc();}
}

3.9、查询文档

通过封装QueryForm对象实现查询

@ApiOperation(value = "queryCondition", notes = "queryCondition")
@PostMapping("/queryCondition/{indexName}")
public Result queryCondition(@PathVariable String indexName,@RequestBody QueryForm form) {try {SearchRequest searchRequest = new SearchRequest(indexName);searchRequest.source(form.searchSourceBuilder());SearchResponse response = client.search(searchRequest, RequestOptions.DEFAULT);SearchHits hits = response.getHits();JSONArray jsonArray = new JSONArray();for (SearchHit hit : hits) {String sourceAsString = hit.getSourceAsString();JSONObject jsonObject = JSON.parseObject(sourceAsString);jsonArray.add(jsonObject);}return Result.suc(jsonArray);} catch (IOException e) {return Result.suc();}
}@Data
static class QueryForm {private Integer id;private String age;private String name;private String address;private String birthday;private String birthdayRange;private String ageRange;SearchSourceBuilder searchSourceBuilder(){SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();if(id != null){sourceBuilder.query(QueryBuilders.termQuery("id", id));}if(name != null){sourceBuilder.query(QueryBuilders.termQuery("name", id));}if(age != null){sourceBuilder.query(QueryBuilders.termQuery("age", id));}if(address != null){sourceBuilder.query(QueryBuilders.termQuery("address", id));}if(birthday != null){sourceBuilder.query(QueryBuilders.termQuery("birthday", id));}if(birthdayRange != null){String[] array = birthdayRange.split("-");sourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("birthday").from(array[0]).to(array[1]).format("yyyy-MM-dd")));}if(ageRange != null){String[] array = ageRange.split("-");sourceBuilder.query(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("age").from(array[0]).to(array[1])));}return sourceBuilder;}
}

3.10、源码

源码地址:

https://gitee.com/suze/springBoot/blob/master/src/main/java/org/suze/springboot/elasticsearch/controller/ElasticSearchController.java

源码下载:

git clone https://gitee.com/suze/springBoot

下面的是我的公众号二维码图片,欢迎关注。
秋夜无霜

这篇关于ElasticSearch7.3.2-RestHighLevelClient实战的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/449530

相关文章

Golang使用minio替代文件系统的实战教程

《Golang使用minio替代文件系统的实战教程》本文讨论项目开发中直接文件系统的限制或不足,接着介绍Minio对象存储的优势,同时给出Golang的实际示例代码,包括初始化客户端、读取minio对... 目录文件系统 vs Minio文件系统不足:对象存储:miniogolang连接Minio配置Min

Node.js 中 http 模块的深度剖析与实战应用小结

《Node.js中http模块的深度剖析与实战应用小结》本文详细介绍了Node.js中的http模块,从创建HTTP服务器、处理请求与响应,到获取请求参数,每个环节都通过代码示例进行解析,旨在帮... 目录Node.js 中 http 模块的深度剖析与实战应用一、引言二、创建 HTTP 服务器:基石搭建(一

网页解析 lxml 库--实战

lxml库使用流程 lxml 是 Python 的第三方解析库,完全使用 Python 语言编写,它对 XPath表达式提供了良好的支 持,因此能够了高效地解析 HTML/XML 文档。本节讲解如何通过 lxml 库解析 HTML 文档。 pip install lxml lxm| 库提供了一个 etree 模块,该模块专门用来解析 HTML/XML 文档,下面来介绍一下 lxml 库

性能分析之MySQL索引实战案例

文章目录 一、前言二、准备三、MySQL索引优化四、MySQL 索引知识回顾五、总结 一、前言 在上一讲性能工具之 JProfiler 简单登录案例分析实战中已经发现SQL没有建立索引问题,本文将一起从代码层去分析为什么没有建立索引? 开源ERP项目地址:https://gitee.com/jishenghua/JSH_ERP 二、准备 打开IDEA找到登录请求资源路径位置

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

滚雪球学Java(87):Java事务处理:JDBC的ACID属性与实战技巧!真有两下子!

咦咦咦,各位小可爱,我是你们的好伙伴——bug菌,今天又来给大家普及Java SE啦,别躲起来啊,听我讲干货还不快点赞,赞多了我就有动力讲得更嗨啦!所以呀,养成先点赞后阅读的好习惯,别被干货淹没了哦~ 🏆本文收录于「滚雪球学Java」专栏,专业攻坚指数级提升,助你一臂之力,带你早日登顶🚀,欢迎大家关注&&收藏!持续更新中,up!up!up!! 环境说明:Windows 10

springboot实战学习(1)(开发模式与环境)

目录 一、实战学习的引言 (1)前后端的大致学习模块 (2)后端 (3)前端 二、开发模式 一、实战学习的引言 (1)前后端的大致学习模块 (2)后端 Validation:做参数校验Mybatis:做数据库的操作Redis:做缓存Junit:单元测试项目部署:springboot项目部署相关的知识 (3)前端 Vite:Vue项目的脚手架Router:路由Pina:状态管理Eleme

深度学习实战:如何利用CNN实现人脸识别考勤系统

1. 何为CNN及其在人脸识别中的应用 卷积神经网络(CNN)是深度学习中的核心技术之一,擅长处理图像数据。CNN通过卷积层提取图像的局部特征,在人脸识别领域尤其适用。CNN的多个层次可以逐步提取面部的特征,最终实现精确的身份识别。对于考勤系统而言,CNN可以自动从摄像头捕捉的视频流中检测并识别出员工的面部。 我们在该项目中采用了 RetinaFace 模型,它基于CNN的结构实现高效、精准的

项目实战系列三: 家居购项目 第四部分

购物车 🌳购物车🍆显示购物车🍆更改商品数量🍆清空购物车&&删除商品 🌳生成订单 🌳购物车 需求分析 1.会员登陆后, 可以添加家居到购物车 2.完成购物车的设计和实现 3.每添加一个家居,购物车的数量+1, 并显示 程序框架图 1.新建src/com/zzw/furns/entity/CartItem.java, CartItem-家居项模型 /***

Birt报表开发实战

我就截图描述得了,没什么含金量,看图基本明白的。 1.开始 a.创建报表文件 b.数据源配置 c.配置数据集 2.网格报表 拖拉式操作,很方便 3.预览效果 其他报表的操作也基本不难,就不扯了! 2.级联参数 官方视频教程:http://demo.actuate.com/demos/cascade/cascade.html