Setting up your Java app to use Bonsai Elasticsearch is quick and easy. Just follow these simple steps:
Adding the Elasticsearch library
You’ll need to add the
elasticsearch-rest-high-level-client
library to your pom.xml file like so:
org.elasticsearch.client elasticsearch-rest-client 6.2.3
Connecting to Bonsai
Bonsai requires basic authentication for all read/write requests. You’ll need to configure the client so that it includes the username and password when communicating with the cluster. The following code is a good starter for integrating Bonsai Elasticsearch into your app:
package io.omc; import org.apache.http.HttpHost; import org.apache.http.auth.AuthScope; import org.apache.http.auth.UsernamePasswordCredentials; import org.apache.http.client.CredentialsProvider; import org.apache.http.impl.client.BasicCredentialsProvider; import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.net.URI; public class Main { public static void main(String[] args) { String connString = System.getenv("BONSAI_URL"); URI connUri = URI.create(connString); String[] auth = connUri.getUserInfo().split(":"); CredentialsProvider cp = new BasicCredentialsProvider(); cp.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(auth[0], auth[1])); RestHighLevelClient rhlc = new RestHighLevelClient( RestClient.builder(new HttpHost(connUri.getHost(), connUri.getPort(), connUri.getScheme())) .setHttpClientConfigCallback( httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(cp) .setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()))); // https://www.elastic.co/guide/en/elasticsearch/client/java-rest/master/java-rest-high-search.html SearchRequest searchRequest = new SearchRequest(); SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder(); searchSourceBuilder.query(QueryBuilders.matchAllQuery()); searchRequest.source(searchSourceBuilder); try { SearchResponse resp = rhlc.search(searchRequest); // Show that the query worked System.out.println(resp.toString()); } catch (Exception ex) { // Log the exception System.out.println(ex.toString()); } // Need to close the client so the thread will exit try { rhlc.close(); } catch (Exception ex) { } } }
Feel free to adapt that code to your particular app. Keep in mind that the core elements here can be moved around, but really shouldn’t be changed or further simplified.
For example, the snippet above parses out the authentication credentials from the
BONSAI_URL
environment variable. This is so the username and password don’t need to be hard coded into your app, where they could pose a security risk.