すべてのプロダクト
Search
ドキュメントセンター

PolarDB:クライアントを使用して PolarSearch に接続する

最終更新日:Nov 09, 2025

PolarSearch は、公式の OpenSearch クライアントと完全に互換性があります。これらのクライアントを使用して、Java や Python などの一般的なプログラミング言語を通じて PolarSearch と対話できます。これにより、インデックスを効率的に管理し、ドキュメント操作 (作成、削除、更新、クエリ) を実行し、複雑な検索を実行して、検索機能をアプリケーションにシームレスに統合できます。

準備

  1. PolarSearch ノードを含むクラスターを作成し、ノードの管理者アカウントを設定します

  2. エンドポイントを取得します: クラスターの [データベースノード] セクションで、[検索ノード] にマウスをかざして、PolarSearch ノードの非公開またはパブリックエンドポイントを取得します。

クラスターへの接続

Java クライアント

1. トランスポートレイヤーを選択して依存関係を追加する

OpenSearch Java クライアントは、HTTP リクエストを処理するためのトランスポートレイヤーフレームワークを必要とします。プロジェクトには Apache HttpClient5 または RestClient のいずれかを選択できます。

Apache HttpClient5 (推奨)

  • Maven
    pom.xml ファイルに、次の依存関係を追加します:

    <!-- OpenSearch Java クライアントコアライブラリ -->
    <dependency>
      <groupId>org.opensearch.client</groupId>
      <artifactId>opensearch-java</artifactId>
      <version>2.19.0</version>
    </dependency>
    
    <!-- Apache HttpClient5 トランスポートレイヤー -->
    <dependency>
      <groupId>org.apache.httpcomponents.client5</groupId>
      <artifactId>httpclient5</artifactId>
      <version>5.2.1</version>
    </dependency>
  • Gradle
    build.gradle ファイルに、次の依存関係を追加します:

    dependencies {
        // OpenSearch Java クライアントコアライブラリ
        implementation 'org.opensearch.client:opensearch-java:2.19.0'
        
        // Apache HttpClient5 トランスポートレイヤー
        implementation 'org.apache.httpcomponents.client5:httpclient5:5.2.1'
    }

RestClient

  • Maven
    pom.xml ファイルに、次の依存関係を追加します:

    <!-- OpenSearch Java クライアントコアライブラリ -->
    <dependency>
      <groupId>org.opensearch.client</groupId>
      <artifactId>opensearch-java</artifactId>
      <version>2.19.0</version>
    </dependency>
    
    <!-- RestClient トランスポートレイヤー -->
    <dependency>
      <groupId>org.opensearch.client</groupId>
      <artifactId>opensearch-rest-client</artifactId>
      <version>2.19.0</version>
    </dependency>
  • Gradle
    build.gradle ファイルに、次の依存関係を追加します:

    dependencies {
        // OpenSearch Java クライアントコアライブラリ
        implementation 'org.opensearch.client:opensearch-java:2.19.0'
    
        // RestClient トランスポートレイヤー
        implementation 'org.opensearch.client:opensearch-rest-client:2.19.0'
    }

2. データクラスを設定する

テストデータクラスを作成して、PolarSearch の機能をテストできます。

static class IndexData {
      private String title;
      private String text;
  
      public IndexData() {}
  
      public IndexData(String title, String text) {
          this.title = title;
          this.text = text;
      }
  
      public String getTitle() {
          return title;
      }
  
      public void setTitle(String title) {
          this.title = title;
      }
  
      public String getText() {
          return text;
      }
  
      public void setText(String text) {
          this.text = text;
      }
  
      @Override
      public String toString() {
          return String.format("IndexData{title='%s', text='%s'}", title, text);
      }
  }

3. クライアントを初期化する

選択したトランスポートレイヤーに基づいて、PolarSearch の接続情報でクライアントを初期化します。アプリケーションでは、PolarSearch の詳細を環境変数として設定するか、テスト用にデフォルトのパラメーター値として直接割り当てることができます。

Apache HttpClient5

次の例は、クライアントを初期化する方法を示しています。このサンプルコードは SSL を無効にします。

import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.opensearch.client.json.jackson.JacksonJsonpMapper;
import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBuilder;

