Quarkus - Connecting to an Elasticsearch cluster

Elasticsearch is a well known full text search engine and NoSQL datastore.

In this guide, we will see how you can get your REST services to use an Elasticsearch cluster.

Quarkus provides two ways of accessing Elasticsearch: via the lower level RestClient or via the RestHighLevelClient we will call them the low level and the high level clients.

This technology is considered preview.

In preview, backward compatibility and presence in the ecosystem is not guaranteed. Specific improvements might require to change configuration or APIs and plans to become stable are under way. Feedback is welcome on our mailing list or as issues in our GitHub issue tracker.

For a full list of possible extension statuses, check our FAQ entry.

Prerequisites

To complete this guide, you need:

  • less than 15 minutes

  • an IDE

  • JDK 1.8+ installed with JAVA_HOME configured appropriately

  • Apache Maven 3.6.2+

  • Elasticsearch installed or Docker installed

Architecture

The application built in this guide is quite simple: the user can add elements in a list using a form and the list is updated.

All the information between the browser and the server is formatted as JSON.

The elements are stored in Elasticsearch.

Solution

We recommend that you follow the instructions in the next sections and create the application step by step. However, you can go right to the completed example.

Clone the Git repository: git clone [https://github.com/quarkusio/quarkus-quickstarts.git](https://github.com/quarkusio/quarkus-quickstarts.git), or download an archive.

The solution for the low level client is located in the elasticsearch-rest-client-quickstart directory.

The solution for the high level client is located in the elasticsearch-rest-high-level-client-quickstart directory.

Creating the Maven project

First, we need a new project. Create a new project with the following command:

  1. mvn io.quarkus:quarkus-maven-plugin:1.7.6.Final:create \
  2. -DprojectGroupId=org.acme \
  3. -DprojectArtifactId=elasticsearch-quickstart \
  4. -DclassName="org.acme.elasticsearch.FruitResource" \
  5. -Dpath="/fruits" \
  6. -Dextensions="resteasy-jackson,elasticsearch-rest-client"
  7. cd elasticsearch-quickstart

This command generates a Maven structure importing the RESTEasy/JAX-RS, Jackson, and the Elasticsearch low level client extensions. After this, the quarkus-elasticsearch-rest-client extension has been added to your pom.xml.

If you want to use the high level client instead, replace the elasticsearch-rest-client extension by the elasticsearch-rest-high-level-client extension.

We use the resteasy-jackson extension here and not the JSON-B variant because we will use the Vert.x JsonObject helper to serialize/deserialize our objects to/from Elasticsearch and it uses Jackson under the hood.

If you don’t want to generate a new project, add the following dependencies to your pom.xml.

For the Elasticsearch low level client, add:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-elasticsearch-rest-client</artifactId>
  4. </dependency>

For the Elasticsearch high level client, add:

  1. <dependency>
  2. <groupId>io.quarkus</groupId>
  3. <artifactId>quarkus-elasticsearch-rest-high-level-client</artifactId>
  4. </dependency>

Creating your first JSON REST service

In this example, we will create an application to manage a list of fruits.

First, let’s create the Fruit bean as follows:

  1. package org.acme.elasticsearch;
  2. public class Fruit {
  3. public String id;
  4. public String name;
  5. public String color;
  6. }

Nothing fancy. One important thing to note is that having a default constructor is required by the JSON serialization layer.

Now create a org.acme.elasticsearch.FruitService that will be the business layer of our application and store/load the fruits from the Elasticsearch instance. Here we use the low level client, if you want to use the high level client instead follow the instructions in the Using the High Level REST Client paragraph instead.

  1. package org.acme.elasticsearch;
  2. import java.io.IOException;
  3. import java.util.ArrayList;
  4. import java.util.List;
  5. import javax.enterprise.context.ApplicationScoped;
  6. import javax.inject.Inject;
  7. import org.apache.http.util.EntityUtils;
  8. import org.elasticsearch.client.Request;
  9. import org.elasticsearch.client.Response;
  10. import org.elasticsearch.client.RestClient;
  11. import io.vertx.core.json.JsonArray;
  12. import io.vertx.core.json.JsonObject;
  13. @ApplicationScoped
  14. public class FruitService {
  15. @Inject
  16. RestClient restClient; (1)
  17. public void index(Fruit fruit) throws IOException {
  18. Request request = new Request(
  19. "PUT",
  20. "/fruits/_doc/" + fruit.id); (2)
  21. request.setJsonEntity(JsonObject.mapFrom(fruit).toString()); (3)
  22. restClient.performRequest(request); (4)
  23. }
  24. public Fruit get(String id) throws IOException {
  25. Request request = new Request(
  26. "GET",
  27. "/fruits/_doc/" + id);
  28. Response response = restClient.performRequest(request);
  29. String responseBody = EntityUtils.toString(response.getEntity());
  30. JsonObject json = new JsonObject(responseBody); (5)
  31. return json.getJsonObject("_source").mapTo(Fruit.class);
  32. }
  33. public List<Fruit> searchByColor(String color) throws IOException {
  34. return search("color", color);
  35. }
  36. public List<Fruit> searchByName(String name) throws IOException {
  37. return search("name", name);
  38. }
  39. private List<Fruit> search(String term, String match) throws IOException {
  40. Request request = new Request(
  41. "GET",
  42. "/fruits/_search");
  43. //construct a JSON query like {"query": {"match": {"<term>": "<match"}}
  44. JsonObject termJson = new JsonObject().put(term, match);
  45. JsonObject matchJson = new JsonObject().put("match", termJson);
  46. JsonObject queryJson = new JsonObject().put("query", matchJson);
  47. request.setJsonEntity(queryJson.encode());
  48. Response response = restClient.performRequest(request);
  49. String responseBody = EntityUtils.toString(response.getEntity());
  50. JsonObject json = new JsonObject(responseBody);
  51. JsonArray hits = json.getJsonObject("hits").getJsonArray("hits");
  52. List<Fruit> results = new ArrayList<>(hits.size());
  53. for (int i = 0; i < hits.size(); i++) {
  54. JsonObject hit = hits.getJsonObject(i);
  55. Fruit fruit = hit.getJsonObject("_source").mapTo(Fruit.class);
  56. results.add(fruit);
  57. }
  58. return results;
  59. }
  60. }

In this example you can note the following:

  1. We inject an Elasticsearch low level RestClient into our service.

  2. We create an Elasticsearch request.

  3. We use Vert.x JsonObject to serialize the object before sending it to Elasticsearch, you can use whatever you want to serialize to JSON.

  4. We send the request (indexing request here) to Elasticsearch.

  5. In order to deserialize the object from Elasticsearch, we again use Vert.x JsonObject.

Now, edit the org.acme.elasticsearch.FruitResource class as follows:

  1. @Path("/fruits")
  2. @Produces(MediaType.APPLICATION_JSON)
  3. @Consumes(MediaType.APPLICATION_JSON)
  4. public class FruitResource {
  5. @Inject
  6. FruitService fruitService;
  7. @POST
  8. public Response index(Fruit fruit) throws IOException {
  9. if (fruit.id == null) {
  10. fruit.id = UUID.randomUUID().toString();
  11. }
  12. fruitService.index(fruit);
  13. return Response.created(URI.create("/fruits/" + fruit.id)).build();
  14. }
  15. @GET
  16. @Path("/{id}")
  17. public Fruit get(@PathParam("id") String id) throws IOException {
  18. return fruitService.get(id);
  19. }
  20. @GET
  21. @Path("/search")
  22. public List<Fruit> search(@QueryParam("name") String name, @QueryParam("color") String color) throws IOException {
  23. if (name != null) {
  24. return fruitService.searchByName(name);
  25. } else if (color != null) {
  26. return fruitService.searchByColor(color);
  27. } else {
  28. throw new BadRequestException("Should provide name or color query parameter");
  29. }
  30. }
  31. }

The implementation is pretty straightforward and you just need to define your endpoints using the JAX-RS annotations and use the FruitService to list/add new fruits.

Configuring Elasticsearch

The main property to configure is the URL to connect to the Elasticsearch cluster.

A sample configuration should look like this:

  1. # configure the Elasticsearch client for a cluster of two nodes
  2. quarkus.elasticsearch.hosts = elasticsearch1:9200,elasticsearch2:9200

In this example, we are using a single instance running on localhost:

  1. # configure the Elasticsearch client for a single instance on localhost
  2. quarkus.elasticsearch.hosts = localhost:9200

If you need a more advanced configuration, you can find the comprehensive list of supported configuration properties at the end of this guide.

Running an Elasticsearch cluster

As by default, the Elasticsearch client is configured to access a local Elasticsearch cluster on port 9200 (the default Elasticsearch port), if you have a local running instance on this port, there is nothing more to do before being able to test it!

If you want to use Docker to run an Elasticsearch instance, you can use the following command to launch one:

  1. docker run --name elasticsearch -e "discovery.type=single-node" -e "ES_JAVA_OPTS=-Xms512m -Xmx512m"\
  2. --rm -p 9200:9200 docker.elastic.co/elasticsearch/elasticsearch-oss:{elasticsearch-version}

Creating a frontend

Now let’s add a simple web page to interact with our FruitResource. Quarkus automatically serves static resources located under the META-INF/resources directory. In the src/main/resources/META-INF/resources directory, add a fruits.html file with the content from this fruits.html file in it.

You can now interact with your REST service:

  • start Quarkus with ./mvnw quarkus:dev

  • open a browser to [http://localhost:8080/fruits.html](http://localhost:8080/fruits.html)

  • add new fruits to the list via the ‘Add fruit’ form

  • search for fruits by name or color via the ‘Search Fruit’ form

Using the High Level REST Client

Quarkus provides support for the Elasticsearch High Level REST Client but keep in mind that it comes with some caveats:

  • It drags a lot of dependencies - especially Lucene -, which doesn’t fit well with Quarkus philosophy. The Elasticsearch team is aware of this issue and it might improve sometime in the future.

  • It is tied to a certain version of the Elasticsearch server: you cannot use a High Level REST Client version 7 to access a server version 6.

Here is a version of the FruitService using the high level client instead of the low level one:

  1. import java.io.IOException;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. import javax.enterprise.context.ApplicationScoped;
  5. import javax.inject.Inject;
  6. import org.elasticsearch.action.get.GetRequest;
  7. import org.elasticsearch.action.get.GetResponse;
  8. import org.elasticsearch.action.index.IndexRequest;
  9. import org.elasticsearch.action.search.SearchRequest;
  10. import org.elasticsearch.action.search.SearchResponse;
  11. import org.elasticsearch.client.RequestOptions;
  12. import org.elasticsearch.client.RestHighLevelClient;
  13. import org.elasticsearch.common.xcontent.XContentType;
  14. import org.elasticsearch.index.query.QueryBuilders;
  15. import org.elasticsearch.search.SearchHit;
  16. import org.elasticsearch.search.SearchHits;
  17. import org.elasticsearch.search.builder.SearchSourceBuilder;
  18. import io.vertx.core.json.JsonObject;
  19. @ApplicationScoped
  20. public class FruitService {
  21. @Inject
  22. RestHighLevelClient restHighLevelClient; (1)
  23. public void index(Fruit fruit) throws IOException {
  24. IndexRequest request = new IndexRequest("fruits"); (2)
  25. request.id(fruit.id);
  26. request.source(JsonObject.mapFrom(fruit).toString(), XContentType.JSON); (3)
  27. restHighLevelClient.index(request, RequestOptions.DEFAULT); (4)
  28. }
  29. public Fruit get(String id) throws IOException {
  30. GetRequest getRequest = new GetRequest("fruits", id);
  31. GetResponse getResponse = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
  32. if (getResponse.isExists()) {
  33. String sourceAsString = getResponse.getSourceAsString();
  34. JsonObject json = new JsonObject(sourceAsString); (5)
  35. return json.mapTo(Fruit.class);
  36. }
  37. return null;
  38. }
  39. public List<Fruit> searchByColor(String color) throws IOException {
  40. return search("color", color);
  41. }
  42. public List<Fruit> searchByName(String name) throws IOException {
  43. return search("name", name);
  44. }
  45. private List<Fruit> search(String term, String match) throws IOException {
  46. SearchRequest searchRequest = new SearchRequest("fruits");
  47. SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
  48. searchSourceBuilder.query(QueryBuilders.matchQuery(term, match));
  49. searchRequest.source(searchSourceBuilder);
  50. SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
  51. SearchHits hits = searchResponse.getHits();
  52. List<Fruit> results = new ArrayList<>(hits.getHits().length);
  53. for (SearchHit hit : hits.getHits()) {
  54. String sourceAsString = hit.getSourceAsString();
  55. JsonObject json = new JsonObject(sourceAsString);
  56. results.add(json.mapTo(Fruit.class));
  57. }
  58. return results;
  59. }
  60. }

In this example you can note the following:

  1. We inject an Elasticsearch RestHighLevelClient inside the service.

  2. We create an Elasticsearch index request.

  3. We use Vert.x JsonObject to serialize the object before sending it to Elasticsearch, you can use whatever you want to serialize to JSON.

  4. We send the request to Elasticsearch.

  5. In order to deserialize the object from Elasticsearch, we again use Vert.x JsonObject.

Hibernate Search Elasticsearch

Quarkus supports Hibernate Search with Elasticsearch via the hibernate-search-elasticsearch extension.

Hibernate Search Elasticsearch allows to synchronize your JPA entities to an Elasticsearch cluster and offers a way to query your Elasticsearch cluster using the Hibernate Search API.

If you’re interested in it, you can read the Hibernate Search with Elasticsearch guide.

Cluster Health Check

If you are using the quarkus-smallrye-health extension, both the extension will automatically add a readiness health check to validate the health of the cluster.

So when you access the /health/ready endpoint of your application you will have information about the cluster status. It uses the cluster health endpoint, the check will be down if the status of the cluster is red, or the cluster is not available.

This behavior can be disabled by setting the quarkus.elasticsearch.health.enabled property to false in your application.properties.

Building a native executable

You can use both clients in a native executable.

You can build a native executable with the usual command ./mvnw package -Pnative.

Running it is as simple as executing ./target/elasticsearch-low-level-client-quickstart-1.0-SNAPSHOT-runner.

You can then point your browser to [http://localhost:8080/fruits.html](http://localhost:8080/fruits.html) and use your application.

Conclusion

Accessing an Elasticsearch cluster from a low level or a high level client is easy with Quarkus as it provides easy configuration, CDI integration and native support for it.

Configuration Reference

About the Duration format

The format for durations uses the standard java.time.Duration format. You can learn more about it in the Duration#parse() javadoc.

You can also provide duration values starting with a number. In this case, if the value consists only of a number, the converter treats the value as seconds. Otherwise, PT is implicitly prepended to the value to obtain a standard java.time.Duration format.