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

1、介绍

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

2、引入依赖

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-java</artifactId>
        <version>8.7.1</version>
    </dependency>
</dependencies>

3、创建和关闭连接

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();
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值