SoFunction
Updated on 2025-04-14

Detailed explanation of Java operation ElasticSearch example

Introduction

Elasticsearch is a distributed search and analysis engine, widely used in full-text search, log analysis and other scenarios. This article describes how to use the Elasticsearch client in Java applications to connect and operate an Elasticsearch cluster.

Environmental preparation

1. Install Elasticsearch

First, make sure that Elasticsearch is installed in your environment. Can​​​Elasticsearch Official Website​​Download the latest version of Elasticsearch and install and start according to the official documentation.

2. Add dependencies

In your Java project, you need to add Elasticsearch's client dependencies. If you are using Maven, you can add the following dependencies in the ​​​​ file:

<dependency>
    <groupId></groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.2</version>
</dependency>

Connect Elasticsearch

1. Create a client

Use the ​​RestHighLevelClient class to create a client that connects to the Elasticsearch cluster.

import ;
import ;
 
public class ElasticsearchClient {
    public static RestHighLevelClient createClient() {
        return new RestHighLevelClient(
            (
                new HttpHost("localhost", 9200, "http")
            )
        );
    }
}

2. Close the client

After all operations are done, remember to close the client to free up the resources.

try {
    ();
} catch (IOException e) {
    ();
}

Basic Operation

1. Create an index

Create a new index and specify some settings and mappings.

import ;
import ;
import ;
import ;
 
public class IndexOperations {
    public static void createIndex(RestHighLevelClient client) throws IOException {
        CreateIndexRequest request = new CreateIndexRequest("test_index");
        ("{\n" +
                "  \"properties\": {\n" +
                "    \"title\": {\n" +
                "      \"type\": \"text\"\n" +
                "    },\n" +
                "    \"content\": {\n" +
                "      \"type\": \"text\"\n" +
                "    }\n" +
                "  }\n" +
                "}", );
        CreateIndexResponse response = ().create(request, );
        ("Index created: " + ());
    }
}

2. Insert data

Insert a document into the index.

import ;
import ;
import ;
 
public class DocumentOperations {
    public static void indexDocument(RestHighLevelClient client) throws IOException {
        String jsonString = "{" +
                "\"title\":\"Elasticsearch Basic Tutorial\"," +
                "\"content\":\"Elasticsearch is a distributed search and analysis engine\"}";
        IndexRequest request = new IndexRequest("test_index").source(jsonString, );
        IndexResponse response = (request, );
        ("Document indexed with ID: " + ());
    }
}

3. Query data

Query the document from the index.

import ;
import ;
 
public class SearchOperations {
    public static void getDocument(RestHighLevelClient client) throws IOException {
        GetRequest request = new GetRequest("test_index", "1");
        GetResponse response = (request, );
        if (()) {
            ("Document found: " + ());
        } else {
            ("Document not found.");
        }
    }
}

With the above steps, you can easily connect and operate an Elasticsearch cluster in your Java application. This article describes how to create clients, create indexes, insert documents, and query documents. These basic operations lay the foundation for more complex usage scenarios.

The above is a simple example of using Java to operate Elasticsearch. Hope it helps you! sure! Elasticsearch is a distributed search and analysis engine, widely used in full-text search, log analysis, real-time application monitoring and other scenarios.

Below is a sample code that uses Java to operate Elasticsearch, including basic operations such as connecting to an ES cluster, creating indexes, inserting documents, querying documents, etc.

Environmental preparation

Add dependencies: Add an Elasticsearch client dependency to your Maven project's ​​​ file.

<dependency>
    <groupId></groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.10.2</version>
</dependency>

Configure Elasticsearch: Make sure you have a running Elasticsearch instance. You can use Docker to quickly start a:

docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "=single-node" elasticsearch:7.10.2

Sample code

Here is a complete Java sample code showing how to connect to an Elasticsearch cluster, create indexes, insert documents, and query documents.

import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
import ;
import ;
import ;
 
public class ElasticsearchExample {
 
    public static void main(String[] args) {
        // Create RestHighLevelClient client        RestHighLevelClient client = new RestHighLevelClient(
                (
                        new HttpHost("localhost", 9200, "http")
                )
        );
 
        try {
            // Create an index            createIndex(client);
 
            // Insert the document            insertDocument(client);
 
            // Query the document            searchDocument(client);
 
        } catch (IOException e) {
            ();
        } finally {
            // Close the client            try {
                ();
            } catch (IOException e) {
                ();
            }
        }
    }
 
    private static void createIndex(RestHighLevelClient client) throws IOException {
        // Create index request        Map&lt;String, Object&gt; mappings = new HashMap&lt;&gt;();
        ("properties", (
                "title", ("type", "text"),
                "content", ("type", "text")
        ));
 
        String mappingJson = (mappings);
        IndexRequest indexRequest = new IndexRequest("my_index")
                .source(mappingJson, );
 
        // Execute the request        IndexResponse indexResponse = (indexRequest, );
        ("Index created: " + ());
    }
 
    private static void insertDocument(RestHighLevelClient client) throws IOException {
        // Create a document        Map&lt;String, Object&gt; document = new HashMap&lt;&gt;();
        ("title", "Elasticsearch Example");
        ("content", "This is an example of using Elasticsearch with Java.");
 
        // Create index request        IndexRequest indexRequest = new IndexRequest("my_index")
                .id("1")
                .source(document);
 
        // Execute the request        IndexResponse indexResponse = (indexRequest, );
        ("Document inserted: " + ());
    }
 
    private static void searchDocument(RestHighLevelClient client) throws IOException {
        // Create a search request        SearchRequest searchRequest = new SearchRequest("my_index");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        (("title", "Elasticsearch"));
        (searchSourceBuilder);
 
        // Execute the request        SearchResponse searchResponse = (searchRequest, );
 
        // Process the response        for (SearchHit hit : ().getHits()) {
            ("Document found: " + ());
        }
    }
}

