このドキュメントでは、Elasticsearc Java API の使用方法について説明します。 Java High Level REST Client 6.7.x を例として使用しています。

前提条件

  • JDK がインストールされていること。 JDK のバージョンは 1.8 以降である必要があります。
  • Alibaba Cloud Elasticsearch インスタンスが作成されていること。 インスタンスのバージョンは、高レベルクライアントのバージョン以上である必要があります。 このドキュメントでは、バージョン 6.7.0 のインスタンスが作成されます。
    重要 高レベルのクライアントは上位互換性があります。 たとえば、バージョン 6.7.0 の高レベルクライアントは、バージョン 6.7.0 以降のバージョンの Elasticsearch クラスターと通信できます。 最新のクライアントの機能を使用できるようにするには、クラスターバージョンと同じ高レベルのクライアントバージョンを使用することを推奨します。
  • Java Maven プロジェクトを作成し、 Pom 依存関係を Java プロジェクトの pom.xml ファイルに追加していること。 pom 依存関係の追加
    このドキュメントでは、Elasticsearch 6.7.0 を例として使用しています。

Pom 依存関係

<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>6.7.0</version>
</dependency>

RequestOptions

REST クライアント 6.3.2 と比べて、バージョン 6.7.0 には RequestOptions クラスが追加されています。 通常の Elasticsearch リクエストに影響を与えることなくオプションを指定できます。

次のサンプルコードでは、ResponseConsumer 設定を調整して、Java 仮想マシン (JVM) メモリが制限されているクライアント環境で非同期応答が使用するキャッシュのサイズを制限しています。 すべてのサンプルコードの詳細については、「」をご参照ください。

private static final RequestOptions COMMON_OPTIONS;

static {
    RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();

    // The default cache size is 100 MB. Change it to 30 MB.
    builder.setHttpAsyncResponseConsumerFactory(
            new HttpAsyncResponseConsumerFactory
                    .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
    COMMON_OPTIONS = builder.build();
}
// Run the following command in parallel and use the custom RequestOptions (COMMON_OPTIONS).
IndexResponse indexResponse = highClient.index(indexRequest, COMMON_OPTIONS);

RequestOptions クラスの使用方法の詳細については、 『RequestOptions』をご参照ください。

次のコードは、 RequestOptions のすべてのサンプルコードです。 サンプルコードでは index API を使用してドキュメントのインデックスを作成し、 delete API を使用してドキュメントを削除します。 ResponseConsumer 設定を調整して、Java 仮想マシン (JVM) メモリが制限されているクライアント環境で非同期応答が使用するキャッシュのサイズを制限しています。

// The file path is src/main/java/RestClientTest67.java.
import org.apache.http.HttpHost;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.nio.client.HttpAsyncClientBuilder;

import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class RestClientTest67 {

    private static final RequestOptions COMMON_OPTIONS;

    static {
        RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder();

        // The default cache size is 100 MB. Change it to 30 MB.
        builder.setHttpAsyncResponseConsumerFactory(
                new HttpAsyncResponseConsumerFactory
                        .HeapBufferedResponseConsumerFactory(30 * 1024 * 1024));
        COMMON_OPTIONS = builder.build();
    }

    public static void main(String[] args) {
        // The Alibaba Cloud Elasticsearch cluster requires basic authentication.
        final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
       // Use the username and password that you have specified when creating the Alibaba Cloud Elasticsearch instance. The username and password are also used to log on to the Kibana console.
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("{username}", "{password}");

        // Create a REST client by using the builder and configure HttpClientConfigCallback for the HTTP client.
       // Click the ID of the Elasticsearch instance. On the Basic Information page, obtain the public IP address of the Elasticsearch cluster.
        RestClientBuilder builder = RestClient.builder(new HttpHost("{Elasticsearch cluster address}", 9200))
                .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
                    @Override
                    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
                    }
                });

        // Create a RestHighLevelClient instance by using the REST low-level client builder.
        RestHighLevelClient highClient = new RestHighLevelClient(builder);

        try {
            // Create a request.
            Map<String, Object> jsonMap = new HashMap<>();
           // field_01 and field_02 are the field names, and value_01 and value_02 are the corresponding values.
           jsonMap.put("{field_01}", "{value_01}");
           jsonMap.put("{field_02}", "{value_02}");
           // index_nameはインデックス名、type_nameはタイプ名、doc_idはドキュメントIDです。
           IndexRequest indexRequest = new IndexRequest("{index_name}", "{type_name}", "{doc_id}").source(jsonMap);

            // Run the following command in parallel and use the custom RequestOptions (COMMON_OPTIONS).
            IndexResponse indexResponse = highClient.index(indexRequest, COMMON_OPTIONS);

            long version = indexResponse.getVersion();

            System.out.println("Index document successfully! " + version);
            // index_name is the index name, type_name is the type name, and doc_id is the document ID. The index name, type name, and document ID are the same as that you have specified when creating the index.
            DeleteRequest request = new DeleteRequest("{index_name}", "{type_name}", "{doc_id}");
            DeleteResponse deleteResponse = highClient.delete(request, COMMON_OPTIONS);

            System.out.println("Delete document successfully! \n" + deleteResponse.toString() + "\n" + deleteResponse.status());

            highClient.close();

        } catch (IOException ioException) {
            // Handle exceptions.
        }
    }
}

中括弧 {} 内に含まれる前述のサンプルコードのパラメーターを、サービス固有のパラメーターに置き換えることができます。 詳細については、コードのコメントをご参照ください。