public class CreateClient {
  public static void main(String[] args) throws Exception {
    var env = System.getenv();
    var hostname = env.getOrDefault("HOST", "<polarsearch_host>");
    var port = Integer.parseInt(env.getOrDefault("PORT", "<polarsearch_port>"));
    var user = env.getOrDefault("USERNAME", "<polarsearch_username>");
    var pass = env.getOrDefault("PASSWORD", "<polarsearch_password>");

    final var hosts = new HttpHost[] { new HttpHost("http", hostname, port) };

    final var sslContext = SSLContextBuilder.create().loadTrustMaterial(null, (chains, authType) -> true).build();

    final var transport = ApacheHttpClient5TransportBuilder.builder(hosts)
            .setMapper(new JacksonJsonpMapper())
            .setHttpClientConfigCallback(httpClientBuilder -> {
                final var credentialsProvider = new BasicCredentialsProvider();
                for (final var host : hosts) {
                    credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(user, pass.toCharArray()));
                }

                // ローカルのテストクラスターは自己署名証明書を使用するため、SSL/TLS 検証を無効にします
                final var tlsStrategy = ClientTlsStrategyBuilder.create()
                        .setSslContext(sslContext)
                        .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                        .build();

                final var connectionManager = PoolingAsyncClientConnectionManagerBuilder.create().setTlsStrategy(tlsStrategy).build();

                return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(connectionManager);
            })
            .build();

    OpenSearchClient client = new OpenSearchClient(transport);
  }
}

RestClient

次の例は、クライアントを初期化する方法を示しています。このサンプルコードは SSL を無効にします。

import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.opensearch.client.RestClient;
import org.opensearch.client.json.jackson.JacksonJsonpMapper;
import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.transport.rest_client.RestClientTransport;

public class CreateRestClient {
  public static void main(String[] args) throws Exception {
    var env = System.getenv();
    var hostname = env.getOrDefault("HOST", "<polarsearch_host>");
    var port = Integer.parseInt(env.getOrDefault("PORT", "<polarsearch_port>"));
    var user = env.getOrDefault("USERNAME", "<polarsearch_username>");
    var pass = env.getOrDefault("PASSWORD", "<polarsearch_password>");
    
    final org.apache.http.HttpHost[] restHosts = new org.apache.http.HttpHost[] {new org.apache.http.HttpHost(hostname, port, "http")};


    RestClient restClient = RestClient.builder(restHosts)
            .setHttpClientConfigCallback(httpClientBuilder -> {
                final org.apache.http.impl.client.BasicCredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
                for (final org.apache.http.HttpHost ignored : restHosts) {
                    credentialsProvider.setCredentials(org.apache.http.auth.AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials(user, pass));
                }

                try {
                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                            // テストクラスターはデフォルトのセキュリティ構成を使用しているだけなので、証明書を無効にします
                            .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                            .setSSLContext(SSLContextBuilder.create().loadTrustMaterial(null, (chains, authType) -> true).build());
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }).build();

    final RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
    final OpenSearchClient client = new OpenSearchClient(transport);
  }
}

4. 基本操作を実行する

次のコードスニペットは、一般的なインデックスおよびドキュメント操作を実行する方法を示しています。

インデックスの作成

String index = "sample-index";
CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index).build();
client.indices().create(createIndexRequest);

ドキュメントへの書き込み

IndexData indexData = new IndexData("first_name", "Bruce");
IndexRequest<IndexData> indexRequest = new IndexRequest.Builder<IndexData>().index(index).id("1").document(indexData).build();
client.index(indexRequest);

ドキュメントの検索

SearchResponse<IndexData> searchResponse = client.search(s -> s.index(index), IndexData.class);
for (int i = 0; i< searchResponse.hits().hits().size(); i++) {
  System.out.println(searchResponse.hits().hits().get(i).source());
}

ドキュメントの削除

client.delete(b -> b.index(index).id("1"));

インデックスの削除

DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(index).build();
DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);

Java 高レベル REST クライアント

Java 高レベル REST クライアントは OpenSearch で非推奨となり、将来のバージョンではサポートされないため、Java クライアントを使用することをお勧めします。

1. 依存関係の追加

pom.xml ファイルに、次の依存関係を追加します:

<!-- OpenSearch Java 高レベル REST クライアントコアライブラリ -->
<dependency>
  <groupId>org.opensearch.client</groupId>
  <artifactId>opensearch-rest-high-level-client</artifactId>
  <version>2.19.0</version>
