Java链接elasticsearch8.14.1

项目需求,需要实现海量数据的聚合、查询。因为职业生涯开发使用springboot微服务架构、Java开发的方式,所以,项目前期准备了elasticsearch、kibana、logstash的集群环境,作为服务端,用于数据的收集、存储;但是特定的客户端应用开发,依然沿用springboot微服务架构,采用java Api Client链接elastisearch ,实现数据查询、用户管理等相关定制功能。

本例讲解springboot架构访问elasticsearch。

一、maven依赖

<dependency>

<groupId>co.elastic.clients</groupId>

<artifactId>elasticsearch-java</artifactId>

<version>8.14.3</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-core</artifactId>

<version>2.17.0</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.17.0</version>

</dependency>

二、elastic search生成API KEY

前文讲解,服务端集成了elasticsearch8.14.1、kibana-8.14.1及Logstash-8.14.1,我们利用kibana的UI界面生成api key,为java对接做准备,如下图所示:

三、Java测试

Java版本要求8版本以上

public class EStest {

public static void main(String\[\] args) throws ElasticsearchException, IOException {

// URL and API key

String serverUrl = "http://192.168.225.3:9200";

String apiKey = "SUdLUjNaQUJUNFNVcVJpUmhfLXE6R1dienJhUU9SWmlseGNKQTM3WjM1dw==";

// Create the low-level client

RestClient restClient = RestClient

.builder(HttpHost.create(serverUrl))

.setDefaultHeaders(new Header\[\]{

new BasicHeader("Authorization", "ApiKey " + apiKey)

})

.build();

// Create the transport with a Jackson mapper

ElasticsearchTransport transport = new RestClientTransport(

restClient, new JacksonJsonpMapper());

// And create the API client

ElasticsearchClient esClient = new ElasticsearchClient(transport);

//要判断是否存在当前索引库

//判断索引是否已经存在

//创建一个对象用来传递索引名

GetIndexRequest existsRequest = new GetIndexRequest();

existsRequest.indices("products");//输入要判断的索引名字

//返回值是布尔类型,判断方法是client对象下indices()方法的exists方法,在这个方法里有索引的名字;

boolean exists = esClient.indices().exists(existsRequest,RequestOptions.DEFAULT);

if(exists){//进行判断返回值;

}

esClient.indices().create(c -> c.index("products"));

}

相关推荐
文丑颜不良啊8 分钟前
LeetCode3281~3300题目解析
java·leetcode
nice_lcj5201 小时前
【从零理解计算机网络 · 02】分层模型:别背 OSI 七层,看数据怎么被“打包“和“拆包“
java·后端·tcp/ip·计算机网络·面试·osi·分层模型
SimonKing2 小时前
给Deepseek Harness装上插件市场,从此插件无忧
java·后端·程序员
艾莉丝努力练剑2 小时前
【AI大模型接入SDK】C++的SessionManager 线程安全
java·开发语言·前端·c++·人工智能·学习·安全
aiotto资源分享3 小时前
Python 写 JSON 文件,程序中途退出会留下什么?
java·python·json·jsondecodeerror
RuoyiOffice3 小时前
SpringBoot3+Vue3 采购到付款:ERP、WMS与财务如何按同一来源协同
java·spring boot·架构·vue
Elasticsearch4 小时前
Java4Shell 远程代码执行漏洞 - CVE-2026-114938
elasticsearch
文丑颜不良啊4 小时前
LeetCode3261~3280题目解析
java·leetcode
代码不停4 小时前
Spring 原理
java·spring
企业数字化笔记4 小时前
报表上线怎么对账?口径回归、权限抽检与差异定位
java·spring boot·mysql