You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Java操作Elasticsearch集群及引入官方Java Rest Client

Hey there! Great that you've got Elasticsearch up and running locally. Let's tackle your two questions clearly with practical, easy-to-follow examples:

1. How to add the official Elasticsearch Java Rest Client to your project

First critical note: make sure the client version matches your Elasticsearch server version exactly—this avoids weird compatibility bugs. Here's how to set it up for common build tools:

For Maven projects

Add these dependencies to your pom.xml:

<dependencies>
    <!-- Rest High Level Client (the user-friendly wrapper recommended for most use cases) -->
    <dependency>
        <groupId>org.elasticsearch.client</groupId>
        <artifactId>elasticsearch-rest-high-level-client</artifactId>
        <version>YOUR_ES_VERSION</version>
    </dependency>
    <!-- Core Elasticsearch dependency (required for client functionality) -->
    <dependency>
        <groupId>org.elasticsearch</groupId>
        <artifactId>elasticsearch</artifactId>
        <version>YOUR_ES_VERSION</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

For Gradle projects

Add these lines to your build.gradle (Groovy DSL):

dependencies {
    implementation 'org.elasticsearch.client:elasticsearch-rest-high-level-client:YOUR_ES_VERSION'
    implementation 'org.elasticsearch:elasticsearch:YOUR_ES_VERSION'
}

Replace YOUR_ES_VERSION with the version of your local Elasticsearch instance (e.g., 8.10.0 if that's what you installed).


2. Simple CRUD operations with Java

We'll use the RestHighLevelClient (the most intuitive option for basic operations) for these examples. Let's start with setting up the client connection, then walk through each operation.

Step 1: Initialize the client

We'll use try-with-resources to ensure the client closes automatically when we're done:

import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.apache.http.HttpHost;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.time.LocalDate;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.xcontent.XContentType;

public class ElasticsearchCrudDemo {
    private static RestHighLevelClient createClient() {
        return new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("localhost", 9200, "http")));
    }

    public static void main(String[] args) {
        try (RestHighLevelClient client = createClient()) {
            // Run CRUD operations in sequence
            indexDocument(client);
            getDocument(client);
            updateDocument(client);
            deleteDocument(client);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Step 2: Index a new document

This adds a document to an index (the index will be created automatically if it doesn't exist):

private static void indexDocument(RestHighLevelClient client) throws IOException {
    // Define document content as a map (you can also use a JSON string)
    Map<String, Object> book = new HashMap<>();
    book.put("title", "Elasticsearch for Java Developers");
    book.put("author", "Jane Smith");
    book.put("publish_date", LocalDate.now().toString());
    book.put("pages", 320);

    IndexRequest request = new IndexRequest("books") // Name of your index
            .id("1") // Optional: Elasticsearch generates a random ID if you omit this
            .source(book, XContentType.JSON);

    IndexResponse response = client.index(request, org.elasticsearch.client.RequestOptions.DEFAULT);
    System.out.println("Index result: " + response.getResult());
}

Step 3: Retrieve a document

Fetch the document we just added:

private static void getDocument(RestHighLevelClient client) throws IOException {
    GetRequest request = new GetRequest("books", "1"); // Index name + document ID
    GetResponse response = client.get(request, org.elasticsearch.client.RequestOptions.DEFAULT);

    if (response.isExists()) {
        System.out.println("Retrieved document: " + response.getSourceAsString());
    } else {
        System.out.println("Document not found!");
    }
}

Step 4: Update a document

Modify specific fields of the existing document:

private static void updateDocument(RestHighLevelClient client) throws IOException {
    UpdateRequest request = new UpdateRequest("books", "1");
    // Update the page count and add a new rating field
    Map<String, Object> updates = new HashMap<>();
    updates.put("pages", 345);
    updates.put("rating", 4.7);
    request.doc(updates, XContentType.JSON);

    UpdateResponse response = client.update(request, org.elasticsearch.client.RequestOptions.DEFAULT);
    System.out.println("Update result: " + response.getResult());
}

For more complex updates (like incrementing a number field), you can use Elasticsearch scripts instead of a simple field map.

Step 5: Delete a document

Remove the document from the index:

private static void deleteDocument(RestHighLevelClient client) throws IOException {
    DeleteRequest request = new DeleteRequest("books", "1");
    DeleteResponse response = client.delete(request, org.elasticsearch.client.RequestOptions.DEFAULT);
    System.out.println("Delete result: " + response.getResult());
}
}

Quick notes

  • If you've enabled Elasticsearch security (username/password auth) on your local instance, you'll need to add credentials to the client builder using an HttpClientConfigCallback.
  • In production code, replace the stack trace print with proper error handling (e.g., logging, user-friendly messages).

内容的提问来源于stack exchange,提问作者D vignesh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:02:30