</dependency>

2. 安全な接続を構成する

REST クライアントを使用する前に、セキュリティプラグインに接続するようにアプリケーションのトラストストアを構成する必要があります。

  • 信頼できる認証局 (CA) によって発行された証明書を使用する場合、追加の構成は必要ありません。

  • テスト環境やデモ環境などで自己署名証明書を使用する場合は、次のコマンドを使用してカスタムトラストストアを作成し、そこにルート CA 証明書を追加できます。

    1. トラストストアを作成して証明書をインポートする:
      Java の keytool ユーティリティを使用して、ルート CA 証明書を truststore.jks などの新しいトラストストアファイルにインポートします。

      keytool -importcert -file <path/to/your/root-ca.pem> -alias <certificate_alias> -keystore <path/to/your/truststore.jks>

      このコマンドを実行すると、新しいトラストストアのパスワードを設定するように求められます。

    2. アプリケーションでトラストストアを指定する:
      Java アプリケーションの起動時に、作成したトラストストアを使用するように Java 仮想マシン (JVM) に指示するシステムプロパティを設定します。

      // クライアント初期化コードの前に実行
      System.setProperty("javax.net.ssl.trustStore", "/full_path/to/your/truststore.jks");
      System.setProperty("javax.net.ssl.trustStorePassword", "password-for-truststore");
説明

セキュリティ機能の構成で問題が発生した場合は、公式の OpenSearch FAQ および TLS トラブルシューティングドキュメントをご参照ください。

3. クライアントを初期化する

アプリケーションでは、次のコードに示すように、PolarSearch の詳細を環境変数として設定するか、テスト用にデフォルトのパラメーター値として直接割り当てることができます。

// デモンストレーション目的のみ。本番コードに認証情報をハードコーディングしないでください。
// 基本認証の認証情報を設定します。
final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY,
  new UsernamePasswordCredentials("<polarsearch_username>", "<polarsearch_password>"));

// RestClient をビルドし、HTTP クライアント設定コールバックを設定して認証情報を適用します。
RestClientBuilder builder = RestClient.builder(new HttpHost("<polarsearch_host>", <polarsearch_port>, "https"))
  .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
    @Override
    public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
      return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    }
  });
// RestHighLevelClient インスタンスを作成します。
RestHighLevelClient client = new RestHighLevelClient(builder);

4. 基本操作を実行する

次のコードスニペットは、一般的なインデックスおよびドキュメント操作を実行する方法を示しています。

インデックスの作成

// カスタム設定とマッピングでインデックスを作成
CreateIndexRequest createIndexRequest = new CreateIndexRequest("custom-index");
createIndexRequest.settings(Settings.builder() 
  .put("index.number_of_shards", 4)
  .put("index.number_of_replicas", 3)
  );
HashMap<String, String> typeMapping = new HashMap<String,String>();
typeMapping.put("type", "integer");
HashMap<String, Object> ageMapping = new HashMap<String, Object>();
ageMapping.put("age", typeMapping);
HashMap<String, Object> mapping = new HashMap<String, Object>();
mapping.put("properties", ageMapping);
createIndexRequest.mapping(mapping);
CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

ドキュメントへの書き込み

// インデックスにデータを追加
IndexRequest request = new IndexRequest("custom-index");
request.id("1");

HashMap<String, String> stringMapping = new HashMap<String, String>();
stringMapping.put("message:", "Testing Java REST client");
request.source(stringMapping);
IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);

ドキュメントの検索

GetRequest getRequest = new GetRequest("custom-index", "1");
GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
System.out.println("Retrieved document: " + getResponse.getSourceAsString());

ドキュメントの削除

DeleteRequest deleteDocumentRequest = new DeleteRequest("custom-index", "1");
DeleteResponse deleteResponse = client.delete(deleteDocumentRequest, RequestOptions.DEFAULT);
System.out.println("Document deleted with result: " + deleteResponse.getResult());

インデックスの削除

DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("custom-index");
AcknowledgedResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
System.out.println("Index deletion acknowledged: " + deleteIndexResponse.isAcknowledged());

低レベル Python クライアント

高レベル Python クライアントは OpenSearch バージョン 2.1.0 以降非推奨となっているため、低レベル Python クライアントを使用することをお勧めします。

