Elasticsearch in Java Applications
Last Updated :
24 Apr, 2025
Elasticsearch is a distributed, free, and public search and analytics engine, that works with all kinds of data, including numerical, textual, geographic, structured, and unstructured. Elasticsearch is lightweight. Elasticsearch has a total dependence size of only about 300 KB. It is just concerned with query performance. This indicates that all database-related processes are well-optimized and scalable. This system has a very high fault tolerance. When one Elasticsearch node in a cluster fails, the master server quickly determines the problem and sends incoming requests as quickly as it can to a replacement node.
How to Use Elasticsearch in Java Applications
Below are the steps to use Elasticsearch in our Java applications.
Prerequisites:
First launch an Elasticsearch instance:
docker run -d --name elastic-test -p 9200:9200 -e "discovery.type=single-node"
-e "xpack.security.enabled=false" docker.elastic.co/elasticsearch/elasticsearch:8.9.3
Elasticsearch by default watches the 9200 port for incoming HTTP requests. By launching a preferred browser and visiting http://localhost:9200/, we can confirm that it has been started successfully:
{
"name": "238170191b08",
"cluster_name": "elasticsearch",
"cluster_uuid": "pvHXz7xsS5W4zlZiiATelw",
"version": {
"number": "6.1.4",
"build_hash": "5b1fea5",
"build_date": "2024-01-12T01:27:58.208Z",
"build_snapshot": false,
"lucene_version": "7.1.0",
"minimum_wire_compatibility_version": "5.6.0",
"minimum_index_compatibility_version": "5.1.0"
},
"tagline": "You Know, for Search"
}
Step 1: Add Maven Dependencies
Let's get right to the Java client now that our main Elasticsearch cluster is operational.Elasticsearch and the Jackson library must first be included to our pom.xml file:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>8.9.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.16.4</version>
</dependency>
Step 2: Elasticsearch Java Client
We can now communicate with Elasticsearch. We will then examine how to carry out the most typical tasks, such adding a document to an index, removing a document from an index, and looking up documents inside an index.
RestClient restClient = RestClient
.builder(HttpHost.create("http://localhost:9200"))
.build();
ElasticsearchTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
ElasticsearchClient client = new ElasticsearchClient(transport);
Step 3: Document Indexing
Adding data to Elastic is the first step towards making them searchable. We'll utilize the ElasticseachClient's.index() function for this:
Person person = new Person(30, "dido datta", new Date(1771468076764L));
IndexResponse response = client.index(i -> i
.index("person")
.id(person.getFullName())
.document(person));
Step 4: Indexed Document Queries
The SearchResponse returned by the.search() function contains Hits. The HitsMetadata can be obtained from the SearchResponse object, and then we can acquire the hits by using the.hits() method once again to receive a List of all the Person objects that match the search request.
String searchText = "Rik";
SearchResponse<Person> searchResponse = client.search(s -> s
.index("person")
.query(q -> q
.match(t -> t
.field("fullName")
.query(searchText))), Person.class);
List<Hit<Person>> hits = searchResponse.hits().hits();
assertEquals(1, hits.size());
assertEquals("Rik Datta", hits.get(0).source().getFullName());
Step 5: Getting Specific Documents by ID
Given a document's id, our goal is to retrieve it first, then remove it. To obtain documents, for example, we utilize the get() method:
String documentId = "Rik Datta";
GetResponse<Person> getResponse = client.get(s -> s
.index("person")
.id(documentId), Person.class);
Person source = getResponse.source();
assertEquals("Rik Datta", source.getFullName());
Step 6: Erasing Specific Documents by ID
Remove a document from an index using the delete() method:
String documentId = dido ";
DeleteResponse response = client.delete(i -> i
.index("person")
.id(documentId));
assertEquals(Result.Deleted, response.result());
assertEquals(" dido datta", response.id());
Step 7: Running the application
Now, let us run the application by performing all the above mentioned operations.
Java
public static void main(String[] args) throws IOException
{
makeConnection();
// Creating a New Person Instance
System.out.println("Inserting a new Person with name Shubham...");
Person person = new Person();
person.setName("Shubham");
person = insertPerson(person);
System.out.println("Person inserted --> " + person);
// Updating the Name of Person
System.out.println("Changing name to `Rik Datta`...");
person.setName("Rik Datta");
// Update Person on the Database
updatePersonById(person.getPersonId(), person);
System.out.println("Person updated --> " + person);
// Getting Person on the Database
System.out.println("Getting Rik...");
Person personFromDB = getPersonById(person.getPersonId());
System.out.println("Person from DB --> " + personFromDB);
// Deleting Person from the Database
System.out.println("Deleting Rik...");
deletePersonById(personFromDB.getPersonId());
System.out.println("Person Deleted");
closeConnection();
}
Output:
Below in the output we have performed all the insert, update, and delete operations.

Similar Reads
API Conventions in Elasticsearch
An API or Application Programming Interface serves as a bridge between different software applications and enables them to communicate effectively. Elasticsearch is a powerful search and analytics engine that provides a robust API that allows users to interact with the Elasticsearch server over HTTP
6 min read
Elasticsearch Aggregations
Elasticsearch is not just a search engine; it's a powerful analytics tool that allows you to gain valuable insights from your data. One of the key features that make Elasticsearch so powerful is its ability to perform aggregations. In this article, we'll explore Elasticsearch aggregations in detail,
4 min read
Metric Aggregation in Elasticsearch
Elasticsearch is a powerful tool not just for search but also for performing complex data analytics. Metric aggregations are a crucial aspect of this capability, allowing users to compute metrics like averages, sums, and more on numeric fields within their data. This guide will delve into metric agg
6 min read
Significant Aggregation in Elasticsearch
Elasticsearch provides a wide range of aggregation capabilities to analyze data in various ways. One powerful aggregation is the Significant Aggregation, which helps identify significant terms or buckets within a dataset. In this guide, we'll delve into the Significant Aggregation in Elasticsearch,
4 min read
Completion suggesters in Elasticsearch
Elasticsearch is a scalable search engine that is based on Apache Lucene and provides numerous capabilities related to full-text search, analytics, and others. Of all these features, the completion suggester can be considered one of the most helpful tools built to improve the search functionality th
5 min read
Bucket Aggregation in Elasticsearch
Elasticsearch is a robust tool not only for full-text search but also for data analytics. One of the core features that make Elasticsearch powerful is its aggregation framework, particularly bucket aggregations. Bucket aggregations allow you to group documents into buckets based on certain criteria,
6 min read
Configuring TLS in Elasticsearch
Transport Layer Security (TLS) is an essential feature for securing communication in Elasticsearch. By encrypting data in transit, TLS helps protect sensitive information from interception and tampering. This article will guide you through configuring TLS in Elasticsearch, complete with examples and
4 min read
Shards and Replicas in Elasticsearch
Elasticsearch, built on top of Apache Lucene, offers a powerful distributed system that enhances scalability and fault tolerance. This distributed nature introduces complexity, with various factors influencing performance and stability. Key among these are shards and replicas, fundamental components
4 min read
Searching Documents in Elasticsearch
Searching documents in Elasticsearch is a foundational skill for anyone working with this powerful search engine. Whether you're building a simple search interface or conducting complex data analysis, understanding how to effectively search and retrieve documents is essential. In this article, we'll
4 min read
Indexing Data in Elasticsearch
In Elasticsearch, indexing data is a fundamental task that involves storing, organizing, and making data searchable. Understanding how indexing works is crucial for efficient data retrieval and analysis. This guide will walk you through the process of indexing data in Elasticsearch step by step, wit
4 min read