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

}

相关推荐
小猿姐5 小时前
唯品会大规模数据库云原生实践:基于 KubeBlocks 管理数千实例的统一运维之路
运维·elasticsearch·云原生
Flittly16 小时前
【AgentScope Java新手村系列】(16)从RAG到多路检索
java·spring boot·spring
小兔崽子去哪了16 小时前
Java 生成二维码解决方案
java·后端
人活一口气20 小时前
从JVM调优到MCP协议:Java全栈技术体系深度总结与企业级架构实践
java·spring boot
Elasticsearch1 天前
使用 Elastic Agent Builder 和 Sarvam AI 构建多语言语音 agent
elasticsearch
NE_STOP1 天前
Vibe Coding -- 完整项目案例实操
java
荣码1 天前
GraphRAG:普通RAG只能回答"点"的问题,我踩了4个坑才搞懂
java·python
SimonKing1 天前
Google第三方授权登录
java·后端·程序员
明月光8181 天前
从一行 @Builder 说起:重新拾起 Java 的 Lombok、注解与 Builder 模式
java
考虑考虑1 天前
Mybatis实现批量插入
java·后端·mybatis