Java High Level REST Client 6.3.x を使用して Elasticsearch Java API を呼び出し、ご利用の Alibaba Cloud Elasticsearch クラスターでドキュメントのインデックス作成と削除を行います。
前提条件
開始する前に、以下が準備されていることを確認してください。
-
JDK 1.8 以降がインストールされています。詳細については、「JDK をインストールする」をご参照ください。
-
バージョン 6.3.2 以降の Alibaba Cloud Elasticsearch クラスター。Java High Level REST Client は上位互換性があるため、6.3.2 クライアントは V6.3.2 以降のクラスターと通信できます。クライアントのすべての特徴を使用するには、クライアントバージョンをクラスターバージョンと同じに保ってください。詳細については、「Alibaba Cloud Elasticsearch クラスターの作成」をご参照ください。
-
クラスターに対して自動インデックス作成が有効になっています。詳細については、「YML ファイルの設定」をご参照ください。自動インデックス作成が有効になっていない場合、以下のエラーが報告されます。

-
クラスターのネットワークアクセスが構成済みであること。
-
インターネットアクセス: 「パブリックネットワークアクセス」機能を有効にし、サーバーのパブリック IP アドレスをパブリック IP アドレスホワイトリストに追加します。クライアントがホームネットワークまたはオフィス LAN 内にある場合は、クライアントのプライベート IP アドレスではなく、インターネット出口 IP アドレスをホワイトリストに追加します。
0.0.0.0/0を追加すると、すべての IPv4 アドレスが許可され、セキュリティリスクが生じます。「Elasticsearch クラスターのパブリックまたはプライベート IP アドレスホワイトリストを設定する」をご参照ください。 -
VPC アクセス: 内部エンドポイントを使用します。プライベート IP アドレスホワイトリストはデフォルトで
0.0.0.0/0に設定されているため、ほとんどの場合、追加の構成は不要です。サーバーは、クラスターと同じ仮想プライベートクラウド (VPC) 内にある必要があります。
説明 IP アドレスホワイトリストが設定されていない場合、または設定が正しくない場合は、「接続タイムアウト」エラーが返されます。クライアントから Kibana ノードにアクセスするには、Kibana 用に別途 IP アドレスホワイトリストを設定します。詳細については、「Kibana のパブリックまたはプライベート IP アドレスホワイトリストを設定する」をご参照ください。 -
-
次のセクションの POM 依存関係が
pom.xmlに追加された Java Maven プロジェクト。
POM 依存関係の追加
ご利用の Maven プロジェクトの pom.xml ファイルに次の依存関係を追加します。
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.3.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.20.0</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.20.0</version>
</dependency>
Apache Log4j にリモートコード実行 (RCE) 脆弱性が存在する可能性があります。詳細については、「脆弱性に関するお知らせ | Apache Log4j 2 のリモートコード実行 (RCE) 脆弱性」をご参照ください。
クラスターへの接続
Basic 認証とクラスターエンドポイントを使用して、RestHighLevelClient インスタンスを初期化します。
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.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
// Set up basic access authentication using the cluster username and password.
// These are the same credentials used to log in to the Kibana console.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("<username>", "<password>"));
// Build the client using the cluster endpoint.
// Obtain the endpoint from the Basic Information page of the cluster.
RestClientBuilder builder = RestClient.builder(
new HttpHost("<cluster-endpoint>", 9200, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
RestHighLevelClient client = new RestHighLevelClient(builder);
次のプレースホルダーを実際の値に置き換えます。
| プレースホルダー | 説明 | 場所 |
|---|---|---|
<username> |
クラスターのユーザー名 | クラスター作成時に設定 |
<password> |
クラスターのパスワード | クラスター作成時に設定 |
<cluster-endpoint> |
クラスターのパブリックまたは内部エンドポイント | 基本情報クラスターの ページ |
ドキュメントのインデックス作成
インデックス API を使用して、インデックスにドキュメントを追加します。
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import java.util.HashMap;
import java.util.Map;
// Build the document content as a map.
// Replace field names and values with your own.
Map<String, Object> document = new HashMap<>();
document.put("<field_01>", "<value_01>");
document.put("<field_02>", "<value_02>");
// Specify the index name, type name, and document ID.
IndexRequest indexRequest = new IndexRequest("<index_name>", "<type_name>", "<doc_id>")
.source(document);
IndexResponse indexResponse = client.index(indexRequest);
System.out.println("Indexed document, version: " + indexResponse.getVersion());
ドキュメントの削除
削除 API を使用して、インデックス名、タイプ名、ドキュメント ID でドキュメントを削除します。
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
// Use the same index name, type name, and document ID as when you indexed the document.
DeleteRequest deleteRequest = new DeleteRequest("<index_name>", "<type_name>", "<doc_id>");
DeleteResponse deleteResponse = client.delete(deleteRequest);
System.out.println("Deleted document successfully.");
完全な例
次の例は、クライアントの初期化、ドキュメントのインデックス作成、およびドキュメントの削除を単一の実行可能なプログラムに組み合わせたものです。また、完全なサンプルコードをダウンロードすることもできます。
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.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class RestClientTest63 {
public static void main(String[] args) {
// Set up basic access authentication.
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
new UsernamePasswordCredentials("{Username}", "{Password}"));
// Initialize the client using the cluster endpoint.
RestClientBuilder builder = RestClient.builder(
new HttpHost("{Endpoint of the Elasticsearch cluster}", 9200, "http"))
.setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
@Override
public HttpAsyncClientBuilder customizeHttpClient(
HttpAsyncClientBuilder httpClientBuilder) {
return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
}
});
RestHighLevelClient highClient = new RestHighLevelClient(builder);
try {
// Index a document.
Map<String, Object> jsonMap = new HashMap<>();
jsonMap.put("{field_01}", "{value_01}");
jsonMap.put("{field_02}", "{value_02}");
IndexRequest indexRequest = new IndexRequest("{index_name}", "{type_name}", "{doc_id}")
.source(jsonMap);
IndexResponse indexResponse = highClient.index(indexRequest);
System.out.println("Indexed document, version: " + indexResponse.getVersion());
// Delete the document using the same index name, type name, and document ID.
DeleteRequest deleteRequest = new DeleteRequest("{index_name}", "{type_name}", "{doc_id}");
DeleteResponse deleteResponse = highClient.delete(deleteRequest);
System.out.println("Deleted document successfully.");
highClient.close();
} catch (IOException ioException) {
// Handle exceptions.
}
}
}
次のステップ
サポートされている API の完全なリストについては、「Java High Level REST Client 6.3 ドキュメント」をご参照ください。