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>8maven.compiler.source>
    <maven.compiler.target>8maven.compiler.target>
    <elastic.version>8.6.2elastic.version>
properties>

<dependencies>
    <dependency>
        <groupId>org.elasticsearch.plugingroupId>
        <artifactId>x-pack-sql-jdbcartifactId>
        <version>8.6.2version>
    dependency>
    <dependency>
        <groupId>co.elastic.clientsgroupId>
        <artifactId>elasticsearch-javaartifactId>
        <version>${elastic.version}version>
    dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.coregroupId>
        <artifactId>jackson-databindartifactId>
        <version>2.12.3version>
    dependency>
    <dependency>
        <groupId>jakarta.jsongroupId>
        <artifactId>jakarta.json-apiartifactId>
        <version>2.0.1version>
    dependency>
dependencies>

获取客户端对象:

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

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

将生成的证书放到项目里面。
ElasticSearch 8 学习笔记总结(六)_第1张图片

创建连接对象:

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

}

你可能感兴趣的:(中间件,(从头到尾,笔记),elasticsearch,学习,java)