1. 環境を構成する

  1. プロジェクトディレクトリに移動します。この例では /home/PolarSearchTestPython を使用します。

    mkdir /home/PolarSearchTestPython
    cd /home/PolarSearchTestPython
  2. /home/PolarSearchTestPython ディレクトリで、仮想環境 (venv) を作成してプロジェクトの依存関係を分離し、グローバル環境との競合を回避します。

    python3 -m venv myenv
  3. 仮想環境をアクティブ化します。

    source myenv/bin/activate
  4. 必要な Python 依存関係ライブラリをインストールします。

    pip3 install opensearch-py

2. PolarSearch に接続する

Python コードで、OpenSearch クラスをインポートし、PolarSearch の接続情報でクライアントインスタンスを作成します。アプリケーションでは、PolarSearch の詳細を環境変数として設定するか、テスト用にデフォルトのパラメーター値として直接割り当てることができます。

from opensearchpy import OpenSearch

host = os.getenv("HOST", default="<polarsearch_host>")
port = int(os.getenv("PORT", <polarsearch_port>))
auth = (os.getenv("USERNAME", "<polarsearch_username>"), os.getenv("PASSWORD", "<polarsearch_password>"))

client = OpenSearch(
    hosts=[{"host": host, "port": port}],
    http_auth=auth,
    use_ssl=False,
    verify_certs=False,
    ssl_show_warn=False,
)

3. 操作例

次のコードスニペットは、一般的なインデックスおよびドキュメント操作を実行する方法を示しています。

インデックスの作成

client.indices.create() メソッドを使用して新しいインデックスを作成します。

index_name = 'python-test-index'
index_body = {
  'settings': {
    'index': {
      'number_of_shards': 4
    }
  }
}

response = client.indices.create(index=index_name, body=index_body)

ドキュメントへの書き込み

client.index() メソッドを使用して、指定したインデックスにドキュメントを追加します。

document = {
  'title': 'Moneyball',
  'director': 'Bennett Miller',
  'year': '2011'
}

response = client.index(
    index = 'python-test-index',
    body = document,
    id = '1',
    refresh = True
)

バッチ操作の実行

client.bulk() メソッドを使用して、一度に複数の操作を実行します。操作は \n で区切ります。

movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }'

client.bulk(body=movies)

ドキュメントの検索

client.search() メソッドを使用して、クエリ基準に基づいてドキュメントを検索します。

q = 'miller'
query = {
  'size': 5,
  'query': {
    'multi_match': {
      'query': q,
      'fields': ['title^2', 'director']
    }
  }
}

response = client.search(
    body = query,
    index = 'python-test-index'
)

ドキュメントの削除

client.delete() メソッドを使用して、特定の ID を持つドキュメントを削除します。

response = client.delete(
    index = 'python-test-index',
    id = '1'
)

インデックスの削除

client.indices.delete() メソッドを使用して、インデックス全体を削除します。

response = client.indices.delete(
    index = 'python-test-index'
)

完全なコード例

次の完全な例は、インデックスの作成から削除までの全プロセスを示しています。

Java クライアント

コード例

