ElasticSearch 8 学习笔记总结(六)

文章目录

  • 一. ES8 的Java API 环境准备
  • 二. ES8 的Java API 索引操作
  • 三. ES8 的Java API 文档操作
    • 1. 文档的 插入 批量插入 删除等操作
    • 2. 文档的查询
  • 四、异步客户端操作

一. ES8 的Java API 环境准备

ES8 废除了Type的概念。为了适应这种数据结构的改变,ES官方从1.7版本开始建议使用新的Elasticsearch Java Client。


搭建maven环境:

<properties>
    <maven.compiler.source>8</maven.compiler.source>
    <maven.compiler.target>8</maven.compiler.target>
    <elastic.version>8.6.2</elastic.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.plugin</groupId>
        <artifactId>x-pack-sql-jdbc</artifactId>
        <version>8.6.2</version>
    </dependency>
    <dependency>
        <groupId>co.elastic.clients</groupId>
        <artifactId>elasticsearch-java</artifactId>
        <version>${elastic.version}</version>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.12.3</version>
    </dependency>
    <dependency>
        <groupId>jakarta.json</groupId>
        <artifactId>jakarta.json-api</artifactId>
        <version>2.0.1</version>
    </dependency>
</dependencies>

获取客户端对象:

因为,服务注册的是基于https的安全elasticsearch服务认证,所以,将之前的证书进行一个转换:

# 生成es-api-ca.crt证书,之前没有密码设置。
openssl pkcs12 -in elastic-stack-ca.p12 -clcerts -nokeys -out es-api-ca.crt

将生成的证书放到项目里面。
在这里插入图片描述

创建连接对象:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

public class ESClient {

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
    }

    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // 异步客户端对象
        ElasticsearchAsyncClient asyncClient = new ElasticsearchAsyncClient(transport);

        // fixme 同步是需要关闭的,而异步是不需要关闭的。
        transport.close();
    }

}

二. ES8 的Java API 索引操作

ES Java的API相关操作:

  • 采用构造器形式来创建所需要的对象。
  • 通过lambda来创建。

对象形式操作:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

public class ESClient {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // 操作索引
        operationIndex();
    }
    // 操作索引
    private static void operationIndex() throws Exception{
        // 获取索引客户端对象
        ElasticsearchIndicesClient indices = client.indices();
        // 判断索引是否存在
        ExistsRequest existsRequest = new ExistsRequest.Builder().index(INDEX_HOLMES).build();
        final boolean flg = indices.exists(existsRequest).value();
        if (flg){
            System.out.println("索引" + INDEX_HOLMES + "已经存在!");
        } else {
            // 创建索引
            // CreateIndexRequest构造方法已经私有化了,所以需要采用构建器方式来构建对象。ES的API对象基本上都采用构建器的方式创建对象。
            CreateIndexRequest request = new CreateIndexRequest.Builder()
                    .index(INDEX_HOLMES)
                    .build();
            final CreateIndexResponse createIndexResponse = indices.create(request);
            System.out.println("创建索引的响应对象" + createIndexResponse);
        }
        // 查询索引
        GetIndexRequest getIndexRequest = new GetIndexRequest.Builder().index(INDEX_HOLMES).build();
        final GetIndexResponse getIndexResponse = indices.get(getIndexRequest);
        // IndexState itholmes = getIndexResponse.get("itholmes");
        System.out.println("查询的响应结果:" + getIndexResponse);
        // 删除索引
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(INDEX_HOLMES).build();
        DeleteIndexResponse delete = indices.delete(deleteIndexRequest);
        System.out.println("索引删除成功:" + delete);
        // fixme 同步是需要关闭的,而异步是不需要关闭的。
        transport.close();
    }

    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

lambda方式创建索引:(推荐使用,代码简洁)

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.indices.*;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import co.elastic.clients.util.ObjectBuilder;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.function.Function;

