PolarSearch は、公式の OpenSearch クライアントと完全に互換性があります。これらのクライアントを使用して、Java や Python などの一般的なプログラミング言語を通じて PolarSearch と対話できます。これにより、インデックスを効率的に管理し、ドキュメント操作 (作成、削除、更新、クエリ) を実行し、複雑な検索を実行して、検索機能をアプリケーションにシームレスに統合できます。
準備
PolarSearch ノードを含むクラスターを作成し、ノードの管理者アカウントを設定します。
エンドポイントを取得します: クラスターの [データベースノード] セクションで、[検索ノード] にマウスをかざして、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 証明書を追加できます。
トラストストアを作成して証明書をインポートする:
Java のkeytoolユーティリティを使用して、ルート CA 証明書をtruststore.jksなどの新しいトラストストアファイルにインポートします。keytool -importcert -file <path/to/your/root-ca.pem> -alias <certificate_alias> -keystore <path/to/your/truststore.jks>このコマンドを実行すると、新しいトラストストアのパスワードを設定するように求められます。
アプリケーションでトラストストアを指定する:
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. 環境を構成する
プロジェクトディレクトリに移動します。この例では
/home/PolarSearchTestPythonを使用します。mkdir /home/PolarSearchTestPython cd /home/PolarSearchTestPython/home/PolarSearchTestPythonディレクトリで、仮想環境 (venv) を作成してプロジェクトの依存関係を分離し、グローバル環境との競合を回避します。python3 -m venv myenv仮想環境をアクティブ化します。
source myenv/bin/activate必要な 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 クライアント
コード例
実行方法
mvn clean package
mvn exec:java -Dexec.mainClass=samples.OpenSearchClientExampleJava 高レベル REST クライアント
コード例
低レベル 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)