依存関係の構成 (pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>OpenSearchJavaClientSample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.opensearch.client</groupId>
            <artifactId>opensearch-rest-client</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>org.opensearch.client</groupId>
            <artifactId>opensearch-java</artifactId>
            <version>2.19.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents.client5</groupId>
            <artifactId>httpclient5</artifactId>
            <version>5.2.1</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.15.2</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents.core5</groupId>
            <artifactId>httpcore5</artifactId>
            <version>5.2</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.30</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.21.0</version>
        </dependency>
    </dependencies>
</project>

サンプルプログラム (OpenSearchClientExample.java)

package samples;

import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;

import org.apache.hc.client5.http.auth.AuthScope;
import org.apache.hc.client5.http.auth.UsernamePasswordCredentials;
import org.apache.hc.client5.http.impl.auth.BasicCredentialsProvider;
import org.apache.hc.client5.http.impl.nio.PoolingAsyncClientConnectionManagerBuilder;
import org.apache.hc.client5.http.ssl.ClientTlsStrategyBuilder;
import org.apache.hc.client5.http.ssl.NoopHostnameVerifier;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.ssl.SSLContextBuilder;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.opensearch.client.RestClient;
import org.opensearch.client.json.jackson.JacksonJsonpMapper;
import org.opensearch.client.opensearch.OpenSearchClient;
import org.opensearch.client.opensearch.core.IndexRequest;
import org.opensearch.client.opensearch.core.SearchResponse;
import org.opensearch.client.opensearch.indices.CreateIndexRequest;
import org.opensearch.client.opensearch.indices.DeleteIndexRequest;
import org.opensearch.client.opensearch.indices.DeleteIndexResponse;
import org.opensearch.client.transport.httpclient5.ApacheHttpClient5TransportBuilder;
import org.opensearch.client.transport.rest_client.RestClientTransport;


public class OpenSearchClientExample {
    static class IndexData {
        private String title;
        private String text;
    
        public IndexData() {}
    
        public IndexData(String title, String text) {
            this.title = title;
            this.text = text;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    
        public String getText() {
            return text;
        }
    
        public void setText(String text) {
            this.text = text;
        }
    
        @Override
        public String toString() {
            return String.format("IndexData{title='%s', text='%s'}", title, text);
        }
    }
    
    private static final Logger LOGGER = LogManager.getLogger(OpenSearchClientExample.class);

    public static OpenSearchClient createClient() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException {
        var env = System.getenv();
        var hostname = env.getOrDefault("HOST", "localhost");
        var port = Integer.parseInt(env.getOrDefault("PORT", "3001"));
        var user = env.getOrDefault("USERNAME", "admin");
        var pass = env.getOrDefault("PASSWORD", "admin");

        final var hosts = new HttpHost[] { new HttpHost("http", hostname, port) };

        final var sslContext = SSLContextBuilder.create().loadTrustMaterial(null, (chains, authType) -> true).build();

        final var transport = ApacheHttpClient5TransportBuilder.builder(hosts)
                .setMapper(new JacksonJsonpMapper())
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    final var credentialsProvider = new BasicCredentialsProvider();
                    for (final var host : hosts) {
                        credentialsProvider.setCredentials(new AuthScope(host), new UsernamePasswordCredentials(user, pass.toCharArray()));
                    }

                    // ローカルのテストクラスターは自己署名証明書を使用するため、SSL/TLS 検証を無効にします
                    final var tlsStrategy = ClientTlsStrategyBuilder.create()
                            .setSslContext(sslContext)
                            .setHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                            .build();

                    final var connectionManager = PoolingAsyncClientConnectionManagerBuilder.create().setTlsStrategy(tlsStrategy).build();

                    return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider).setConnectionManager(connectionManager);
                })
                .build();
        return new OpenSearchClient(transport);
    }

    public static OpenSearchClient createRestClient()  {
        var env = System.getenv();
        var hostname = env.getOrDefault("HOST", "localhost");
        var port = Integer.parseInt(env.getOrDefault("PORT", "3001"));
        var user = env.getOrDefault("USERNAME", "admin");
        var pass = env.getOrDefault("PASSWORD", "admin");
        final org.apache.http.HttpHost[] restHosts = new org.apache.http.HttpHost[] {new org.apache.http.HttpHost(hostname, port, "http")};


        RestClient restClient = RestClient.builder(restHosts)
                .setHttpClientConfigCallback(httpClientBuilder -> {
                    final org.apache.http.impl.client.BasicCredentialsProvider credentialsProvider = new org.apache.http.impl.client.BasicCredentialsProvider();
                    for (final org.apache.http.HttpHost ignored : restHosts) {
                        credentialsProvider.setCredentials(org.apache.http.auth.AuthScope.ANY, new org.apache.http.auth.UsernamePasswordCredentials(user, pass));
                    }

                    try {
                        return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider)
                                // テストクラスターはデフォルトのセキュリティ構成を使用しているだけなので、証明書を無効にします
                                .setSSLHostnameVerifier(NoopHostnameVerifier.INSTANCE)
                                .setSSLContext(SSLContextBuilder.create().loadTrustMaterial(null, (chains, authType) -> true).build());
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }).build();

        final RestClientTransport transport = new RestClientTransport(restClient, new JacksonJsonpMapper());
        return new OpenSearchClient(transport);
    }

    public static void main(String[] args) {
        try {
            LOGGER.info("start test...");

            var client = createClient();
            LOGGER.info("client create");
            final var index = "my-index";
            // 1. インデックスの作成
            LOGGER.info("1. Creating an index {} start", index);
            if (!client.indices().exists(r -> r.index(index)).value()) {
                CreateIndexRequest createIndexRequest = new CreateIndexRequest.Builder().index(index)
                        .build();
                client.indices().create(createIndexRequest);
            }
            LOGGER.info("1. Creating an index {} finished", index);
    
            // 2. データのインデックス作成
            LOGGER.info("2. Indexing data start");
            IndexData indexData = new IndexData("first_name", "Bruce");
            IndexRequest<IndexData> indexRequest = new IndexRequest.Builder<IndexData>().index(index).id("1").document(indexData).build();
            client.index(indexRequest);
            LOGGER.info("2. Indexing data finished");
    
            Thread.sleep(1500);
    
            // 3. ドキュメントの検索
            LOGGER.info("3. Searching for documents start");
            SearchResponse<IndexData> searchResponse = client.search(s -> s.index(index), IndexData.class);
            for (int i = 0; i< searchResponse.hits().hits().size(); i++) {
                LOGGER.info(searchResponse.hits().hits().get(i).source());
            }        
            LOGGER.info("3. Searching for documents finished");
            
            // 4. ドキュメントの削除
            LOGGER.info("4. Deleting a document start");
            client.delete(b -> b.index(index).id("1"));
            LOGGER.info("4. Deleting a document finished");
    
            // 5. インデックスの削除
            LOGGER.info("5. Deleting an index {} start", index);
            DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest.Builder().index(index).build();
            DeleteIndexResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest);
            LOGGER.info("5. Deleting an index {} finished", index);

            LOGGER.info("end test...");
        } catch (Exception e) {
            LOGGER.error(e.toString());
        }
    }
}

