Elasticsearch in Java Applications
Last Updated :
28 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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker? A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read
CTE in SQL In SQL, a Common Table Expression (CTE) is an essential tool for simplifying complex queries and making them more readable. By defining temporary result sets that can be referenced multiple times, a CTE in SQL allows developers to break down complicated logic into manageable parts. CTEs help with hi
6 min read