Elasticsearch用RestHighLevelClient替换TransportClient

在Elasticsearch 7.0之后的版本废弃TransportClient,在Elasticsearch 8.0的版本中也将完全移除TransportClient,其次想使用认证还是9200比较简单,如果是9300必须要和证书配合使用所以项目中打算由RestHighLevelClient 替换掉 Transport Client。

连接替换

package es7121.utils;

import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

import java.io.IOException;

/**
 * @description: TODO
 * @author:******
 * @createTime: 2021-05-18 11:48
 * @version: 1.0
 */
public class ClientFactory {

    private static RestHighLevelClient client = null;
    private static final  String HOST="172.22.57.31";
    private static final  int PORT=9200;
    public static final   String DEFAULT_SCHEME_NAME = "http";
    private static final  String USERNAME="elastic";
    private static final  String PASSWORD="changeme";

    public static RestHighLevelClient getClient() {
        if (client == null) {
            CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
            credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(USERNAME, PASSWORD));
            //无需认证
            //RestClientBuilder builder = RestClient.builder(new HttpHost(HOST, PORT, DEFAULT_SCHEME_NAME));

            RestClientBuilder builder = RestClient.builder(new HttpHost(HOST, PORT,DEFAULT_SCHEME_NAME))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

            client = new RestHighLevelClient(builder);
        }
        return client;
    }


    public static void closeClient(){
        if(client!=null){
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}

创建索引替换

package es7121.index;

import org.elasticsearch.action.admin.indices.alias.Alias;
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.GetAliasesResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;

import java.util.Map;
import java.util.Set;

/**
 * @description: TODO
 * @author:*****
 * @createTime: 2021-05-18 14:04
 * @version: 1.0
 */
public class IndexTest {

    private RestHighLevelClient client = null;

    public IndexTest(RestHighLevelClient client) {
        this.client = client;

    }

    //https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.12/java-rest-high-create-index.html
    public boolean create(String index) {
        try {
            CreateIndexRequest request = new CreateIndexRequest(index);
            request.settings(Settings.builder().put("index.number_of_shards", 3).put("index.number_of_replicas", 0));
            //可以多种方式
            request.mapping(
                "{\n" +
                    "  \"properties\": {\n" +
                    "    \"user\": {\n" +
                    "      \"type\": \"text\"\n" +
                    "    },\n" +
                    "    \"postDate\": {\n" +
                    "      \"type\": \"text\"\n" +
                    "    },\n" +
                    "    \"message\": {\n" +
                    "      \"type\": \"text\"\n" +
                    "    }\n" +
                    "  }\n" +
                    "}", XContentType.JSON);
            request.alias(new Alias(index + "alias"));
            request.setTimeout(TimeValue.timeValueMinutes(2));
            CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);
            return createIndexResponse.isAcknowledged();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public boolean delete(String index) {
        try {
            DeleteIndexRequest request = new DeleteIndexRequest(index);
            request.timeout(TimeValue.timeValueMinutes(2));
            request.timeout("2m");
            AcknowledgedResponse deleteIndexResponse = client.indices().delete(request, RequestOptions.DEFAULT);
            return deleteIndexResponse.isAcknowledged();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public String[] getIndex(String index) {
        try {
            GetIndexRequest request = new GetIndexRequest(index);
            //request.indices("test_index");
            request.includeDefaults(true);
            GetIndexResponse getIndexResponse = client.indices().get(request, RequestOptions.DEFAULT);

            return getIndexResponse.getIndices();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String[0];
    }

    public void getAll() {
        try {
            GetAliasesRequest request = new GetAliasesRequest();
            GetAliasesResponse getAliasesResponse = client.indices().getAlias(request, RequestOptions.DEFAULT);
            Map<String, Set<AliasMetadata>> map = getAliasesResponse.getAliases();
            Set<String> indices = map.keySet();
            System.out.println("all index begin");
            for (String key : indices) {
                System.out.println(key);
            }
            System.out.println("all index end");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public boolean exist(String index) {
        try {
            GetIndexRequest request = new GetIndexRequest(index);
            boolean result = client.indices().exists(request, RequestOptions.DEFAULT);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

}

查询替换

//暂无,这里是另外一个同事进行的替换

健康状况索引的信息

            ClusterHealthRequest clusterHealthRequest = new  ClusterHealthRequest();
            clusterHealthRequest.indices("dlp-network-20210422-01");
            ClusterHealthResponse response = client.cluster().health(clusterHealthRequest,RequestOptions.DEFAULT);
           // GetIndexResponse indexResponse = client.indices().getDataStream(request , RequestOptions.DEFAULT);
            Request request = new Request("GET","/_cat/indices/dlp-network-20210422-01?h=index,docs.count,store.size&bytes=kb&format=json&pretty");
            Response response1 = client.getLowLevelClient().performRequest(request);
            String reponseBody = EntityUtils.toString(response1.getEntity());
            Object parse = JSON.parse(reponseBody);
            System.out.println("all index end");

transportClinet可以直接获取index的信息,但是新的接口不提供只能通过如下方法获取
官网信息
https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.12/_changing_the_application_8217_s_code.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值