简体   繁体   中英

How to connect to elasticsearch using java?

I am using elasticsearch 7.3 version, I am very new to this, all i want is to connect to elasticsearch node, i have installed ealasticsearch in one of the google cloud instance now i want to connect to elasticsearch and create index, delete index using java, how can i achieve that, i used this code but its full of error

public class ElasticConnection {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
           TransportClient client = new PreBuiltTransportClient(Settings.EMPTY)
        .addTransportAddress(new TransportAddress(InetAddress.getByName("host1"), 9300))
        .addTransportAddress(new TransportAddress(InetAddress.getByName("host2"), 9300));

// on shutdown

client.close(); 
    }

} 

tell what jar should i add or what should i do, please help me out with this.

Thanks.

Don't use the TransportClient - it is deprecated. use the high level rest client: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high.html .

Also, note that the rest port is 9200, for when using the java high level rest client.

another option that you can use and worth mentioning is Jest: https://github.com/searchbox-io/Jest/tree/master/jest

public RestHighLevelClient createESRestClient() {
    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(esUserName, esPassword));

    RestClientBuilder restClientBuilder = RestClient
            .builder(new HttpHost(esRestclientHost, 9200, "http"));
    // Use this one if your ElasticSearch server is setup to use username & password authentication
    if (esAuthentication) {
        restClientBuilder.setHttpClientConfigCallback(h -> h.setDefaultCredentialsProvider(credentialsProvider));
    }

    return new RestHighLevelClient(restClientBuilder);
}

You can use the following code to create your ElasticSearch connection. RestHighLevelClient is the new client which replaced TransportClient , I suggest that you use RestHighLevelClient .

For your reference this is listed in the ElasticSearch documentation guide: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/7.3/java-rest-high-getting-started-initialization.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM