This topic describes how to use the Java high-level REST client to call the Elasticsearch document API. This topic also provides sample code for you to connect to an Alibaba Cloud Elasticsearch cluster, create indexes, create documents, and retrieve documents.

Prerequisites

  • Install the JDK and configure Java environment variables.

    In this example, jdk1.8.0_211 is used. We do not guarantee the compatibility of other JDK versions. You can download the JDK from the official website.

  • Prepare a Java program development tool.

    In this example, Eclipse is used. You can choose other tools.

Background information

The sample code provided in this topic is based on Java high-level REST client 6.3.x. We do not guarantee the compatibility of other client versions.

Procedure

  1. Create a Maven project.

    The following figure shows the configuration of the Maven project.

    Figure 1. Select project name and location
    Figure 2. Configure project
  2. Add the following dependencies to the pom.xml file:
    <dependency>
         <groupId>org.elasticsearch.client</groupId>
         <artifactId>elasticsearch-rest-high-level-client</artifactId>
         <version>6.3.2</version>
    </dependency>
  3. Create a package, and create the required Java files in the package.

    The following figure shows the configuration of the package.

    The following figure shows the required Java files.

    The following figure shows the directories in the Maven project.

    • IndexAPI_use.java: creates indexes and documents.
    • UpdateAPI_use.java: updates documents.
    • GetAPI_use.java: retrieves documents.
    • DeleteAPI_use.java: deletes documents.
    Note This example is only for reference. You can also create other Java files to meet your business requirements.
  4. Add the following code to the IndexAPI_use.java file to connect to your Alibaba Cloud Elasticsearch cluster and call the Java IndexRequest operation to create indexes.
    The code snippet is as follows:
    //Connect to the Elasticsearch cluster.
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    
            credentialsProvider.setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials("elastic", "Your password"));
    
    
            RestClientBuilder builder = RestClient.builder(new HttpHost("Your Elasticsearch instance ID.public.elasticsearch.aliyuncs.com", 9200))
                    .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
    
                        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                            return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                        }
                    });
    //Call the Java IndexRequest operation to create an index.
    RestHighLevelClient client = new RestHighLevelClient(builder);
            try {
                IndexRequest request = new IndexRequest();
                request.index("apitest_index");
                request.type("apitest_type");
                request.id("1");
                Map<String, Object> source = new HashMap<>();
                source.put("user", "kimchy");
                source.put("post_date", new Date());
                source.put("message", "trying out Elasticsearch");
                request.source(source);
                try {
                    IndexResponse result = client.index(request);
                    System.out.println(result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } finally {
                client.close();
            }
    You can download the complete sample code from Sample code. The returned result is as follows:
    IndexResponse
    [
    index=apitest_index,
    type=apitest_type,
    id=1,
    version=1,
    result=created,
    seqNo=0,
    primaryTerm=1,
    shards={"total":2,"successful":1,"failed":0}
    ]
  5. Add the following code to the UpdateAPI_use.java file to call the Java UpdateRequest operation to update documents.
    The code snippet is as follows:
    RestHighLevelClient client = new RestHighLevelClient(builder);
         try {
    
                UpdateRequest updateRequest = new UpdateRequest("apitest_index", "apitest_type", "1");
                IndexRequest indexRequest = new IndexRequest("apitest_index", "apitest_type", "1");
                Map<String, String> source = new HashMap<>();
                source.put("user", "dingw2");
                indexRequest.source(source);
                updateRequest.doc(indexRequest);
                UpdateResponse result = client.update(updateRequest);
                System.out.println(result);
    
            }catch (IOException e) {
                    e.printStackTrace();
            } finally {
                client.close();
            }
    You can download the complete code from Sample code. The returned result is as follows:
    UpdateResponse
    [
    index=apitest_index,
    type=apitest_type,
    id=1,
    version=2,
    seqNo=1,
    primaryTerm=1,
    result=updated,
    shards=ShardInfo{
        total=2,
        successful=2,
        failures=[]
      }
    ]
  6. Add the following code to the GetAPI_use.java file to call the Java GetRequest operation to retrieve documents.
    The code snippet is as follows:
    RestHighLevelClient client = new RestHighLevelClient(builder);
         try {
                GetRequest request = new GetRequest("apitest_index", "apitest_type", "1");
                GetResponse result = client.get(request);
                System.out.println(result);
    
            }catch (IOException e) {
                    e.printStackTrace();
            } finally {
                client.close();
            }
    You can download the complete sample code from Sample code. The returned result is as follows:
    {
        "_index": "apitest_index",
        "_type": "apitest_type",
        "_id": "1",
        "_version": 2,
        "found": true,
        "_source": {
            "post_date": "2019-06-10T05:50:52.752Z",
            "message": "trying out Elasticsearch",
            "user": "dingw2"
        }
    }
  7. Add the following code to the DeleteAPI_use.java file to call the Java DeleteRequest operation to delete documents.
    The code snippet is as follows:
    RestHighLevelClient client = new RestHighLevelClient(builder);
         try {
                DeleteRequest request = new DeleteRequest("apitest_index", "apitest_type", "1");
                DeleteResponse result = client.delete(request);
                System.out.println(result);
            } catch(Throwable e) {
                e.printStackTrace();
            } finally {
                client.close();
            }
    You can download the complete sample code from Sample code. The returned result is as follows:
    DeleteResponse
    [
    index=apitest_index,
    type=apitest_type,
    id=1,
    version=3,
    result=deleted,
    shards=ShardInfo{
        total=2,
        successful=2,
        failures=[]
      }
    ]

What to do next

You can call other document API operations to meet your business requirements. For more information about calling other document API operations, see Document API.