Search in sources :

Example 16 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project warn-report by saaavsaaa.

the class ElasticClient method search.

@Test
public void search() throws IOException {
    String elasticsearchHost = "sl010a-analysisdb1:9200,sl010a-analysisdb2:9200,sl010a-analysisdb3:9200";
    String[] elasticHosts = elasticsearchHost.split(",");
    HttpHost[] httpHosts = new HttpHost[elasticHosts.length];
    for (int i = 0; i < elasticHosts.length; i++) {
        String ip = elasticHosts[i].split(":")[0];
        String port = elasticHosts[i].split(":")[1];
        httpHosts[i] = new HttpHost(ip, Integer.parseInt(port), "https");
    }
    RestClient restClient = RestClient.builder(httpHosts).setDefaultHeaders(new Header[] { new BasicHeader("Authorization", "Basic Q049ZGVtb3VzZXI6Q049ZGVtb3VzZXI=") }).build();
    RestHighLevelClient client = new RestHighLevelClient(restClient);
    SearchRequest searchRequest = new SearchRequest();
    SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
    searchSourceBuilder.query(QueryBuilders.matchAllQuery());
    searchRequest.source(searchSourceBuilder);
    SearchResponse searchResponse = client.search(searchRequest);
    System.out.println(searchResponse.getTotalShards());
}
Also used : SearchRequest(org.elasticsearch.action.search.SearchRequest) Header(org.apache.http.Header) BasicHeader(org.apache.http.message.BasicHeader) HttpHost(org.apache.http.HttpHost) RestClient(org.elasticsearch.client.RestClient) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) BasicHeader(org.apache.http.message.BasicHeader) SearchSourceBuilder(org.elasticsearch.search.builder.SearchSourceBuilder) SearchResponse(org.elasticsearch.action.search.SearchResponse) Test(org.junit.Test)

Example 17 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project kylo by Teradata.

the class ElasticSearchRestService method commit.

@Override
public void commit(@Nonnull String indexName) {
    try (RestClient restClient = buildRestClient()) {
        restClient.performRequest(POST_METHOD, getIndexRefreshEndPoint(indexName));
        log.debug("Committed index with name {}", indexName);
    } catch (ResponseException responseException) {
        log.error("Index refresh encountered issues in Elasticsearch for index name {" + indexName + "}", responseException);
    } catch (ClientProtocolException clientProtocolException) {
        log.error("Http protocol error for refresh for index name {" + indexName + "}", clientProtocolException);
    } catch (IOException ioException) {
        log.error("IO Error in rest client", ioException);
    }
}
Also used : ResponseException(org.elasticsearch.client.ResponseException) RestClient(org.elasticsearch.client.RestClient) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 18 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project kylo by Teradata.

the class ElasticSearchRestService method delete.

@Override
public void delete(@Nonnull String indexName, @Nonnull String typeName, @Nonnull String id, @Nonnull String schema, @Nonnull String table) {
    try (RestClient restClient = buildRestClient()) {
        // Delete schema
        restClient.performRequest(DELETE_METHOD, getIndexDeleteEndPoint(indexName, typeName, id));
        log.info("Deleted schema document for index={}, type={}, id={}", indexName, typeName, id);
        final String dataIndexName = "kylo-data";
        final String dataIndexType = "hive-data";
        // Delete data
        if ((restClientConfig.getEsversion() != null) && (restClientConfig.getEsversion().equals(VERSION_TWO))) {
            log.debug("Elasticsearch v2");
            restClient.performRequest(DELETE_METHOD, getDataDeleteEndPointEsV2(dataIndexName, dataIndexType), new HashMap<>(), getDataDeleteRequestBodyDslEsV2(schema, table));
        } else {
            log.debug("Elasticsearch v5 or above");
            restClient.performRequest(POST_METHOD, getDataDeleteEndPoint(dataIndexName, dataIndexType), new HashMap<>(), getDataDeleteRequestBodyDsl(schema, table));
        }
        log.info("Deleted data for index={}, type={}, schema={}, table={}", dataIndexName, dataIndexType, schema, table);
    } catch (ResponseException responseException) {
        log.error("Index document deletion encountered issues in Elasticsearch for index={}, type={}, id={}", indexName, typeName, responseException);
    } catch (ClientProtocolException clientProtocolException) {
        log.error("Http protocol error for delete document for index={}, type={}, id={}", indexName, typeName, id, clientProtocolException);
    } catch (IOException ioException) {
        log.error("IO Error in rest client", ioException);
    }
}
Also used : ResponseException(org.elasticsearch.client.ResponseException) RestClient(org.elasticsearch.client.RestClient) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 19 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project incubator-gobblin by apache.

