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

}

相关推荐
风象南4 分钟前
SpringBoot 控制器的动态注册与卸载
java·spring boot·后端
我是一只代码狗30 分钟前
springboot中使用线程池
java·spring boot·后端
hello早上好43 分钟前
JDK 代理原理
java·spring boot·spring
PanZonghui1 小时前
Centos项目部署之Java安装与配置
java·linux
沉着的码农1 小时前
【设计模式】基于责任链模式的参数校验
java·spring boot·分布式
Mr_Xuhhh2 小时前
信号与槽的总结
java·开发语言·数据库·c++·qt·系统架构
纳兰青华2 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
coding and coffee2 小时前
狂神说 - Mybatis 学习笔记 --下
java·后端·mybatis
千楼2 小时前
阿里巴巴Java开发手册(1.3.0)
java·代码规范
reiraoy2 小时前
缓存解决方案
java