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.

3
  • Is your elasticsearch running up?? have you checked it in cmd?? Commented Feb 11, 2020 at 13:05
  • @Vishwa Ratna, Yes, it was running fine in port 9200. Commented Feb 11, 2020 at 13:06
  • Informative: dzone.com/articles/elasticsearch-java-api Commented Feb 11, 2020 at 13:08

2 Answers 2

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")));
}
Sign up to request clarification or add additional context in comments.

5 Comments

@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 :)
@Paul Steven are you now able to resolve your query??
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.
Where to put the username and password for es in httpHost
@PaulSteven you can refer this stackoverflow.com/questions/48185570/… to know how to add authentication for es
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);
        }
    });

2 Comments

where to put the username and password of es in httphost?
@PaulSteven Answered at the answer. Source from elasticsearch website: elastic.co/guide/en/elasticsearch/client/java-rest/current/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.