Master Elasticsearch with Jest: A Hands‑On Java Client Guide
This tutorial walks you through using Jest, a fluent Java HTTP client for Elasticsearch, covering Maven setup, creating a reusable client, performing CRUD operations, bulk and asynchronous requests, and showcases code examples that illustrate how to manage indices and documents efficiently.
1. Introduction
Anyone who has used Elasticsearch knows that building queries with the REST‑based search API can be tedious and error‑prone.
This tutorial explores Jest, an HTTP Java client for Elasticsearch. While Elasticsearch provides its own native Java client, Jest offers a smoother API and easier‑to‑use interface.
2. Maven Dependency
The first step is to add the Jest library to your POM file:
<dependency>
<groupId>io.searchbox</groupId>
<artifactId>jest</artifactId>
<version>6.3.1</version>
</dependency>Jest's version follows the major version of Elasticsearch, ensuring client‑server compatibility.
3. Using Jest Client
We create a JestClient via JestClientFactory. The client is thread‑safe, so we expose a singleton for the whole application:
public JestClient jestClient() {
JestClientFactory factory = new JestClientFactory();
factory.setHttpClientConfig(
new HttpClientConfig.Builder("http://localhost:9200")
.multiThreaded(true)
.defaultMaxTotalConnectionPerRoute(2)
.maxTotalConnection(10)
.build());
return factory.getObject();
}The client supports proxies, SSL, authentication, and node discovery.
All Jest calls return a JestResult. Use isSucceeded() to check success and getErrorMessage() for details:
JestResult jestResult = jestClient.execute(new Delete.Builder("1").index("employees").build());
if (jestResult.isSucceeded()) {
System.out.println("Success!");
} else {
System.out.println("Error: " + jestResult.getErrorMessage());
}3.1. Index Management
Check if an index exists:
JestResult result = jestClient.execute(new IndicesExists.Builder("employees").build());Create an index:
jestClient.execute(new CreateIndex.Builder("employees").build());Customize settings:
Map<String, Object> settings = new HashMap<>();
settings.put("number_of_shards", 11);
settings.put("number_of_replicas", 2);
jestClient.execute(new CreateIndex.Builder("employees").settings(settings).build());Modify aliases:
jestClient.execute(new ModifyAliases.Builder(
new AddAliasMapping.Builder("employees", "e").build()).build());
jestClient.execute(new ModifyAliases.Builder(
new RemoveAliasMapping.Builder("employees", "e").build()).build());3.2. Creating Documents
Index a JSON document directly:
{
"name": "Michael Pratt",
"title": "Java Developer",
"skills": ["java", "spring", "elasticsearch"],
"yearsOfService": 2
}Using Jackson to build JSON:
ObjectMapper mapper = new ObjectMapper();
JsonNode employeeJsonNode = mapper.createObjectNode()
.put("name", "Michael Pratt")
.put("title", "Java Developer")
.put("yearsOfService", 2)
.set("skills", mapper.createArrayNode().add("java").add("spring").add("elasticsearch"));
jestClient.execute(new Index.Builder(employeeJsonNode.toString()).index("employees").build());Or using a Java Map:
Map<String, Object> employeeHashMap = new LinkedHashMap<>();
employeeHashMap.put("name", "Michael Pratt");
employeeHashMap.put("title", "Java Developer");
employeeHashMap.put("yearsOfService", 2);
employeeHashMap.put("skills", Arrays.asList("java", "spring", "elasticsearch"));
jestClient.execute(new Index.Builder(employeeHashMap).index("employees").build());Or a POJO:
public class Employee {
String name;
String title;
List<String> skills;
int yearsOfService;
}
Employee employee = new Employee();
employee.setName("Michael Pratt");
employee.setTitle("Java Developer");
employee.setYearsOfService(2);
employee.setSkills(Arrays.asList("java", "spring", "elasticsearch"));
jestClient.execute(new Index.Builder(employee).index("employees").build());3.3. Reading Documents
Get a document by ID:
jestClient.execute(new Get.Builder("employees", "17").build());Retrieve the source as JSON or deserialize to a DTO:
Employee getResult = jestClient.execute(new Get.Builder("employees", "1").build())
.getSourceAsObject(Employee.class);Search queries can be sent as JSON strings or built with Jackson. The client returns SearchResult.Hit objects that include metadata such as score and routing.
List<SearchResult.Hit<Employee, Void>> hits =
jestClient.execute(new Search.Builder(search).build())
.getHits(Employee.class);
for (SearchResult.Hit<Employee, Void> hit : hits) {
System.out.println(String.format("Document %s has score %s", hit.id, hit.score));
}3.4. Updating Documents
Update via the Update operation:
employee.setYearOfService(3);
jestClient.execute(new Update.Builder(employee).index("employees").id("1").build());3.5. Deleting Documents
Delete by ID:
jestClient.execute(new Delete.Builder("17").index("employees").build());4. Bulk Operations
Combine multiple actions in a single request:
jestClient.execute(new Bulk.Builder()
.defaultIndex("employees")
.addAction(new Index.Builder(employeeObject1).build())
.addAction(new Index.Builder(employeeObject2).build())
.addAction(new Delete.Builder("17").build())
.build());5. Asynchronous Operations
Execute operations without blocking using executeAsync and a JestResultHandler:
jestClient.executeAsync(
new Index.Builder(employeeObject1).build(),
new JestResultHandler<JestResult>() {
@Override public void completed(JestResult result) {
// handle result
}
@Override public void failed(Exception ex) {
// handle exception
}
});6. Conclusion
This tutorial introduced the Jest client, a robust RESTful Java client for Elasticsearch. Its fluent builder API, full support for Elasticsearch features, and ability to perform synchronous, bulk, and asynchronous operations make it a compelling alternative to the native client.
All code examples are available on the project's GitHub page.
Original source: https://www.baeldung.com/elasticsearch-jest
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