実行方法

mvn clean package
mvn exec:java -Dexec.mainClass=samples.OpenSearchClientExample

Java 高レベル REST クライアント

コード例

依存関係の構成 (pom.xml)

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>RESTClientSample</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>
    <dependencies>
        <!-- OpenSearch Java 高レベル REST クライアントコアライブラリ -->
        <dependency>
          <groupId>org.opensearch.client</groupId>
          <artifactId>opensearch-rest-high-level-client</artifactId>
          <version>2.19.0</version>
        </dependency>
    </dependencies>
</project>

サンプルプログラム (RESTClientSample.java)

package com.example;
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.opensearch.action.admin.indices.delete.DeleteIndexRequest;
import org.opensearch.action.delete.DeleteRequest;
import org.opensearch.action.delete.DeleteResponse;
import org.opensearch.action.get.GetRequest;
import org.opensearch.action.get.GetResponse;
import org.opensearch.action.index.IndexRequest;
import org.opensearch.action.index.IndexResponse;
import org.opensearch.action.support.master.AcknowledgedResponse;
import org.opensearch.client.RequestOptions;
import org.opensearch.client.RestClient;
import org.opensearch.client.RestClientBuilder;
import org.opensearch.client.RestHighLevelClient;
import org.opensearch.client.indices.CreateIndexRequest;
import org.opensearch.client.indices.CreateIndexResponse;
import org.opensearch.common.settings.Settings;

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

public class RESTClientSample {

  public static void main(String[] args) throws IOException {

    // 自己署名証明書を使用する場合は、証明書を含むキーストアをポイントします。
    // System.setProperty("javax.net.ssl.trustStore", "/full/path/to/keystore.jks");
    // System.setProperty("javax.net.ssl.trustStorePassword", "password-to-keystore");

    // 基本認証の認証情報を確立します。
    // デモンストレーション目的のみ。本番コードに認証情報をハードコーディングしないでください。
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY,
      new UsernamePasswordCredentials("<polarsearch_username>", "<polarsearch_password>"));

    // クライアントを作成
    RestClientBuilder builder = RestClient.builder(new HttpHost("<polarsearch_host>", <polarsearch_port>, "https"))
      .setHttpClientConfigCallback(new RestClientBuilder.HttpClientConfigCallback() {
        @Override
        public HttpAsyncClientBuilder customizeHttpClient(HttpAsyncClientBuilder httpClientBuilder) {
          return httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
        }
      });
    RestHighLevelClient client = new RestHighLevelClient(builder);