public class ESClient {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // lambda方式 操作索引
        operationIndexLambda();
    }
    // fixme 操作索引 Lambda方式 其实就是提供了两种方式
    private static void operationIndexLambda() throws Exception{
        // 获取索引客户端对象
        ElasticsearchIndicesClient indices = client.indices();
        // 检查索引是否存在
        boolean flg = indices.exists(req -> req.index(INDEX_HOLMES)).value();
        if (flg){
            System.out.println("索引" + INDEX_HOLMES + "已经存在!");
        } else {
            // 创建索引
            final CreateIndexResponse createIndexResponse = indices.create(req -> req.index(INDEX_HOLMES));
            System.out.println("创建索引的响应对象:" + createIndexResponse);
        }
        // 查询索引
        final GetIndexResponse getIndexResponse = indices.get(req -> req.index(INDEX_HOLMES));
        System.out.println("查询的响应结果:" + getIndexResponse.get("itholmes"));
        // 删除索引
        DeleteIndexResponse deleteIndexResponse = indices.delete(req -> req.index(INDEX_HOLMES));
        System.out.println("索引删除成功:" + deleteIndexResponse);
        // fixme 同步是需要关闭的,而异步是不需要关闭的。
        transport.close();
    }
   
    // 初始化ES服务器的连接
    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

三. ES8 的Java API 文档操作

1. 文档的 插入 批量插入 删除等操作

文档对象形式操作:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;

public class ESClient2 {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // fixme 文档操作
        operateDocument();
    }
    // 对象操作文档
    public static void operateDocument() throws Exception{
        // 创建对象数据
        User user = new User();
        user.setId(1001);
        user.setName("zhangsan");
        user.setAge(30);
        CreateRequest<User> createRequest = new CreateRequest.Builder<User>()
                .index(INDEX_HOLMES)
                .id("1001")
                .document(user)
                .build();

        // 增加文档
        CreateResponse createResponse = client.create(createRequest);
        System.out.println("文档创建的响应对象:" + createResponse);

        // 批量添加数据
        List<BulkOperation> opts = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            CreateOperation<User> optObj = new CreateOperation.Builder<User>()
                    .index(INDEX_HOLMES)
                    .id("200" + i)
                    .document(new User(2000 + i,"张三" + i,30 + i))
                    .build();
            BulkOperation opt = new BulkOperation.Builder()
                    .create(optObj)
                    .build();
            opts.add(opt);
        }
        BulkRequest bulkRequest = new BulkRequest.Builder()
                .operations(opts)
                .build();
        final BulkResponse bulk = client.bulk(bulkRequest);
        System.out.println("批量新增数据的响应:" + bulk);

        // 文档删除
        DeleteRequest deleteRequest = new DeleteRequest.Builder()
                .index(INDEX_HOLMES)
                .id("2001")
                .build();
        DeleteResponse delete = client.delete(deleteRequest);
        System.out.println("删除后的响应:" + delete);
        // 关闭transport
        transport.close();
    }

    // 初始化ES服务器的连接
    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

lambda形式:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;

public class ESClient2 {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // fixme 文档操作
        operateDocumentLambda();
    }

    // lambda操作文档
    public static void operateDocumentLambda() throws Exception{
        // 增加文档
        Result result = client.create(
                req ->
                        req.index(INDEX_HOLMES).id("1001").document(new User(1001, "张三", 30))
        ).result();
        System.out.println("文档创建的响应对象:" + result);

        // 批量添加数据
        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            users.add(new User(3000 + i , "lisi" + i ,30 + i));
        }
        BulkResponse bulk = client.bulk(
                req -> {
                    users.forEach(
                            u -> {
                                req.operations(
                                        b -> b.create(
                                                d -> d.index(INDEX_HOLMES)
                                                        .id(u.getId().toString())
                                                        .document(u)
                                        )
                                );
                            }
                    );
                    return req;
                }
        );
        System.out.println("批量新增数据的响应:" + bulk);

        // 文档删除
        DeleteResponse delete = client.delete(
                req -> req.index(INDEX_HOLMES).id("3001")
        );
        System.out.println("删除后的响应:" + delete);
        // 关闭transport
        transport.close();
    }

    // 初始化ES服务器的连接
    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

2. 文档的查询

对象形式操作:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;

