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"));

}

相关推荐
taopi202443 分钟前
android java系统弹窗的基础模板
android·java·开发语言
松仔log1 小时前
Java多线程——对象的组合
java·开发语言·jvm
酷爱码1 小时前
springboot 动态配置定时任务
java·spring boot·后端
从未止步..2 小时前
Jenkins未在第一次登录后设置用户名,第二次登录不进去怎么办?
java·运维·jenkins
老马啸西风2 小时前
IM 即时通讯系统-42-基于netty实现的IM服务端,提供客户端jar包,可集成自己的登录系统
java
2501_903238652 小时前
Java 9模块开发:Eclipse实战指南
java·开发语言·eclipse·个人开发
test猿2 小时前
hive为什么建表,表存储什么
java
程序猿零零漆3 小时前
SpringCloud系列教程:微服务的未来(二十)Seata快速入门、部署TC服务、微服务集成Seata
java·spring·spring cloud·微服务
wdxylb3 小时前
GIt使用笔记大全
笔记·git·elasticsearch
我的K84094 小时前
Spring Boot基本项目结构
java·spring boot·后端