java(springboot)对接elasticsearch8+

1、pom引用

注:jackson包es只用到了databind,之所以全部引用是因为actuator用到了其他,只升级一个会 导致版本冲突

<!-- https://mvnrepository.com/artifact/co.elastic.clients/elasticsearch-java -->
<dependency><groupId>co.elastic.clients</groupId><artifactId>elasticsearch-java</artifactId><version>8.8.2</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.2</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.15.2</version>
</dependency>
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.15.2</version>
</dependency>
<dependency><groupId>jakarta.json</groupId><artifactId>jakarta.json-api</artifactId><version>2.1.2</version>
</dependency>

2、配置文件

注:因为没有用springboot自身的es插件所以健康检查检测不到es状态,关闭es检测

elasticsearch:host: 10.247.149.67port: 9200userName: elasticpassword: Zlens@2023
management:health:elasticsearch:enabled: false

3、连接池

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import com.alibaba.cloud.commons.lang.StringUtils;
import org.apache.http.Header;
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.apache.http.message.BasicHeader;
import org.elasticsearch.client.RestClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;@Configuration
public class ElasticSearchConfig {@Value("${elasticsearch.host}")private String host;@Value("${elasticsearch.port}")private Integer port;@Value("${elasticsearch.apiKey:}")private String apiKey;@Value("${elasticsearch.userName}")private String userName;@Value("${elasticsearch.password}")private String password;@Beanpublic ElasticsearchClient elasticsearchClient() {ElasticsearchTransport transport;RestClient restClient;if(StringUtils.isNotBlank(apiKey)){//apiKey验证模式restClient = RestClient.builder(new HttpHost(host, port)).setDefaultHeaders(new Header[]{new BasicHeader("Authorization", "ApiKey " + apiKey)}).build();}else{final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();// 账号密码验证模式credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(userName, password));restClient = RestClient.builder(new HttpHost(host, port)).setHttpClientConfigCallback(httpClientBuilder ->httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();}transport = new RestClientTransport(restClient, new JacksonJsonpMapper());ElasticsearchClient client = new ElasticsearchClient(transport);System.out.println("es初始化完成");return client;}
}

4、操作类

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.mapping.DateProperty;
import co.elastic.clients.elasticsearch._types.mapping.Property;
import co.elastic.clients.elasticsearch.core.BulkRequest;
import co.elastic.clients.elasticsearch.core.BulkResponse;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import co.elastic.clients.elasticsearch.core.bulk.BulkResponseItem;
import co.elastic.clients.elasticsearch.core.search.Hit;
import co.elastic.clients.transport.endpoints.BooleanResponse;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;@Service
@Log4j2
public class ElasticsearchService<T> {@Resourceprivate ElasticsearchClient elasticsearchClient;/*** 判断索引是否存在.** @param indexName index名称*/public boolean existIndex(String indexName) {try {BooleanResponse booleanResponse = elasticsearchClient.indices().exists(e -> e.index(indexName));return booleanResponse.value();} catch (IOException e) {log.error("向es中检测索引【{}】出错,错误信息为:{}", indexName, e.getMessage());throw new RuntimeException("向es中检测索引【"+indexName+"】出错");}}/*** 创建索引.** @param indexName index名称*/public void createIndex(String indexName) {try {Map<String, Property> documentMap = new HashMap<>();documentMap.put("createTime", Property.of(property ->property.date(DateProperty.of(dateProperty ->dateProperty.index(true).format("epoch_millis"))//textProperty.index(true)))));elasticsearchClient.indices().create(c -> c.index(indexName).mappings(mappings ->mappings.properties(documentMap)));} catch (IOException e) {log.error("向es中创建索引【{}】出错,错误信息为:{}", indexName, e.getMessage());}}/*** 添加记录.**/public void addDocument(T data, String indexName) {try {if (!this.existIndex(indexName)) {this.createIndex(indexName);}elasticsearchClient.index(i -> i.index(indexName).id(null).document(data));} catch (IOException e) {log.error("向es中添加document出错:{}", e.getMessage());}}/*** 批量添加.** @param dataList 添加的数量集合* @param indexName indexName*/public void batchAddDocument(List<T> dataList, String indexName) {if (!this.existIndex(indexName)) {this.createIndex(indexName);}BulkRequest.Builder br = new BulkRequest.Builder();dataList.forEach(data -> br.operations(op -> op.index(idx -> idx.index(indexName).id(null).document(data))));try {BulkResponse result = elasticsearchClient.bulk(br.build());if (result.errors()) {log.error("Bulk had errors");for (BulkResponseItem item : result.items()) {if (item.error() != null) {log.error(item.error().reason());}}}} catch (IOException e) {log.error("向es中添加document出错:{}",e.getMessage());}}/*** 根据索引名称和字段查询数据.** @param indexName 索引名称* @param filedValue 查询字段值* @param filedName 查询字段名称*/public List<T> findDataList(String indexName, String filedName, String filedValue,Class<T> className) {try {SearchResponse<T> searchResponse = elasticsearchClient.search(s -> s.index(indexName).query(q -> q.match(t -> t.field(filedName).query(filedValue))),className);List<Hit<T>> hitList = searchResponse.hits().hits();List<T> dataList = new ArrayList<>();for (Hit<T> mapHit : hitList) {dataList.add(mapHit.source());}return dataList;} catch (IOException e) {log.error("【查询 -> 失败】从es中查询分析后的日志出错,错误信息为:{}", e.getMessage());}return null;}
}

上边创建索引是定制的加了特殊mapping,正常这样

/*** 创建索引.** @param indexName index名称*/public void createIndex(String indexName) {try {elasticsearchClient.indices().create(c -> c.index(indexName));} catch (IOException e) {log.error("向es中创建索引【{}】出错,错误信息为:{}", indexName, e.getMessage());}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/7031.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

七大排序算法和计数排序

文章目录 一、直接插入排序二、希尔排序三、直接选择排序四、堆排序五、冒泡排序六、快速排序6.1递归实现快速排序6.2非递归实现快速排序 七、归并排序7.1递归实现归并排序7.2非递归实现归并排序 八、计数排序 以下排序以从小到大排序为例 一、直接插入排序 时间复杂度&#x…

文章审核之敏感词过滤

技术选型 DFA实现原理 DFA全称为&#xff1a;Deterministic Finite Automaton,即确定有穷自动机。 存储&#xff1a;一次性的把所有的敏感词存储到了多个map中&#xff0c;就是下图表示这种结构 敏感词&#xff1a;冰毒、大麻、大坏蛋 工具类 最下面的main方法是测试用的&a…

Java版本电子招标采购系统源代码—企业战略布局下的采购寻源

智慧寻源 多策略、多场景寻源&#xff0c;多种看板让寻源过程全程可监控&#xff0c;根据不同采购场景&#xff0c;采取不同寻源策略&#xff0c; 实现采购寻源线上化管控&#xff1b;同时支持公域和私域寻源。 询价比价 全程线上询比价&#xff0c;信息公开透明&#xff0c;可…

微信小程序-地图上的图标计算旋转值朝向经纬度计算

废话不多说&#xff0c;开整 // 参数为寄件人经纬度和收件人经纬度 // 根据寄收件人经纬度弧度π进行rotate旋转计算 const getRotate (po1, po2) > {if (!(po1 && po2)) return 0const lng_a po1.longitudeconst lat_a po1.latitudeconst lng_b po2.longitud…

MySQL使用

目录 1 MySQL的登录 1.1 服务的启动和终止 1.2 自带客户端的登录与退出 2 MySQL演示使用 2.1 MySQL的使用演示 2.2 MySQL的编码设置 1 MySQL的登录 1.1 服务的启动和终止 MySQL安装完毕以后&#xff0c;需要启动服务器进程&#xff0c;不然客户端无法连接数据库。 在前面…

vue-cli项目中,使用webpack-bundle-analyzer进行模块分析,查看各个模块的体积,方便后期代码优化

一、安装 npm install --save-dev webpack-bundle-analyzer 二、在vue.config.js中配置 const BundleAnalyzerPlugin require(webpack-bundle-analyzer).BundleAnalyzerPlugin plugins: [new BundleAnalyzerPlugin({analyzerMode: server,analyzerHost: 127.0.0.1,analyze…

Word2Vec实现文本识别分类

深度学习训练营之使用Word2Vec实现文本识别分类 原文链接环境介绍前言前置工作设置GPU数据查看构建数据迭代器 Word2Vec的调用生成数据批次和迭代器模型训练初始化拆分数据集并进行训练 预测 原文链接 &#x1f368; 本文为&#x1f517;365天深度学习训练营 中的学习记录博客&…

探析国内数字孪生引擎技术现状

在数字孪生软件来发中&#xff0c;渲染引擎是一个关键点&#xff0c;国内大多数字孪生平台引擎通常使用的是自研的渲染引擎或者采用开源的渲染引擎。下面通过一些常见的渲染引擎在国内数字孪生引擎中的应用带大家了解数字孪生软件开发的方式。 自研渲染引擎&#xff1a;许多数…

HTTPS安全套接字层超文本传输协议

HTTPS安全套接字层超文本传输协议 HTTPS简介HTTPS和HTTP的主要区别客户端在使用HTTPS方式与Web服务器通信时的步骤SSL/TLS协议的加密&#xff08;握手&#xff09;过程为什么数据传输阶段使用对称加密HTTPS 的优点HTTPS 的缺点HTTPS 的优化证书优化会话复用 HTTPS简介 HTTP协议…

文件包含漏洞利用思路

简介 通过PHP函数引入文件时&#xff0c;传入的文件名没有经过合理的验证&#xff0c;从而操作了预想之外的文件&#xff0c;导致意外的文件泄漏甚至恶意代码注入。 常见的文件包含函数 php中常见的文件包含函数有以下四种&#xff1a; include()require()include_once()re…

海外服务器推荐:国外高性能服务器免费

对于寻找高性能的海外服务器&#xff0c;海外服务器推荐指导&#xff0c;我建议您考虑以下因素&#xff1a; 1. 可靠性和性能&#xff1a;选择信誉良好、可靠性好的服务器提供商。它们应该有稳定的网络基础设施和高性能的服务器硬件来满足您的需求。 2. 位置选择&#xff1a;…

苍穹外卖day05——Redis(被病毒入侵)+店铺营业状态设置

Redis被病毒入侵了 数据删光光然后只剩这四个玩意&#xff0c;乱下东西乱删东西&#xff0c;还好是docker部署&#xff0c;不然就寄了。 在服务器上部署redis记得一定要设置密码&#xff0c;不然被人扫肉鸡注入病毒整个服务器给你崩掉。 使用配置类的方式搭建相关程序 配置数…

医生出国访问交流,为什么要趁早申请访问学者?

在当前国内&#xff0c;有这样一类医生群体&#xff0c;他们四十岁上下&#xff0c;就职于国内大型三甲医院&#xff0c;受过良好教育&#xff0c;事业辉煌&#xff0c;属于是别人眼中的精英阶层&#xff0c;然而&#xff0c;随着岁月的沉淀&#xff0c;副高级别医生群体的人生…

实现简单Spring基于XML的配置程序

定义一个容器&#xff0c;使用ConcurrentHashMap 做为单例对象的容器 先解析beans.xml得到第一个bean对象的信息&#xff0c;id&#xff0c;class&#xff0c;属性和属性值使用反射生成对象&#xff0c;并赋值将创建好的bean对象放入到singletonObjects集合中提供getBean(id)方…

Java实现根据商品ID获取1688商品详情数据方法

要通过1688的API获取商品详情数据&#xff0c;您可以使用1688开放平台提供的接口来实现。以下是一种使用Java编程语言实现的示例&#xff0c;展示如何通过1688开放平台API获取商品详情&#xff1a; 首先&#xff0c;确保您已注册成为1688开放平台的开发者&#xff0c;并创建一…

【Redis】剖析RDB和AOF持久化原理

文章目录 前言1、AOF日志1.1、概述1.2、日志文件1.3、写回策略1.4、策略实现原理1.5、重写机制1.6、AOF 后台重写1.6.1、介绍1.6.2、实现原理 1.7、优缺点 2、RDB快照2.1、概述2.2、实现方式2.3、实现原理2.4、极端情况2.5、优缺点 3、混合体实现4、大Key问题4.1、何为大key4.2…

profinet 调试记录

一、 树莓派运行codesys runtime 1. 用户名称要以 root 登录 若是普通用户&#xff0c;会提示&#xff1a;脚本必须以 root 身份运行 2. codesys报错&#xff1a; 在树莓派config.txt文件添加&#xff1a;arm_64bit0 3. 扫描设备需开启PLC 图标变红&#xff0c;则开启成…

【MATLAB第58期】基于MATLAB的PCA-Kmeans、PCA-LVQ与BP神经网络分类预测模型对比

【MATLAB第58期】基于MATLAB的PCA-Kmeans、PCA-LVQ与BP神经网络分类预测模型对比 一、数据介绍 基于UCI葡萄酒数据集进行葡萄酒分类及产地预测 共包含178组样本数据&#xff0c;来源于三个葡萄酒产地&#xff0c;每组数据包含产地标签及13种化学元素含量&#xff0c;即已知类…

Python组合模式介绍、使用方法

一、Python组合模式介绍 概念&#xff1a; 组合模式(Composite Pattern)是一种结构型设计模式&#xff0c;它通过将对象组合成树状结构来表示“整体/部分”层次结构&#xff0c;让客户端可以以相同的方式处理单个对象和组合对象。 功能&#xff1a; 统一对待组合对象和叶子对…

STM32H5开发(1)----总览

STM32H5开发----1.总览 概述样品申请STM32H5-2MB 框图产品列表STM32H5-2MB 框图STM32H5-128KB框图功能对比STM32H5-128KB vs H5-2MB组员对比STM32H5 亮点 概述 STM32H5系列微控制器是意法半导体公司推出的一款高性能MCU, CortexM33内核的微控制器产品。 他和STM32F2、F4、F7、…