0基础学习Elasticsearch-使用Java操作ES

文章目录

  • [1 背景](#1 背景)
  • [2 前言](#2 前言)
  • [3 Java如何操作ES](#3 Java如何操作ES)
    • [3.1 引入依赖](#3.1 引入依赖)
    • [3.2 依赖介绍](#3.2 依赖介绍)
    • [3.3 隐藏依赖](#3.3 隐藏依赖)
    • [3.4 初始化客户端(获取ES连接)](#3.4 初始化客户端(获取ES连接))
    • [3.5 发送请求给ES](#3.5 发送请求给ES)

1 背景

上篇学习了0基础学习Elasticsearch-Quick start,随后本篇研究如何使用Java操作ES

2 前言

  1. 建议通篇阅读再回头来跟着敲代码
  2. 建议先阅读Java连接ES云以及如何使用CA证书连接ES鉴权连接对Java连接ES有哪几种方法有个认知,阅读如何Reading responses,阅读如何同步、异步发送请求
  3. ES 8版本后建议使用Java Low Level REST ClientJava客户端,本篇采用该客户端

3 Java如何操作ES

3.1 引入依赖

xml 复制代码
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-client</artifactId>
    <version>8.13.4</version>
</dependency>

3.2 依赖介绍

low-level Java REST client内部采用了Apache Http Async Client来发送HTTP请求,内部含有以下这些依赖,如果遇到依赖冲突,需要解决:

  • org.apache.httpcomponents:httpasyncclient
  • org.apache.httpcomponents:httpcore-nio
  • org.apache.httpcomponents:httpclient
  • org.apache.httpcomponents:httpcore
  • commons-codec:commons-codec
  • commons-logging:commons-logging

3.3 隐藏依赖

如果遇到上面列出的依赖冲突,可以使用下面这个方法来解决,pom文件加入下面代码:

xml 复制代码
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-shade-plugin</artifactId>
            <version>3.1.0</version>
            <executions>
                <execution>
                    <phase>package</phase>
                    <goals><goal>shade</goal></goals>
                    <configuration>
                        <relocations>
                            <relocation>
                                <pattern>org.apache.http</pattern>
                                <shadedPattern>hidden.org.apache.http</shadedPattern>
                            </relocation>
                            <relocation>
                                <pattern>org.apache.logging</pattern>
                                <shadedPattern>hidden.org.apache.logging</shadedPattern>
                            </relocation>
                            <relocation>
                                <pattern>org.apache.commons.codec</pattern>
                                <shadedPattern>hidden.org.apache.commons.codec</shadedPattern>
                            </relocation>
                            <relocation>
                                <pattern>org.apache.commons.logging</pattern>
                                <shadedPattern>hidden.org.apache.commons.logging</shadedPattern>
                            </relocation>
                        </relocations>
                    </configuration>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

3.4 初始化客户端(获取ES连接)

概括:通过账号密码来获取连接。笔者这里通过注入bean的方式初始化ES客户端并交给Spring管理

java 复制代码
@Slf4j
@Configuration
public class EsClient {

    public static final String HOST = "192.168.90.128";
    public static final int PORT = 9200;
    public static final String PROTOCOL = "https";
    public static final String username = "elastic";
    public static final String password = "84fZ4PuywWr_unOcr+JH";
    @Bean
    public RestClient restClient() {
        RestClientBuilder clientBuilder = RestClient.
                builder(new HttpHost(HOST, PORT, PROTOCOL))
                .setCompressionEnabled(true);
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(username, password));
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, TrustAllStrategy.INSTANCE).build();
            clientBuilder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder
                    .setSSLContext(sslContext)
                    .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                    .setDefaultCredentialsProvider(credentialsProvider));
        } catch (Exception e) {
            log.error("EsClient_elasticsearchClient, init RestClient error. error msg:{}", e.getMessage());
        }

        return clientBuilder.build();
    }
}

3.5 发送请求给ES

写一个测试类来尝试操作ES:

java 复制代码
@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = GmallEsApplication.class)
@ContextConfiguration
public class EsClientTest{

    @Resource
    private RestClient restClient;

    @Test
    public void performRequest() throws IOException {
        Request request = new Request(
                "GET",
                "/");
        Response response = restClient.performRequest(request);
        log.info("response:{}", JSON.toJSONString(response));

        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            System.err.println("Method failed: " + response.getStatusLine());
        } else {
            HttpEntity entity = response.getEntity();
            String responseBody = EntityUtils.toString(entity);
            log.info("responseBody:{}", responseBody);
        }
    }

}
相关推荐
Dusk_橙子3 小时前
在elasticsearch中,document数据的写入流程如何?
大数据·elasticsearch·搜索引擎
喝醉酒的小白5 小时前
Elasticsearch 中,分片(Shards)数量上限?副本的数量?
大数据·elasticsearch·jenkins
熟透的蜗牛7 小时前
Elasticsearch 8.17.1 JAVA工具类
elasticsearch
九圣残炎11 小时前
【ElasticSearch】 Java API Client 7.17文档
java·elasticsearch·搜索引擎
risc12345613 小时前
【Elasticsearch】HNSW
elasticsearch
我的棉裤丢了14 小时前
windows安装ES
大数据·elasticsearch·搜索引擎
乙卯年QAQ16 小时前
【Elasticsearch】RestClient操作文档
java·大数据·elasticsearch·jenkins
超级阿飞21 小时前
利用Kubespray安装生产环境的k8s集群-实施篇
elasticsearch·容器·kubernetes
小诺大人1 天前
Docker 安装 elk(elasticsearch、logstash、kibana)、ES安装ik分词器
elk·elasticsearch·docker
forestsea1 天前
【Elasticsearch 】 聚合分析:桶聚合
大数据·elasticsearch·搜索引擎