    // 1. カスタム設定とマッピングでインデックスを作成
    CreateIndexRequest createIndexRequest = new CreateIndexRequest("custom-index");
    createIndexRequest.settings(Settings.builder()
      .put("index.number_of_shards", 4)
      .put("index.number_of_replicas", 3)
    );
    HashMap<String, String> typeMapping = new HashMap<>();
    typeMapping.put("type", "integer");
    HashMap<String, Object> ageMapping = new HashMap<>();
    ageMapping.put("age", typeMapping);
    HashMap<String, Object> mapping = new HashMap<>();
    mapping.put("properties", ageMapping);
    createIndexRequest.mapping(mapping);
    CreateIndexResponse createIndexResponse = client.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    System.out.println("Index creation acknowledged: " + createIndexResponse.isAcknowledged());

    // 2. インデックスにデータを追加
    IndexRequest request = new IndexRequest("custom-index");
    request.id("1");
    HashMap<String, String> stringMapping = new HashMap<>();
    stringMapping.put("message", "Testing Java REST client");
    request.source(stringMapping);
    IndexResponse indexResponse = client.index(request, RequestOptions.DEFAULT);
    System.out.println("Document indexed with result: " + indexResponse.getResult());
    
    // 3. ドキュメントを取得
    GetRequest getRequest = new GetRequest("custom-index", "1");
    GetResponse getResponse = client.get(getRequest, RequestOptions.DEFAULT);
    System.out.println("Retrieved document: " + getResponse.getSourceAsString());

    // 4. ドキュメントを削除
    DeleteRequest deleteDocumentRequest = new DeleteRequest("custom-index", "1");
    DeleteResponse deleteResponse = client.delete(deleteDocumentRequest, RequestOptions.DEFAULT);
    System.out.println("Document deleted with result: " + deleteResponse.getResult());

    // 5. インデックスを削除
    DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("custom-index");
    AcknowledgedResponse deleteIndexResponse = client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
    System.out.println("Index deletion acknowledged: " + deleteIndexResponse.isAcknowledged());

    client.close();
  }
}

低レベル Python クライアント

依存関係の構成

pip3 install opensearch-py

サンプルプログラム

import os
from opensearchpy import OpenSearch

host = os.getenv("HOST", default="<polarsearch_host>")
port = int(os.getenv("PORT", <polarsearch_port>))
auth = (os.getenv("USERNAME", "<polarsearch_username>"), os.getenv("PASSWORD", "<polarsearch_password>"))


client = OpenSearch(
    hosts=[{"host": host, "port": port}],
    http_auth=auth,
    use_ssl=False,
    verify_certs=False,
    ssl_show_warn=False,
)

# デフォルト以外の設定でインデックスを作成します。
index_name = 'python-test-index'
index_body = {
  'settings': {
    'index': {
      'number_of_shards': 4
    }
  }
}

response = client.indices.create(index=index_name, body=index_body)
print('\nCreating index:')
print(response)

# インデックスにドキュメントを追加します。
document = {
  'title': 'Moneyball',
  'director': 'Bennett Miller',
  'year': '2011'
}
id = '1'

response = client.index(
    index = index_name,
    body = document,
    id = id,
    refresh = True
)

print('\nAdding document:')
print(response)

# 一括操作を実行

movies = '{ "index" : { "_index" : "my-dsl-index", "_id" : "2" } } \n { "title" : "Interstellar", "director" : "Christopher Nolan", "year" : "2014"} \n { "create" : { "_index" : "my-dsl-index", "_id" : "3" } } \n { "title" : "Star Trek Beyond", "director" : "Justin Lin", "year" : "2015"} \n { "update" : {"_id" : "3", "_index" : "my-dsl-index" } } \n { "doc" : {"year" : "2016"} }'

client.bulk(body=movies)

# ドキュメントを検索します。
q = 'miller'
query = {
  'size': 5,
  'query': {
    'multi_match': {
      'query': q,
      'fields': ['title^2', 'director']
    }
  }
}

response = client.search(
    body = query,
    index = index_name
)
print('\nSearch results:')
print(response)

# ドキュメントを削除します。
response = client.delete(
    index = index_name,
    id = id
)

print('\nDeleting document:')
print(response)

# インデックスを削除します。
response = client.indices.delete(
    index = index_name
)

print('\nDeleting index:')
print(response)

参考資料