SoFunction
Updated on 2025-04-14

Tutorial on using Elasticsearch in Java

1. Introduction to Elasticsearch

Elasticsearch is a distributed search and analysis engine built on Apache Lucene, which can realize real-time data storage, search, and analysis. It is widely used in full-text search, log analysis, performance monitoring and other fields. The core concepts of Elasticsearch include documents, indexes, and shards.

2. Environmental preparation

2.1 Install Elasticsearch

fromElasticsearch official websiteDownload and install the version that suits your operating system.

After the installation is complete, start the Elasticsearch service with the following command:

./bin/elasticsearch

By default, Elasticsearch runs onhttp://localhost:9200

2.2 Java development environment configuration

  • Install the Java SDK (JDK 11 or later).
  • Install Maven or Gradle.
  • Create a Maven project and add dependencies to the Elasticsearch Java client.

2.3 Adding Elasticsearch client dependencies

In the Maven projectAdd the following dependencies to the file:

<dependencies>
    <!-- Elasticsearch Java Client -->
    <dependency>
        <groupId></groupId>
        <artifactId>elasticsearch-java</artifactId>
        <version>8.10.0</version>
    </dependency>
</dependencies>

If you use Gradle, you canAdd the following dependencies to the file:

dependencies {
    implementation ':elasticsearch-java:8.10.0'
}

After adding dependencies, make sure the project compiles normally.

3. Connect to Elasticsearch using Java

Next, we will write a simple Java program to connect to Elasticsearch.

3.1 Writing connection code

Create a Java class, e.g., and write the following code:

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
public class ElasticsearchConnection {
    public static void main(String[] args) throws Exception {
        // Create a REST client        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        // Create a transport layer        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        // Create an Elasticsearch client        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Get cluster information        InfoResponse info = ();
        ("Connected to Elasticsearch cluster: " + ());
        // Close the client        ();
    }
}

3.2 Run the code

Compile and run the program, if successful, you will see an output similar to the following:

Connected to Elasticsearch cluster: elasticsearch

This indicates that you have successfully connected to Elasticsearch.

4. Basic CRUD operation

Elasticsearch's CRUD operation mainly involves adding, checking, modifying, and deleting documents in the index.

4.1 Creating indexes and inserting documents

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
public class ElasticsearchCRUD {
    public static void main(String[] args) throws Exception {
        // Create a REST client        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        // Create a transport layer        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        // Create an Elasticsearch client        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Create a document        String json = "{ \"name\": \"John Doe\", \"age\": 30, \"city\": \"New York\" }";
        // Insert document to index        IndexRequest&lt;Object&gt; request = new &lt;&gt;()
            .index("users")
            .id("1")
            .document(json)
            .build();
        IndexResponse response = (request);
        ("Document inserted with ID: " + ());
        // Close the client        ();
    }
}

4.2 Query documents

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
public class ElasticsearchRead {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Query the document        GetRequest getRequest = new ()
                .index("users")
                .id("1")
                .build();
        GetResponse&lt;Object&gt; response = (getRequest, );
        if (()) {
            ("Document found: " + ());
        } else {
            ("Document not found");
        }
        ();
    }
}

4.3 Update the document

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
import ;
public class ElasticsearchUpdate {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Update the document        Map&lt;String, Object&gt; updateJson = (
                "age", 31,
                "city", "San Francisco"
        );
        UpdateRequest&lt;Object, Map&lt;String, Object&gt;&gt; updateRequest = new &lt;&gt;()
                .index("users")
                .id("1")
                .doc(updateJson)
                .build();
        UpdateResponse&lt;Object&gt; updateResponse = (updateRequest, );
        ("Document updated: " + ());
        ();
    }
}

4.4 Delete a document

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
public class ElasticsearchDelete {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Delete the document        DeleteRequest deleteRequest = new ()
                .index("users")
                .id("1")
                .build();
        DeleteResponse deleteResponse = (deleteRequest);
        ("Document deleted: " + ());
        ();
    }
}

5. Complex query operations

Elasticsearch provides powerful query DSL (Domain Specific Language), supporting boolean queries, range queries, aggregation queries, etc.

5.1 Boolean query

import ;
import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
import ;
public class ElasticsearchBooleanQuery {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Boolean query        SearchRequest searchRequest = new ()
                .index("users")
                .query(Query
                .bool(b -&gt; b
                    .must(m -&gt; (match -&gt; ("name").query("John Doe")))
                    .filter(f -&gt; (r -&gt; ("age").gte(30)))
                ))
                .build();
        SearchResponse&lt;Object&gt; searchResponse = (searchRequest, );
        for (Hit&lt;Object&gt; hit : ().hits()) {
            ("Document found: " + ());
        }
        ();
    }
}

5.2 Scope Query

import ;
import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
import ;
public class ElasticsearchRangeQuery {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Scope query: query documents with age between 25 and 35        SearchRequest searchRequest = new ()
                .index("users")
                .query((r -&gt; ("age").gte(25).lte(35)))
                .build();
        SearchResponse&lt;Object&gt; searchResponse = (searchRequest, );
        for (Hit&lt;Object&gt; hit : ().hits()) {
            ("Document found: " + ());
        }
        ();
    }
}

6. Index management and optimization

In Elasticsearch, index management is a very important operation. Reasonable index setting and optimization can greatly improve query performance.

6.1 Create index and set maps

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
public class ElasticsearchCreateIndex {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Create index and set mapping        CreateIndexRequest createIndexRequest = new ()
                .index("users")
                .mappings(m -&gt; m
                    .properties("name", p -&gt; (t -&gt; t))
                    .properties("age", p -&gt; (i -&gt; i))
                    .properties("city", p -&gt; (t -&gt; t))
                )
                .build();
        CreateIndexResponse createIndexResponse = ().create(createIndexRequest);
        if (()) {
            ("Index created successfully!");
        }
        ();
    }
}

6.2 Delete the index

import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
public class ElasticsearchDeleteIndex {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Delete the index        DeleteIndexRequest deleteIndexRequest = new ()
                .index("users")
                .build();
        DeleteIndexResponse deleteIndexResponse = ().delete(deleteIndexRequest);
        if (()) {
            ("Index deleted successfully!");
        }
        ();
    }
}

7. Aggregation operation

Elasticsearch's aggregation function is very powerful, and it can group data, calculate average, maximum, minimum, and other operations.

7.1 Aggregation query: Calculate the average of age

import ;
import ;
import ;
import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
import ;
import ;
public class ElasticsearchAggregation {
    public static void main(String[] args) throws Exception {
        RestClient restClient = (
                new HttpHost("localhost", 9200, "http")).build();
        RestClientTransport transport = new RestClientTransport(
                restClient, new JacksonJsonpMapper());
        ElasticsearchClient client = new ElasticsearchClient(transport);
        // Aggregation query: Calculate the average age        SearchRequest searchRequest = new ()
                .index("users")
                .size(0)  // No document is returned, only aggregate results are returned                .aggregations("average_age", a -&gt; (avg -&gt; ("age")))
                .build();
        SearchResponse&lt;Object&gt; searchResponse = (searchRequest, );
        double averageAge = ().get("average_age").avg().value();
        ("Average age: " + averageAge);
        ();
    }
}

8. Summary

This tutorial details how to use Elasticsearch in Java, covering connections, basic CRUD operations, complex queries, index management, and aggregation operations. With these examples, developers can learn step by step how to integrate Elasticsearch into Java projects and leverage its powerful search and analytics capabilities to build efficient applications.

This is the end of this article about the tutorial on using Elasticsearch in Java. For more related content on using Elasticsearch in Java, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!