Utilisez le SDK OpenSearch pour Java V3.1 pour ajouter, mettre à jour et supprimer des documents en mode commit. Dans ce mode, mettez en tampon un ou plusieurs documents dans une file d'attente côté client, puis soumettez l'ensemble du lot via un seul appel à la méthode commit.
Cas d'utilisation
Fusionner et valider dynamiquement les données provenant de plusieurs sources
Valider un seul document en temps réel
Valider un petit lot de documents à la fois
Le mode commit ne prend en charge que les champs appartenant à la même table. Il est impossible de valider des champs issus de tables différentes lors d'un même appel.
Prérequis
Avant de commencer, assurez-vous de disposer des éléments suivants :
Une application OpenSearch avec une table configurée
Le nom de l'application (
appName), le nom de la table (tableName) et le point de terminaison API OpenSearch (host) correspondant à votre régionUn ID AccessKey et un secret AccessKey associés à un utilisateur RAM disposant des autorisations OpenSearch requises. Pour la configuration, consultez les rubriques Créer un utilisateur RAM et Règles d'autorisation d'accès
La paire de clés AccessKey de votre compte Alibaba Cloud offre un accès à toutes les opérations d'API. Utilisez plutôt la paire de clés AccessKey d'un utilisateur RAM et attribuez-lui le rôle AliyunServiceRoleForOpenSearch. Ne stockez jamais les identifiants directement dans le code source.
Configurer les variables d'environnement
Définissez vos identifiants sous forme de variables d'environnement afin que l'exemple de code puisse les lire au moment de l'exécution.
Linux et macOS
Remplacez <access_key_id> et <access_key_secret> par l'ID AccessKey et le secret AccessKey de l'utilisateur RAM, puis exécutez les commandes suivantes :
export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Windows
Créez un fichier de variables d'environnement et ajoutez-y les variables
ALIBABA_CLOUD_ACCESS_KEY_IDetALIBABA_CLOUD_ACCESS_KEY_SECRETavec les valeurs correspondantes.Redémarrez Windows pour appliquer les modifications.
Fonctionnement
Chaque opération suit le même schéma en trois étapes :
Encapsulez les données du document dans un objet
Map.Appelez les méthodes
add(),update()ouremove()pour placer le document en attente dans le tampon client.Appelez la méthode
commit(appName, tableName)pour soumettre tous les documents mis en tampon à OpenSearch.
Après une validation réussie, vérifiez les journaux d'erreurs de la console OpenSearch pour confirmer que les données ont été indexées sans erreurs au niveau des champs (telles que des échecs de conversion de type).
Ajouter un document
Créez un objet Map contenant les champs du document, placez-le en attente avec la méthode add(), puis soumettez-le via la méthode commit().
package com.aliyun.opensearch;
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Maps;
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 java.io.UnsupportedEncodingException;
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";
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";
public static void main(String[] args) {
// Read credentials from environment variables
String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Print the file encoding and default charset for debugging
System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", java.nio.charset.Charset.defaultCharset().name()));
// Use a random integer as the document's primary key
Random rand = new Random();
int value = rand.nextInt(Integer.MAX_VALUE);
// Build the document as a Map object
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);
// Initialize the SDK client chain: OpenSearch -> OpenSearchClient -> DocumentClient
OpenSearch openSearch1 = new OpenSearch(accesskey, secret, host);
OpenSearchClient serviceClient1 = new OpenSearchClient(openSearch1);
DocumentClient documentClient1 = new DocumentClient(serviceClient1);
// Stage the document in the client buffer
documentClient1.add(doc1);
System.out.println(doc1.toString());
try {
// Submit all buffered documents. You can buffer multiple documents before calling commit.
OpenSearchResult osr = documentClient1.commit(appName, tableName);
checkCommitResult(osr);
} catch (OpenSearchException | OpenSearchClientException e) {
e.printStackTrace();
}
// Wait 10 seconds before querying -- OpenSearch indexes data asynchronously
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// Check whether the commit was accepted without transport-level errors.
// A "true" result means the request was received successfully.
// Field-level errors (such as type conversion failures) are reported separately
// in the OpenSearch console error logs.
private static void checkCommitResult(OpenSearchResult osr) {
if (osr.getResult().equalsIgnoreCase("true")) {
System.out.println("No error occurred when the data is committed! \n The request ID is " + osr.getTraceInfo().getRequestId());
} else {
System.out.println("An error occurred when the data is committed!" + osr.getTraceInfo());
}
}
}
Mettre à jour un document
Pour mettre à jour un document, construisez un nouvel objet Map contenant la même clé primaire et les nouvelles valeurs de champ, puis appelez la méthode update() suivie de la méthode commit().
// Build the updated document -- must include the same primary key as the original
Map<String, Object> doc2 = Maps.newLinkedHashMap();
doc2.put("id", value); // same primary key as doc1
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);
// Stage the update in the client buffer
documentClient1.update(doc2);
System.out.println(doc2.toString());
try {
OpenSearchResult osr = documentClient1.commit(appName, tableName);
checkCommitResult(osr);
} catch (OpenSearchException | OpenSearchClientException e) {
e.printStackTrace();
}
// Wait 10 seconds before querying
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Supprimer un document
Pour supprimer un document, créez un objet Map ne contenant que la clé primaire, puis appelez la méthode remove() suivie de la méthode commit().
// Only the primary key is required to identify the document for deletion
Map<String, Object> doc3 = Maps.newLinkedHashMap();
doc3.put("id", value);
// Stage the deletion in the client buffer
documentClient1.remove(doc3);
System.out.println(doc3.toString());
try {
OpenSearchResult osr = documentClient1.commit(appName, tableName);
checkCommitResult(osr);
} catch (OpenSearchException | OpenSearchClientException e) {
e.printStackTrace();
}
// Wait at least 1 second (10 seconds recommended) before querying.
// Querying immediately after deletion may still return the deleted document.
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Vérifier le résultat
Après chaque validation, interrogez OpenSearch pour confirmer la présence ou l'absence des données attendues.
import com.aliyun.opensearch.sdk.dependencies.com.google.common.collect.Lists;
import com.aliyun.opensearch.sdk.dependencies.org.json.JSONObject;
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;
// Initialize a separate client for search
OpenSearch openSearch2 = new OpenSearch(accesskey, secret, host);
OpenSearchClient serviceClient2 = new OpenSearchClient(openSearch2);
SearcherClient searcherClient2 = new SearcherClient(serviceClient2);
// Configure paging and response format
// Supported formats: XML, JSON. FULLJSON is not supported.
Config config = new Config(Lists.newArrayList(appName));
config.setStart(0);
config.setHits(30);
config.setSearchFormat(SearchFormat.JSON);
// Query by primary key
SearchParams searchParams = new SearchParams(config);
searchParams.setQuery("id:'" + value + "'");
try {
SearchResult searchResult = searcherClient2.execute(searchParams);
String result = searchResult.getResult();
JSONObject obj = new JSONObject(result);
System.out.println("Query result: " + obj.toString());
} catch (OpenSearchException | OpenSearchClientException e) {
e.printStackTrace();
}
Étapes suivantes
AliyunServiceRoleForOpenSearch — consultez les autorisations requises pour le rôle lié au service
Règles d'autorisation d'accès — configurez un accès granulaire pour les utilisateurs RAM
Créer une paire de clés AccessKey — générez les identifiants pour votre utilisateur RAM