1

I am new to java coming from python. I know there are lot of answers out there to connect ElasticSearch with java. But it is difficult for me to understand and some are outdated. In python, I can easily import elasticsearch module and connect to it.

Here's the Code in python:

from elasticsearch import Elasticsearch
es = Elasticsearch('localhost', port=9200, http_auth=('username', 'password'), scheme="http")

But in java, i have included the elasticsearch maven dependency in pom.xml. I want to connect to elasticsearch. I came to know RestHighLevelClient can do this job. I found this code. But don't know how to make it connect to Elastic Search.

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

Any one can help me or show me some sample code to connect with Elastic Search with java. In python, it was done in two lines. Help me with java.

Paul Steven
  • 93
  • 4
  • 13

2 Answers2

2

For connecting elasticsearch using java you can use the below code:

public class ElasticsearchClient {
//private static final Logger log = LoggerFactory.getLogger(ElasticsearchClient.class);
private final RestHighLevelClient client;

public ElasticsearchClient(ElasticsearchConfig elasticsearchConfig) {
    client = new RestHighLevelClient(RestClient.builder(new HttpHost(elasticsearchConfig.getHost(),
            elasticsearchConfig.getPort(), "http")));
}
}

elasticsearchConfiguration:

host: localhost

port: 9200
  • For more information you can see this and this.

You can even follow instructions from this documentation

You need to add this dependency in pom.xml

<dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>${es.client.version}</version>
</dependency>

Update 1

Instead of separate config file, in order to add host and port inside code itself you can use below mentioned code:

public class ElasticsearchClient {
private static final Logger log = LoggerFactory.getLogger(ElasticsearchClient.class);
private final RestHighLevelClient client;


public ElasticsearchClient(ElasticsearchConfig elasticsearchConfig) {
    client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));
}
ESCoder
  • 15,431
  • 2
  • 19
  • 42
  • @Paul Steven you can go through the updated part of my answer to know how to add host and port inside code itself, instead of separate config file :) – ESCoder Feb 11 '20 at 13:32
  • @Paul Steven are you now able to resolve your query?? – ESCoder Feb 11 '20 at 13:37
  • Thanks.... it worked. I want to get data from elastic search index. Here code in python to get es index data: `query = {'query': {'bool': {'must': [{'match_all': {}}], 'must_not': [], 'should': []}}, 'size': 10000}; results = es.search(index='index name', body=query);` Can u help me in java to get es index data. – Paul Steven Feb 11 '20 at 13:45
  • Where to put the username and password for es in `httpHost` – Paul Steven Feb 12 '20 at 05:38
  • 1
    @PaulSteven you can refer this https://stackoverflow.com/questions/48185570/add-authentication-in-elasticsearch-high-level-client-for-java?r=SearchResults to know how to add authentication for es – ESCoder Feb 12 '20 at 09:52
1

For the current version Java REST Client version 7.5, follow the instructions at ElasticSearch Client:

RestHighLevelClient client = new RestHighLevelClient(
        RestClient.builder(
                new HttpHost("localhost", 9200, "http"),
                new HttpHost("localhost", 9201, "http")));

Maven repository, ElasticSearch Client :

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.5.2</version>
</dependency>

All the API functions are specified at the client website: search, multi-search, index, etc.

The "Java Low Level REST Client" Basic Authentication is defined here:

final CredentialsProvider credentialsProvider =
    new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
    new UsernamePasswordCredentials("user", "password"));

RestClientBuilder builder = RestClient.builder(
    new HttpHost("localhost", 9200))
    .setHttpClientConfigCallback(new HttpClientConfigCallback() {
        @Override
        public HttpAsyncClientBuilder customizeHttpClient(
                HttpAsyncClientBuilder httpClientBuilder) {
            return httpClientBuilder
                .setDefaultCredentialsProvider(credentialsProvider);
        }
    });
tremendows
  • 4,262
  • 3
  • 34
  • 51
  • where to put the username and password of es in httphost? – Paul Steven Feb 12 '20 at 05:51
  • @PaulSteven Answered at the answer. Source from elasticsearch website: https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/_basic_authentication.html – tremendows Feb 12 '20 at 13:59