環境変数の設定
ALIBABA_CLOUD_ACCESS_KEY_ID および ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数を設定します。
Alibaba Cloud アカウントの AccessKey ペアを使用して、すべての API 操作にアクセスできます。API 操作の呼び出しや日常的な O&M の実行には、Resource Access Management (RAM) ユーザーを使用することをお勧めします。RAM ユーザーの使用方法については、RAM ユーザーの作成 を参照してください。
AccessKey ペアの作成方法については、AccessKey ペアの作成 を参照してください。
RAM ユーザーの AccessKey ペアを使用する場合は、Alibaba Cloud アカウントを使用して、必要な権限が AliyunServiceRoleForOpenSearch ロールに付与されていることを確認してください。詳細については、AliyunServiceRoleForOpenSearch および アクセス認証ルール を参照してください。
プロジェクトコードなど、他人が簡単にアクセスできる資料に AccessKey ペアを含めないでください。含めると、AccessKey ペアが漏洩し、アカウント内のリソースが安全でなくなる可能性があります。
Linux および macOS
次のコマンドを実行します。
<access_key_id>および<access_key_secret>を、使用する RAM ユーザーの AccessKey ID と AccessKey シークレットに置き換えます。export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>Windows
環境変数ファイルを作成し、ALIBABA_CLOUD_ACCESS_KEY_ID および ALIBABA_CLOUD_ACCESS_KEY_SECRET 環境変数をファイルに追加してから、環境変数を AccessKey ID と AccessKey シークレットに設定します。
AccessKey ペアを有効にするには、Windows を再起動します。
OpenSearch SDK for Java V3.1 を使用したデータコミットのデモコード
コミットモードでデータをアップロードするには、まず、アップロードするドキュメントデータを Map オブジェクトに動的にカプセル化する必要があります。次に、add メソッドを呼び出して、Map オブジェクトをクライアントバッファにアップロードします。最後に、commit メソッドを呼び出して、Map オブジェクトを送信します。
シナリオ
データの動的なマージとコミット
単一ドキュメントのコミット
一度に少数のドキュメントをコミット
package com.aliyun.opensearch;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Maps;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchResult;
import com.aliyun.opensearch.sdk.generated.search.Config;
import com.aliyun.opensearch.sdk.generated.search.SearchFormat;
import com.aliyun.opensearch.sdk.generated.search.SearchParams;
import com.aliyun.opensearch.sdk.generated.search.general.SearchResult;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Random;
public class testCommitSearch {
private static String appName = "Name of the OpenSearch application for which you want to commit data"; // データをコミットするOpenSearchアプリケーションの名前
private static String tableName = "Name of the table to which data is to be uploaded"; // データをアップロードするテーブルの名前
private static String host = "Endpoint of the OpenSearch API in your region"; // リージョンのOpenSearch APIのエンドポイント
public static void main(String[] args) {
// Specify your AccessKey pair.
// Obtain the AccessKey ID and AccessKey secret from environment variables.
// You must configure the environment variables before you run the sample code. For more information, see the "Configure environment variables" section of this topic.
// AccessKeyペアを指定します。
// 環境変数からAccessKey IDとAccessKeyシークレットを取得します。
// サンプルコードを実行する前に、環境変数を設定する必要があります。詳細については、このトピックの「環境変数の設定」セクションを参照してください。
String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Obtain the file encoding format and default encoding format.
// ファイルのエンコード形式とデフォルトのエンコード形式を取得します。
System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));
// Generate a random value and use the value as the value of the primary key.
// ランダムな値を生成し、その値をプライマリキーの値として使用します。
Random rand = new Random();
int value = rand.nextInt(Integer.MAX_VALUE);
// Create a Map object named doc1 to store the data of the document to be uploaded.
// アップロードするドキュメントのデータを格納するために、doc1という名前のMapオブジェクトを作成します。
Map<String, Object> doc1 = Maps.newLinkedHashMap();
doc1.put("id", value);
String title_string = "Upload doc1 in commit mode";// UTF-8
byte[] bytes;
try {
bytes = title_string.getBytes("utf-8");
String utf8_string = new String(bytes, "utf-8");
doc1.put("name", utf8_string);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
doc1.put("phone", "1381111****");
int[] int_arr = {33,44};
doc1.put("int_arr", int_arr);
String[] literal_arr = {"Upload doc1 in commit mode","Test uploading doc1 in commit mode"};
doc1.put("literal_arr", literal_arr);
float[] float_arr = {(float)1.1,(float)1.2};
doc1.put("float_arr", float_arr);
doc1.put("cate_id", 1);
// Create an OpenSearch object.
// OpenSearchオブジェクトを作成します。
OpenSearch openSearch1 = new OpenSearch(accesskey, secret, host);
// Use the OpenSearch object as a parameter to create an OpenSearchClient object.
// OpenSearchオブジェクトをパラメーターとして使用して、OpenSearchClientオブジェクトを作成します。
OpenSearchClient serviceClient1 = new OpenSearchClient(openSearch1);
// Create a DocumentClient object that is used to upload and submit data.
// データのアップロードと送信に使用するDocumentClientオブジェクトを作成します。
DocumentClient documentClient1 = new DocumentClient(serviceClient1);
// Call the add method to upload the document to the client buffer.
// addメソッドを呼び出して、ドキュメントをクライアントバッファにアップロードします。
documentClient1.add(doc1);
// Display the document.
// ドキュメントを表示します。
System.out.println(doc1.toString());
try {
// Call the commit method to submit the added document. In this example, only one document is submitted at a time and you can view the result after 10 seconds. You can also upload multiple documents to the client buffer and then submit the documents at a time.
// commitメソッドを呼び出して、追加されたドキュメントを送信します。この例では、一度に1つのドキュメントのみが送信され、10秒後に結果を表示できます。複数のドキュメントをクライアントバッファにアップロードしてから、一度に送信することもできます。
OpenSearchResult osr = documentClient1.commit(appName, tableName);
// Whether the data is committed depends on whether an error occurs when you commit the data and whether an error occurs in the OpenSearch console.
// After you commit the data, errors may occur in the application. The OpenSearch console records these errors in error logs, such as failures of field content conversion.
// データがコミットされるかどうかは、データのコミット時にエラーが発生するかどうか、およびOpenSearchコンソールでエラーが発生するかどうかによって異なります。
// データをコミットした後、アプリケーションでエラーが発生する可能性があります。OpenSearchコンソールは、これらのエラーをエラーログに記録します(フィールドコンテンツの変換の失敗など)。
if(osr.getResult().equalsIgnoreCase("true")){
System.out.println("No error occurred when the data is committed! \n The request ID is "+osr.getTraceInfo().getRequestId()); // データのコミット時にエラーは発生しませんでした! \n リクエストIDは{リクエストID}です。
}else{
System.out.println("An error occurred when the data is committed!" + osr.getTraceInfo()); // データのコミット時にエラーが発生しました!
}
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
try {
Thread.sleep(10000); // Hibernate the thread for 10 seconds, after which you can view the new data in the OpenSearch console.
// スレッドを10秒間休止します。その後、OpenSearchコンソールで新しいデータを表示できます。
} catch (InterruptedException e) {
e.printStackTrace();
}
// Create a Map object named doc2 to update doc1. Call the add method to perform this update and make sure that you specify the valid name and primary key value of doc1.
// doc1を更新するために、doc2という名前のMapオブジェクトを作成します。addメソッドを呼び出してこの更新を実行し、doc1の有効な名前とプライマリキー値を指定していることを確認します。
Map<String, Object> doc2 = Maps.newLinkedHashMap();
doc2.put("id", value);
String title_string2 = "Update doc1 in commit mode";// UTF-8
byte[] bytes2;
try {
bytes2 = title_string2.getBytes("utf-8");
String utf8_string2 = new String(bytes2, "utf-8");
doc2.put("name", utf8_string2);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
doc2.put("phone", "1390000****");
int[] int_arr2 = {22,22};
doc2.put("int_arr", int_arr2);
String[] literal_arr2 = {"Update doc1 in commit mode","Update doc1 in commit mode"};
doc2.put("literal_arr", literal_arr2);
float[] float_arr2 = {(float)1.1,(float)1.2};
doc2.put("float_arr", float_arr2);
doc2.put("cate_id", 1);
// Call the add method to upload the Map object doc2 to the client buffer. This update operation can be executed normally, because the primary key is valid.
// addメソッドを呼び出して、Mapオブジェクトdoc2をクライアントバッファにアップロードします。プライマリキーが有効であるため、この更新操作は正常に実行できます。
documentClient1.update(doc2);
// Display the document.
// ドキュメントを表示します。
System.out.println(doc2.toString());
try {
// Call the commit method to submit the updated document. In this example, only one document is submitted at a time and you can view the result after 10 seconds. You can also update multiple documents in the client buffer and then submit the documents at a time.
// commitメソッドを呼び出して、更新されたドキュメントを送信します。この例では、一度に1つのドキュメントのみが送信され、10秒後に結果を表示できます。クライアントバッファ内の複数のドキュメントを更新してから、一度に送信することもできます。
OpenSearchResult osr = documentClient1.commit(appName, tableName);
// Whether the data is committed depends on whether an error occurs when you commit the data and whether an error occurs in the OpenSearch console.
// After you commit the data, errors may occur in the application. The OpenSearch console records these errors in error logs, such as failures of field content conversion.
// データがコミットされるかどうかは、データのコミット時にエラーが発生するかどうか、およびOpenSearchコンソールでエラーが発生するかどうかによって異なります。
// データをコミットした後、アプリケーションでエラーが発生する可能性があります。OpenSearchコンソールは、これらのエラーをエラーログに記録します(フィールドコンテンツの変換の失敗など)。
if(osr.getResult().equalsIgnoreCase("true")){
System.out.println("No error occurred when the data is committed! \n The request ID is "+osr.getTraceInfo().getRequestId()); // データのコミット時にエラーは発生しませんでした! \n リクエストIDは{リクエストID}です。
}else{
System.out.println("An error occurred when the data is committed!" + osr.getTraceInfo()); // データのコミット時にエラーが発生しました!
}
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
try {
Thread.sleep(10000);// Hibernate the thread for 10 seconds, after which you can view the updated data in the OpenSearch console.
// スレッドを10秒間休止します。その後、OpenSearchコンソールで更新されたデータを表示できます。
} catch (InterruptedException e) {
e.printStackTrace();
}
// Create a Map object named doc3 to delete the document. To delete a document, you need to only specify the primary key value of the document.
// ドキュメントを削除するために、doc3という名前のMapオブジェクトを作成します。ドキュメントを削除するには、ドキュメントのプライマリキー値のみを指定する必要があります。
Map<String, Object> doc3 = Maps.newLinkedHashMap();
doc3.put("id", value);
// Upload the Map object doc3 to the client buffer to delete the document.
// Mapオブジェクトdoc3をクライアントバッファにアップロードして、ドキュメントを削除します。
documentClient1.remove(doc3);
// Display the document.
// ドキュメントを表示します。
System.out.println(doc3.toString());
try {
// Call the commit method to submit the deleted document. In this example, only one document is submitted at a time and you can view the result after 10 seconds. You can also delete multiple documents from the client buffer and then submit the deleted documents at a time.
// commitメソッドを呼び出して、削除されたドキュメントを送信します。この例では、一度に1つのドキュメントのみが送信され、10秒後に結果を表示できます。クライアントバッファから複数のドキュメントを削除してから、一度に送信することもできます。
OpenSearchResult osr = documentClient1.commit(appName, tableName);
// Whether the data is committed depends on whether an error occurs when you commit the data and whether an error occurs in the OpenSearch console.
// After you commit the data, errors may occur in the application. The OpenSearch console records these errors in error logs, such as failures of field content conversion.
// データがコミットされるかどうかは、データのコミット時にエラーが発生するかどうか、およびOpenSearchコンソールでエラーが発生するかどうかによって異なります。
// データをコミットした後、アプリケーションでエラーが発生する可能性があります。OpenSearchコンソールは、これらのエラーをエラーログに記録します(フィールドコンテンツの変換の失敗など)。
if(osr.getResult().equalsIgnoreCase("true")){
System.out.println("No error occurred when the data is committed! \n The request ID is "+osr.getTraceInfo().getRequestId()); // データのコミット時にエラーは発生しませんでした! \n リクエストIDは{リクエストID}です。
}else{
System.out.println("An error occurred when the data is committed!" + osr.getTraceInfo()); // データのコミット時にエラーが発生しました!
}
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
try {
Thread.sleep(10000); // Hibernate the thread for 10 seconds, after which you can check whether the document is deleted. If you do not hibernate the thread and query data immediately after the deletion, the data to be deleted may be returned in the search results. Hibernate the thread for at least one second.
// スレッドを10秒間休止します。その後、ドキュメントが削除されたかどうかを確認できます。スレッドを休止せずに削除直後にデータをクエリすると、削除されるデータが検索結果に返される場合があります。スレッドを少なくとも1秒間休止します。
} catch (InterruptedException e) {
e.printStackTrace();
}
// Create an OpenSearch object.
// OpenSearchオブジェクトを作成します。
OpenSearch openSearch2 = new OpenSearch(accesskey, secret, host);
// Use the OpenSearch object as a parameter to create an OpenSearchClient object.
// OpenSearchオブジェクトをパラメーターとして使用して、OpenSearchClientオブジェクトを作成します。
OpenSearchClient serviceClient2 = new OpenSearchClient(openSearch2);
// Use the OpenSearchClient object as a parameter to create a SearcherClient object.
// OpenSearchClientオブジェクトをパラメーターとして使用して、SearcherClientオブジェクトを作成します。
SearcherClient searcherClient2 = new SearcherClient(serviceClient2);
// Create a Config object and use the config clause to configure parameters such as the paging-related parameters and data format of returned results.
// Configオブジェクトを作成し、config句を使用して、ページング関連のパラメーターや返される結果のデータ形式などのパラメーターを設定します。
Config config = new Config(Lists.newArrayList(appName));
config.setStart(0);
config.setHits(30);
// Specify the data format of returned results. Supported formats are XML and JSON. The FULLJSON format is not supported. In this example, the data format is set to JSON.
// 返される結果のデータ形式を指定します。サポートされている形式はXMLとJSONです。FULLJSON形式はサポートされていません。この例では、データ形式はJSONに設定されています。
config.setSearchFormat(SearchFormat.JSON);
SearchParams searchParams = new SearchParams(config);
searchParams.setQuery("id:'" + value + "'");
// Run the query and return the results.
// クエリを実行し、結果を返します。
SearchResult searchResult;
try {
searchResult = searcherClient2.execute(searchParams);
String result = searchResult.getResult();
JSONObject obj = new JSONObject(result);
// Display the search results.
// 検索結果を表示します。
System.out.println("Query debugging results:" + obj.toString()); // クエリデバッグ結果:
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
}
}データをコミットする場合、同じテーブルのフィールドのみをコミットでき、異なるテーブルのフィールドをコミットすることはできません。