Code description

  • Create a client: Use RestHighLevelClient​ to connect to the Elasticsearch cluster.
  • Create index: Define the mapping of the index and create the index.
  • Insert Document: Creates a document and inserts it into the specified index.
  • Query Documents: Use a matching query (​matchQuery​) to search for documents containing specific keywords.

Run the code

Make sure your Elasticsearch instance is running and then run the above Java program. You should see the output of index creation, document insertion, and query results.

Hope this example helps you! If you have any questions or need further assistance, feel free to let me know. sure! Elasticsearch is a distributed search and analysis engine, widely used in full-text search, log analysis, real-time application monitoring and other scenarios. Operating Elasticsearch in Java applications usually requires the use of officially provided client libraries such as ​​elasticsearch-rest-high-level-client​ (now stopped updating) or a more modern ​​elasticsearch-java​ client.

The following is a detailed step and sample code that shows how to operate an Elasticsearch instance using the ​​elasticsearch-java​ client in Java:

1. Add dependencies

First, add the dependencies of the Elasticsearch client in your ​​​​ file. Take Maven as an example here:

&lt;dependency&gt;
    &lt;groupId&gt;&lt;/groupId&gt;
    &lt;artifactId&gt;elasticsearch-java&lt;/artifactId&gt;
    &lt;version&gt;8.6.2&lt;/version&gt; &lt;!-- Please select the appropriate version according to the actual situation --&gt;
&lt;/dependency&gt;

2. Create a client

Create an Elasticsearch client instance that communicates with the Elasticsearch cluster.

import ;
import ;
import ;
import .rest_client.RestClientTransport;
import ;
import ;
 
public class ElasticsearchClientExample {
 
    public static ElasticsearchClient createClient() {
        // Create a Rest client        RestClient restClient = (
            new HttpHost("localhost", 9200, "http")
        ).build();
 
        // Create an Elasticsearch client        ElasticsearchTransport transport = new RestClientTransport(
            restClient, new JacksonJsonpMapper()
        );
 
        return new ElasticsearchClient(transport);
    }
}

3. Index Document

Next, we demonstrate how to index (insert) a document into Elasticsearch.

import ;
import ;
import ;
import ;
 
public class IndexDocumentExample {
 
    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = ();
 
        // Create a document object        MyDocument document = new MyDocument();
        (1);
        ("Elasticsearch Java Client Example");
        ("This is an example of using the Elasticsearch Java client.");
 
        // Use ObjectMapper to convert objects to JSON strings        ObjectMapper objectMapper = new ObjectMapper();
        String jsonString = (document);
 
        // Create index request        IndexRequest&lt;MyDocument&gt; request = new &lt;MyDocument&gt;()
            .index("my_index")
            .id((()))
            .document(document)
            .build();
 
        // Execute index request        IndexResponse response = (request);
 
        // Check the response results        if (() == ) {
            ("Document indexed successfully.");
        } else {
            ("Failed to index document.");
        }
 
        // Close the client        ();
    }
}
 
class MyDocument {
    private int id;
    private String title;
    private String content;
 
    // Getters and Setters
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
         = id;
    }
 
    public String getTitle() {
        return title;
    }
 
    public void setTitle(String title) {
         = title;
    }
 
    public String getContent() {
        return content;
    }
 
    public void setContent(String content) {
         = content;
    }
}

4. Query the document

Next, we demonstrate how to query documents in Elasticsearch.

import ;
import ;
import ;
 
public class SearchDocumentExample {
 
    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = ();
 
        // Create a query request        SearchRequest request = new ()
            .index("my_index")
            .query(q -&gt; (m -&gt; ("title").query("Elasticsearch")))
            .build();
 
        // Execute query request        SearchResponse&lt;MyDocument&gt; response = (request, );
 
        // Process query results        for (Hit&lt;MyDocument&gt; hit : ().hits()) {
            MyDocument document = ();
            ("Found document: " + ());
        }
 
        // Close the client        ();
    }
}

5. Delete the document

Finally, we demonstrate how to delete documents in Elasticsearch.

import ;
import ;
import ;
 
public class DeleteDocumentExample {
 
    public static void main(String[] args) throws Exception {
        ElasticsearchClient client = ();
 
        // Create a delete request        DeleteRequest request = new ()
            .index("my_index")
            .id("1")
            .build();
 
        // Execute the delete request        DeleteResponse response = (request);
 
        // Check the response results        if (() == ) {
            ("Document deleted successfully.");
        } else {
            ("Failed to delete document.");
        }
 
        // Close the client        ();
    }
}

Summarize

This article's code shows how to use the ​​elasticsearch-java​ client to perform basic CRUD operations in Java. You can extend these examples based on actual needs, such as handling more complex queries, batch operations, etc.

The above is the detailed explanation of the examples of Java operating ElasticSearch. For more information about Java operating ElasticSearch, please pay attention to my other related articles!