Spring Boot: Talking to Elasticsearch through JEST (REST api)
If you use Spring Boot with some database you are probably quite familiar with Spring Data project. This way we can use many database systems very standardized way. It includes Elasticsearch using Spring Data Elasticsearch project. Spring Data Elasticsearch talks to ES server using native port and there are situations when we may prefer using REST api here. And if we are in such situation, Jest library comes to rescue. Jest is a Java HTTP Rest client for ElasticSearch and its API is very nice and straightforward. To use it in our Spring Boot application (assuming we have Gradle based app) we simply include …
compile("io.searchbox:jest:2.0.4")
… into build.gradle file as an additional dependency. To use Jest we need JestClient as an entry point. From SpringBoot application perspective, we can define @Service
bean that will create and hold connection object. Such service can be injected in our code later using @Autowire
annotation. Implementation of minimal JestClient service can look like the following one.
@Service
public class JestClientService implements Serializable {
private static final long serialVersionUID = 1L;
JestClient client=null;
@Value("${jest.elasticsearch.host}")
String host;
@Value("${jest.elasticsearch.port}")
String port;
@Value("${jest.elasticsearch.index}")
String indexName;
/**
*
*/
public JestClient getClient() {
if (this.client==null){
GsonFireBuilder fireBuilder = new GsonFireBuilder();
fireBuilder.enableExposeMethodResult();
GsonBuilder builder = fireBuilder.createGsonBuilder();
builder.excludeFieldsWithoutExposeAnnotation();
final Gson gson = builder.setDateFormat(AbstractJestClient.ELASTIC_SEARCH_DATE_FORMAT).create();
System.out.println("Establishing JEST Connection to Elasticsearch over HTTP: "+"http://"+this.host+":"+this.port);
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(new HttpClientConfig
.Builder("http://"+this.host+":"+this.port)
.multiThreaded(true)
.readTimeout(20000)
.gson(gson)
.build());
this.client = factory.getObject();
}
return this.client;
}
}
Jest library contains decent documentation and internal tests come as nice source of examples that are very easy to learn from.