public class ESClient3 {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // fixme 文档查询操作
        queryDocument();
    }

    // 文档查询操作
    public static void queryDocument() throws Exception{

        MatchQuery matchQuery = new MatchQuery.Builder()
                .field("age").query(30)
                .build();

        Query query = new Query.Builder()
                .match(matchQuery)
                .build();

        SearchRequest searchRequest = new SearchRequest.Builder()
                .query(query) // 传递条件
                .build();

        SearchResponse<Object> search = client.search(searchRequest, Object.class);

        System.out.println(search);

        transport.close();
    }

    // 初始化ES服务器的连接
    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

lambda操作:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.Result;
import co.elastic.clients.elasticsearch._types.query_dsl.MatchQuery;
import co.elastic.clients.elasticsearch._types.query_dsl.Query;
import co.elastic.clients.elasticsearch.core.*;
import co.elastic.clients.elasticsearch.core.bulk.BulkOperation;
import co.elastic.clients.elasticsearch.core.bulk.CreateOperation;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;
import java.util.ArrayList;
import java.util.List;

public class ESClient3 {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // fixme 文档查询操作
        queryDocumentLambda();
    }

    // 文档查询操作
    public static void queryDocumentLambda() throws Exception{

        SearchResponse<Object> search = client.search(
                req -> {
                    req.query(
                            q -> q.match(
                                    m -> m.field("name").query("zhangsan")
                            )
                    );
                    return req;
                },
                Object.class
        );

        System.out.println(search);

        transport.close();
    }

    // 初始化ES服务器的连接
    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

四、异步客户端操作

进行异步相关操作:

package com.itholmes.elasticsearch.api;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import co.elastic.clients.transport.rest_client.RestClientTransport;
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.ssl.SSLContexts;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;

import javax.net.ssl.SSLContext;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.KeyStore;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

public class ESClient3 {

    private static ElasticsearchClient client;

    private static ElasticsearchAsyncClient asyncClient;

    private static ElasticsearchTransport transport;

    public static final String INDEX_HOLMES = "itholmes";

    public static void main(String[] args) throws Exception{
        // 初始化ES服务器的连接
        initESConnection();
        // fixme 异步文档查询操作
        asyncClientOperation();
    }

    public static void asyncClientOperation() throws Exception{
        asyncClient.indices().create(
                req -> req.index("newindex")
        ).thenApply( // 此处可以处理一下,resp返回值
            resp -> resp.acknowledged()
        ).whenComplete( // 当完成时,调用的回调
                (resp,error) -> {
                    System.out.println("回调方法");
                    if (resp != null){
                        System.out.println(resp);
                    } else {
                        error.printStackTrace();
                    }
                }
        );
        System.out.println("主线程代码...");
    }

