Categories

Java

Here's how to set up your Java app to use Bonsai Elasticsearch.
Last updated
July 7, 2023

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 <span class="inline-code"><pre><code>elasticsearch-rest-high-level-client</code></pre></span> 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:

<div class="code-snippet-container"><a fs-copyclip-element="click-2" href="#" class="btn w-button code-copy-button" title="Copy"><img class="copy-image" src="https://global-uploads.webflow.com/63c81e4decde60c281417feb/6483934eeefb356710a1d2e9_icon-copy.svg" loading="lazy" alt=""><img class="copied-image" src="https://assets-global.website-files.com/63c81e4decde60c281417feb/64839e207c2860eb9e6aa572_icon-copied.svg" loading="lazy" alt=""></a><div class="code-snippet"><pre><code fs-codehighlight-element="code" fs-copyclip-element="copy-this-2" class="hljs language-java">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) {

 }
}
}</code></pre></div></div>

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  <span class="inline-code"><pre><code>BONSAI_URL</code></pre></span> 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.

View code snippet
Close code snippet