the class ElasticsearchRestWriter method buildRestClient.

// TODO: Support pass through of configuration (e.g. timeouts etc) of rest client from above
private static RestClient buildRestClient(List<InetSocketTransportAddress> hosts, int threadCount, boolean sslEnabled, String keyStoreType, String keyStoreFilePassword, String identityFilepath, String trustStoreType, String trustStoreFilePassword, String cacertsFilepath) throws Exception {
    HttpHost[] httpHosts = new HttpHost[hosts.size()];
    String scheme = sslEnabled ? "https" : "http";
    for (int h = 0; h < httpHosts.length; h++) {
        InetSocketTransportAddress host = hosts.get(h);
        httpHosts[h] = new HttpHost(host.getAddress(), host.getPort(), scheme);
    }
    RestClientBuilder builder = RestClient.builder(httpHosts);
    if (sslEnabled) {
        log.info("ssl configuration: trustStoreType = {}, cacertsFilePath = {}", trustStoreType, cacertsFilepath);
        KeyStore truststore = KeyStore.getInstance(trustStoreType);
        FileInputStream trustInputStream = new FileInputStream(cacertsFilepath);
        try {
            truststore.load(trustInputStream, trustStoreFilePassword.toCharArray());
        } finally {
            trustInputStream.close();
        }
        SSLContextBuilder sslBuilder = SSLContexts.custom().loadTrustMaterial(truststore, null);
        log.info("ssl key configuration: keyStoreType = {}, keyFilePath = {}", keyStoreType, identityFilepath);
        KeyStore keystore = KeyStore.getInstance(keyStoreType);
        FileInputStream keyInputStream = new FileInputStream(identityFilepath);
        try {
            keystore.load(keyInputStream, keyStoreFilePassword.toCharArray());
        } finally {
            keyInputStream.close();
        }
        sslBuilder.loadKeyMaterial(keystore, keyStoreFilePassword.toCharArray());
        final SSLContext sslContext = sslBuilder.build();
        builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setSSLContext(sslContext).setSSLHostnameVerifier(new NoopHostnameVerifier()).setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build()));
    } else {
        builder = builder.setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultIOReactorConfig(IOReactorConfig.custom().setIoThreadCount(threadCount).build()));
    }
    // Configure timeouts
    builder.setRequestConfigCallback(requestConfigBuilder -> requestConfigBuilder.setConnectionRequestTimeout(// Important, otherwise the client has spurious timeouts
    0));
    return builder.build();
}
Also used : RestClient(org.elasticsearch.client.RestClient) SSLContext(javax.net.ssl.SSLContext) IOReactorConfig(org.apache.http.impl.nio.reactor.IOReactorConfig) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) ConfigUtils(org.apache.gobblin.util.ConfigUtils) Batch(org.apache.gobblin.writer.Batch) Future(java.util.concurrent.Future) SSLContexts(org.apache.http.ssl.SSLContexts) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) Nullable(javax.annotation.Nullable) WriteResponse(org.apache.gobblin.writer.WriteResponse) WriteCallback(org.apache.gobblin.writer.WriteCallback) Pair(org.apache.commons.math3.util.Pair) Config(com.typesafe.config.Config) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) IOException(java.io.IOException) KeyStore(java.security.KeyStore) PasswordManager(org.apache.gobblin.password.PasswordManager) FileInputStream(java.io.FileInputStream) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) List(java.util.List) Slf4j(lombok.extern.slf4j.Slf4j) Paths(java.nio.file.Paths) VisibleForTesting(com.google.common.annotations.VisibleForTesting) HttpHost(org.apache.http.HttpHost) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) BatchAsyncDataWriter(org.apache.gobblin.writer.BatchAsyncDataWriter) NoopHostnameVerifier(org.apache.http.conn.ssl.NoopHostnameVerifier) HttpHost(org.apache.http.HttpHost) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) SSLContext(javax.net.ssl.SSLContext) InetSocketTransportAddress(org.elasticsearch.common.transport.InetSocketTransportAddress) KeyStore(java.security.KeyStore) SSLContextBuilder(org.apache.http.ssl.SSLContextBuilder) FileInputStream(java.io.FileInputStream)

