暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Java使用 High Level REST Client 连接Elasticsearch

技术白小白 2018-10-23
541

今天西宁,最低气温-2℃,本来以为一个短袖可以扛到回去,现在看来回不去了,时隔多年,终于又体会到了什么叫冷!


==================我是分割线=================================

Java 客户端连接 Elasticsearch, 分别是TransportClient, NodeClient,XPackTransportClient,

TransportClient:

         作为一个外部访问者,请求ES的集群,对于集群而言,它是一个外部因素。

NodeClient

        作为ES集群的一个节点,它是ES中的一环,其他的节点对它是感知的。

XPackTransportClient:

        服务安装了 x-pack 插件

重要客户端版本应该和服务端版本保持一致,所有的elasticsearch操作都使用Client对象执行。 本质上, 所有的操作都是并行执行的。

TransportClient旨在被Java高级REST客户端取代,该客户端执行HTTP请求而不是序列化的Java请求,同时也最简单最容易使用的客户端。

因此,对前面三种连接方式不再赘述, 可自行研究。下面主要讲 Java High Level REST Client, 直接上代码:


/**
 * 使用 Java High Rest Client 操作 ElasticSearch 
 **/
import org.elasticsearch.client.Response;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.apache.commons.httpclient.HttpURL;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.entity.ContentType;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.util.EntityUtils;
public class ElasticSearchUtil {
    private static RestClient restClient;
    // rest 访问方法
    private static final String GET_METHOD = "GET";
    private static final String PUT_METHOD = "PUT";
    private static final String POST_METHOD = "POST";
    private static final String DELETE_METHOD = "DELETE";
    /**
     * 获取ES client
     * 此方法为线程安全, 需要把所有的ES节点都加上, 实现负载均衡
     *
     **/
    public static RestClient getRest(){
        restClient = RestClient.builder(getHttpHost()).build();
        return restClient;
    }
    /**
     *得到一个HttpHost[] 数组
     *
     **/
    private static HttpHost[] getHttpHost(){
        // host
        String hostsStr = "";
        String postStr = "";
        String scheme = "http";
        String[] hostArr = StringUtils.spilt(hostsStr, ",")
        List<HttpHost> httpHostList = new arrayList<>();
        if (hostArr.length <= 0) {
            return null;
        } else{
            for (String host : hostArr ) {
                HttpHost httpHost = new HttpHost(host, Integer.parseInt(postStr), scheme);
                httpHostList.add(httpHost);
            }
        }
        HttpHost[] httpHosts = new HttpHost[httpHostList.size()];
        return httpHostList.toArray(httpHosts);
    }
    /**
     * 通过URL, sql查询数据
     *
     **/
    public static String getDataFromSql(String sql) throws IOException {
        // 获取客户端
        restClient = getRest();
        String endpoint = "_sql?sql=" + sql;
        // url特殊字符转换
        HttpURL target = new HttpURL(endpoint);
        Response response = restClient.perfromRequest(GET_METHOD, target.toString());
        String result = EntityUtils.toString(response.getEntity());
        if (restClient != null) {
            restClient.close();
        }
        return result;
    }
    /**
     * 查询所有数据
     *
     **/
    public static String queryAll(String indexName, String type) throws Exception {
        String endpoint = "/" + indexName + "/" type + "/_search";
        HttpEntity entity = new NStringEntity("{\n" + 
            " \"query\":{\n" + 
            " \"match_all\":{}\n" + 
            "}\n" + 
            "}", ContentType.APPLICATION_JSON);
        Response response = restClient.perfromRequest(POST_METHOD, endpoint, Collections.<String, String>emptyMap, entity);
        String result = EntityUtils.toString(response.getEntity());
        if (restClient != null) {
            restClient.close();
        }
        return result;
    }
}
复制

此处,就全部结束,很简单的实现,以此作为记录。

文章转载自技术白小白,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论