How to connect to an Elasticsearch cluster using Java?
To connect to an Elasticsearch cluster, you can utilize Java’s Elasticsearch client library, such as the Elasticsearch Java High Level REST Client.
Here are the steps to connect to an ES cluster:
- First, make sure you have added the Elasticsearch Java High Level REST Client library to your project dependencies. You can do this using build tools like Maven or Gradle.
- In Java code, create an Elasticsearch client instance by using the RestClient.builder() method to create a RestClientBuilder object and configure the REST client with the appropriate host and port.
RestClientBuilder builder = RestClient.builder(
new HttpHost("localhost", 9200, "http"),
new HttpHost("localhost", 9201, "http")
);
RestHighLevelClient client = new RestHighLevelClient(builder);
- Now you can use the client object to perform various operations like indexing, searching, deleting, etc.
For example, to perform a search operation, you can build a search request using SearchRequest and SearchSourceBuilder, and then execute the search using the client.search() method.
SearchRequest searchRequest = new SearchRequest("my_index");
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.matchQuery("title", "java"));
searchRequest.source(searchSourceBuilder);
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
- Remember to close the client connection after you have completed all operations.
client.close();
These are the basic steps for connecting to an ES cluster. You can customize and expand based on your own requirements.