Example 20 with RestClient

use of org.graylog.shaded.elasticsearch7.org.elasticsearch.client.RestClient in project incubator-gobblin by apache.

the class RestWriterVariant method getTestClient.

@Override
public TestClient getTestClient(Config config) throws IOException {
    final ElasticsearchRestWriter restWriter = new ElasticsearchRestWriter(config);
    final RestHighLevelClient highLevelClient = restWriter.getRestHighLevelClient();
    return new TestClient() {

        @Override
        public GetResponse get(GetRequest getRequest) throws IOException {
            return highLevelClient.get(getRequest);
        }

        @Override
        public void recreateIndex(String indexName) throws IOException {
            RestClient restClient = restWriter.getRestLowLevelClient();
            try {
                restClient.performRequest("DELETE", "/" + indexName);
            } catch (Exception e) {
            // ok since index may not exist
            }
            String indexSettings = "{\"settings\" : {\"index\":{\"number_of_shards\":1,\"number_of_replicas\":1}}}";
            HttpEntity entity = new StringEntity(indexSettings, ContentType.APPLICATION_JSON);
            Response putResponse = restClient.performRequest("PUT", "/" + indexName, Collections.emptyMap(), entity);
            Assert.assertEquals(putResponse.getStatusLine().getStatusCode(), 200, "Recreate index succeeded");
        }

        @Override
        public void close() throws IOException {
            restWriter.close();
        }
    };
}
Also used : GetResponse(org.elasticsearch.action.get.GetResponse) Response(org.elasticsearch.client.Response) StringEntity(org.apache.http.entity.StringEntity) HttpEntity(org.apache.http.HttpEntity) GetRequest(org.elasticsearch.action.get.GetRequest) RestClient(org.elasticsearch.client.RestClient) RestHighLevelClient(org.elasticsearch.client.RestHighLevelClient) IOException(java.io.IOException)

Aggregations

RestClient (org.elasticsearch.client.RestClient)41 HttpHost (org.apache.http.HttpHost)21 IOException (java.io.IOException)15 Response (org.elasticsearch.client.Response)9 HttpEntity (org.apache.http.HttpEntity)6 BasicHeader (org.apache.http.message.BasicHeader)6 ResponseException (org.elasticsearch.client.ResponseException)6 Test (org.junit.jupiter.api.Test)6 RestClientBuilder (org.elasticsearch.client.RestClientBuilder)5 RestHighLevelClient (org.elasticsearch.client.RestHighLevelClient)5 Test (org.junit.Test)5 ArrayList (java.util.ArrayList)4 AuthScope (org.apache.http.auth.AuthScope)4 ClientProtocolException (org.apache.http.client.ClientProtocolException)4 SearchRequest (org.elasticsearch.action.search.SearchRequest)4 List (java.util.List)3 StringEntity (org.apache.http.entity.StringEntity)3 IndexRequest (org.elasticsearch.action.index.IndexRequest)3 JsonNode (com.fasterxml.jackson.databind.JsonNode)2 TestHazelcastFactory (com.hazelcast.client.test.TestHazelcastFactory)2