    // 初始化ES服务器的连接
    public static void initESConnection() throws Exception{
        final BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        // 声明ES当前登录的账号密码
        credentialsProvider.setCredentials(AuthScope.ANY,new UsernamePasswordCredentials("elastic","3j=JYpywv=jMtQB+XIXS"));
        // 证书的路径
        Path caCertificatePath = Paths.get("E:\\itholmes\\demo\\itholmes-es8\\certs\\es-api-ca.crt");
        // x.509 , pkcs12都是 证书的算法
        CertificateFactory factory = CertificateFactory.getInstance("x.509");
        Certificate trustedCa;
        try (InputStream is = Files.newInputStream(caCertificatePath)){
            trustedCa = factory.generateCertificate(is);
        }
        KeyStore trustStore = KeyStore.getInstance("pkcs12");
        trustStore.load(null,null);
        trustStore.setCertificateEntry("ca",trustedCa);
        SSLContextBuilder sslContextBuilder = SSLContexts.custom()
                .loadTrustMaterial(trustStore,null);
        SSLContext sslContext = sslContextBuilder.build();
        RestClientBuilder builder = RestClient.builder(new HttpHost("192.168.43.133", 9200, "https"))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // 创建客户端
        RestClient restClient = builder.build();
        // 通过客户端,创建传输对象
        transport = new RestClientTransport(restClient, new JacksonJsonpMapper());

        // 同步客户端对象
        client = new ElasticsearchClient(transport);
        // 异步客户端对象
        asyncClient = new ElasticsearchAsyncClient(transport);
    }

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/246.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

学习 Python 之 Pygame 开发魂斗罗(十一)

学习 Python 之 Pygame 开发魂斗罗&#xff08;十一&#xff09;继续编写魂斗罗1. 改写主类函数中的代码顺序2. 修改玩家初始化3. 显示玩家生命值4. 设置玩家碰到敌人死亡5. 设置敌人子弹击中玩家6. 修改updatePlayerPosition()函数逻辑继续编写魂斗罗 在上次的博客学习 Pytho…

(四)HDFS双HA高可用机制

目录 概述 原理 主备切换 小结: 概述 进入到了hadoop 2.x的时代&#xff0c;为了保证namenode上的元数据不会丢失&#xff0c;而且是高可用的&#xff0c;出现了双实例HA的机制 原理 集群里启动两个namenode&#xff0c;一个是active状态(主)&#xff0c;一个是standby(备…

HDFS黑名单退役服务器

黑名单&#xff1a;表示在黑名单的主机IP地址不可以&#xff0c;用来存储数据。 企业中&#xff1a;配置黑名单&#xff0c;用来退役服务器。 黑名单配置步骤如下&#xff1a; 1&#xff09;编辑/opt/module/hadoop-3.1.3/etc/hadoop目录下的blacklist文件 添加如下主机名称&…

Spring —— 初学 Spring, 理解控制反转

JavaEE传送门JavaEE Servlet —— Smart Tomcat,以及一些访问出错可能的原因 Servlet —— Servlet API 目录SpringIoC (理解控制反转)传统代码ioc代码DISpring Spring 通常指的是 Spring Farmework (Spring 框架), 它是一个开源框架 用一句话来概括: Spring 是一个包含了众多…

【linux】Linux基本指令(上)

前言&#xff1a; 在之前我们已经简单了介绍了一下【Linux】&#xff0c;包括它的概念&#xff0c;由来啊等进行了讲解&#xff0c;接下来我们就将正式的踏入对其的学习&#xff01;&#xff01;&#xff01; 本文目录&#x1f449;操作系统的概念1.命令的语法1.1命令介绍1.2选…

ChatGPT告诉你:项目管理能干到60岁吗?

早上好&#xff0c;我是老原。这段时间最火的莫过于ChatGPT&#xff0c;从文章创作到论文写作&#xff0c;甚至编程序&#xff0c;简直厉害的不要不要的。本以为过几天热度就自然消退了&#xff0c;结果是愈演愈烈&#xff0c;热度未减……大家也从一开始得玩乐心态&#xff0c…

python flask项目打包成docker镜像发布

1.编写python flask代码&#xff0c;简单写一个加法的接口&#xff0c;命名为sum.py import json from flask import Flask,request,render_template app Flask(__name__)app.route(/) def index():return hello worldapp.route(/sum,methods[POST]) def correct():a request…

C/C++网络编程笔记Socket

https://www.bilibili.com/video/BV11Z4y157RY/?vd_sourced0030c72c95e04a14c5614c1c0e6159b上面链接是B站的博主教程&#xff0c;源代码来自上面视频&#xff0c;侵删&#xff0c;这里只是做笔记&#xff0c;以供复习和分享。上一篇博客我记录了配置环境并且跑通了&#xff0…

Nginx——Nginx的优化设计

摘要 本博文介绍Nginx的优化设计方向和原理&#xff0c;帮助大家在nginx的使用和优化中提供一个参考的方向&#xff0c;让你的nginx发挥最大性能&#xff0c;节约系统资源。 一、Nginx开启Http2.0的优化 HTTP/2是HTTP协议的最新标准&#xff0c;它是HTTP/1.1的继承者。由于它…

大厂与小厂招人的区别,看完多少有点不敢相信

前两天在头条发了一条招人的感慨&#xff0c;关于大厂招人和小公司招人的区别。 大厂&#xff1a;有影响力&#xff0c;有钱&#xff0c;能够吸引了大量的应聘者。因此&#xff0c;也就有了筛选的资格&#xff0c;比如必须985名校毕业&#xff0c;必须35岁以下&#xff0c;不能…

数据结构与算法这么难,为什么我们还要学习?

文章目录前言1. 数据结构与算法是什么&#xff1f;2. 为什么数据结构与算法很难&#xff1f;3. 如何系统学习数据结构与算法&#xff1f;&#x1f351; 复杂度&#x1f351; 线性表&#x1f351; 树形结构&#x1f351; 图&#x1f351; 排序&#x1f351; 字符串&#x1f351;…

【c++】:模拟实现STL模板中的string

文章目录 前言一.string的模拟实现总结前言 上一篇文章我们详细介绍了STL中的string的一些常用的接口&#xff0c;这一篇文章我们将从底层实现string类&#xff0c;当然我们只是实现一些重要的&#xff0c;经常使用的接口&#xff0c;并且不是完全按照STL中的string去走的。 一…

对于从事芯片行业的人来说,有哪些知识是需要储备的?

近两年芯片行业大火&#xff0c;不少同学想要转行&#xff0c;却不知道该如何下手&#xff0c;需要学习哪些基础知识&#xff0c;下面就来看看资深工程师怎么说&#xff1f; 随着工艺的发展&#xff0c;芯片肯定是尺寸越来越小&#xff0c;至于小到什么样的程度是极限&#xf…

【小破站下载工具】Python tkinter 实现网站下载工具,所有数据一键获取

目录前言开发环境本次项目案例步骤先展示下完成品的效果界面导入模块先创建个窗口功能按键主要功能代码编写功能一功能二功能三前言 最近很多同学想问我&#xff0c;怎么把几个代码的功能集合到一起&#xff1f; 很简单&#xff0c;写一个界面就行了&#xff0c;想要哪个代码…

CSS的三大特性

&#x1f31f;所属专栏&#xff1a;前端只因变凤凰之路&#x1f414;作者简介&#xff1a;rchjr——五带信管菜只因一枚&#x1f62e;前言&#xff1a;该系列将持续更新前端的相关学习笔记&#xff0c;欢迎和我一样的小白订阅&#xff0c;一起学习共同进步~&#x1f449;文章简…

用ChatGPT生成Excel公式,太方便了

ChatGPT 自去年 11 月 30 日 OpenAI 重磅推出以来&#xff0c;这款 AI 聊天机器人迅速成为 AI 界的「当红炸子鸡」。一经发布&#xff0c;不少网友更是痴迷到通宵熬夜和它对话聊天&#xff0c;就为了探究 ChatGPT 的应用天花板在哪里&#xff0c;经过试探不少人发现&#xff0c…

vue3+vite项目移动端适配:postcss-pxtorem和amfe-flexible

一&#xff0c;定义 postcss-pxtorem PostCSS 的一个插件&#xff0c;可以从像素单位生成 rem 单位。 amfe-flexible amfe-flexible是配置可伸缩布局方案&#xff0c;主要是将1rem设为viewWidth/10。 二&#xff0c;使用 1. 设置 viewport 在 index.html 中&#xff1a; &l…

学生信息表

目录 一、功能说明 二、核心思想 三、所用知识回顾 四、基本框架 五、js功能实现部分 一、功能说明 &#xff08;1&#xff09;输入对应的信息&#xff0c;点击录入可以为下面的表格添加一条记录&#xff0c;注意当所填信息不完整时不允许进行提交。 &#xff08;2&…

UE实现建筑生长(材质遮罩方式)效果

文章目录 1.实现目标2.实现过程2.1 遮罩2.2 生长动画3.参考资料1.实现目标 在UE中实现建筑的生成动画效果,GIF动图如下: 2.实现过程 通过动态设置材质遮罩OpacityMask的参数,即通过材质方式来实现建筑生长效果 2.1 遮罩 现有的教程中大多通过BoxMask-3D材质节点实现,但是…

扫地机器人(蓝桥杯C/C++)

题目描述 小明公司的办公区有一条长长的走廊&#xff0c;由 NN 个方格区域组成&#xff0c;如下图所示。 走廊内部署了 KK 台扫地机器人&#xff0c;其中第 ii 台在第 A_iAi​ 个方格区域中。已知扫地机器人每分钟可以移动到左右相邻的方格中&#xff0c;并将该区域清扫干净。…