Use el SDK de OpenSearch para Java V3.1 para agregar, actualizar y eliminar documentos en modo commit. En este modo, se almacenan temporalmente uno o más documentos en una cola del lado del cliente y luego se envía todo el lote con una sola llamada a commit.
Casos de uso
Fusionar y enviar datos de varias fuentes de forma dinámica
Enviar un solo documento en tiempo real
Enviar lotes pequeños de documentos de manera secuencial
El modo commit solo admite campos dentro de la misma tabla. No es posible enviar campos de tablas diferentes en una sola llamada.
Requisitos previos
Antes de empezar, asegúrese de contar con lo siguiente:
Una aplicación de OpenSearch con una tabla configurada
El nombre de la aplicación (
appName), el nombre de la tabla (tableName) y el endpoint de la API de OpenSearch (host) correspondiente a su regiónUn AccessKey ID y un AccessKey secret de un usuario de Resource Access Management (RAM) con los permisos necesarios para OpenSearch. Para consultar los pasos de configuración, consulte Crear un usuario RAM y Reglas de autorización de acceso
El par de AccessKey de su cuenta de Alibaba Cloud tiene acceso a todas las operaciones de la API. Se recomienda usar el par de AccessKey de un usuario RAM y asignarle el rol AliyunServiceRoleForOpenSearch. Nunca almacene credenciales directamente en el código fuente.
Configurar variables de entorno
Establezca sus credenciales como variables de entorno para que el código de ejemplo pueda leerlas durante la ejecución.
Linux y macOS
Reemplace <access_key_id> y <access_key_secret> con el AccessKey ID y el AccessKey secret del usuario RAM, y ejecute el siguiente comando:
export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id>
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
Windows
Cree un archivo de variables de entorno y agregue
ALIBABA_CLOUD_ACCESS_KEY_IDyALIBABA_CLOUD_ACCESS_KEY_SECRETcon los valores correspondientes.Reinicie Windows para que los cambios surtan efecto.
Funcionamiento
Cada operación sigue el mismo patrón de tres pasos:
Encapsular los datos del documento en un objeto
Map.Llamar a
add(),update()oremove()para preparar el documento en el búfer del cliente.Llamar a
commit(appName, tableName)para enviar todos los documentos almacenados en el búfer a OpenSearch.
Después de un commit exitoso, revise los registros de errores en la consola de OpenSearch para confirmar que los datos se indexaron correctamente y sin errores de campo (como fallos en la conversión de tipos).
Agregar un documento
Cree un objeto Map con los campos del documento, prepárelo mediante add() y envíelo con 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());
}
}
}
Actualizar un documento
Para actualizar un documento, construya un nuevo objeto Map con la misma clave primaria y los valores de campo actualizados; después, llame a update() seguido de 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();
}
Eliminar un documento
Para eliminar un documento, construya un objeto Map que contenga únicamente la clave primaria y llame a remove() seguido de 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();
}
Comprobar el resultado
Después de cada commit, consulte OpenSearch para confirmar que los datos esperados están presentes o ausentes según corresponda.
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();
}
Pasos siguientes
AliyunServiceRoleForOpenSearch -- revise los permisos necesarios para el rol vinculado al servicio
Reglas de autorización de acceso -- configure el acceso detallado para usuarios RAM
Crear un par de AccessKey -- genere credenciales para su usuario RAM