Elasticsearch Java API使用(1):创建ElasticsearchClient

1、介绍

Elasticsearch是一个基于Lucene构建的开源搜索引擎,支持复杂的搜索功能。Java API SDK是Elasticsearch官方提供的一种方式,允许Java应用程序直接与Elasticsearch集群交互。8.x的版本和旧版本API差别比较大。本文没有使用Springboot data相关的功能,而是直接演示原生API的用法。

2、引入依赖

html 复制代码
<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-java</artifactId>
        <version>8.7.1</version>
    </dependency>
</dependencies>

3、创建和关闭连接

java 复制代码
void testAnonymous() {
        // 匿名连接
        RestClient restClient = RestClient.builder(new HttpHost("192.168.0.10", 9200),
                new HttpHost("192.168.0.11", 9200),
                new HttpHost("192.168.0.12", 9200)).build();
        ObjectMapper objectMapper = new ObjectMapper();
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper(objectMapper));
        ElasticsearchClient client = new ElasticsearchClient(transport);
        client.shutdown();
    }


    void testBasicCredentials() {
        // 使用账号密码创建连接
        String username = "elastic";
        String password = "elastic";
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));

        RestClient restClient = RestClient.builder(new HttpHost("localhost", 9200))
                .setHttpClientConfigCallback(httpAsyncClientBuilder ->
                        httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider)).build();
        ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        client.shutdown();
    }
相关推荐
懒惰蜗牛14 小时前
Day63 | Java IO之NIO三件套--选择器(下)
java·nio·选择器·selector·半包粘包·tcp缓冲区
JavaGuide14 小时前
美团2026届后端一二面(附详细参考答案)
java·后端
打工人你好14 小时前
如何设计更安全的 VIP 权限体系
java·jvm·安全
L.EscaRC14 小时前
Spring IOC核心原理与运用
java·spring·ioc
摇滚侠14 小时前
2025最新 SpringCloud 教程,Nacos-总结,笔记19
java·笔记·spring cloud
在逃热干面15 小时前
(笔记)获取终端输出保存到文件
java·笔记·spring
爱笑的眼睛1115 小时前
深入理解MongoDB PyMongo API:从基础到高级实战
java·人工智能·python·ai
笃行客从不躺平15 小时前
遇到大SQL怎么处理
java·开发语言·数据库·sql
q***876015 小时前
Spring Boot 整合 Keycloak
java·spring boot·后端
Billow_lamb15 小时前
Spring Boot2.x.x全局拦截器
java·spring boot·后端