Configurar variables de entorno
Configure las variables de entorno ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET.
El par de AccessKey de una cuenta de Alibaba Cloud permite acceder a todas las operaciones de la API. Se recomienda utilizar un usuario de Resource Access Management (RAM) para invocar operaciones de la API o realizar tareas rutinarias de operación y mantenimiento. Para obtener información sobre cómo usar un usuario de RAM, consulte Create a RAM user.
Para obtener información sobre cómo crear un par de AccessKey, consulte Create an AccessKey pair.
Si utiliza el par de AccessKey de un usuario de RAM, asegúrese de que se hayan otorgado los permisos obligatorios al rol AliyunServiceRoleForOpenSearch mediante su cuenta de Alibaba Cloud. Para más información, consulte AliyunServiceRoleForOpenSearch y Access authorization rules.
Se recomienda no incluir su par de AccessKey en materiales fácilmente accesibles para otros, como el código del proyecto. De lo contrario, su par de AccessKey podría filtrarse y comprometer la seguridad de los recursos de su cuenta.
-
Linux y macOS
Ejecute los siguientes comandos. Reemplace
<access_key_id>y<access_key_secret>con el AccessKey ID y el AccessKey secret del usuario de RAM que esté utilizando.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, agregue las variables ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET al archivo y, a continuación, establezca las variables de entorno con su AccessKey ID y su AccessKey secret.
Reinicie Windows para que el par de AccessKey surta efecto.
Código de ejemplo para sugerencias desplegables
Antes de ejecutar el código de ejemplo, reemplace los siguientes parámetros con sus valores reales:
host: El endpoint público de la API de su instancia. Para obtener el endpoint, vaya a la página de lista de instancias , haga clic en Details correspondiente a la instancia y busque el Public API Endpoint en la sección Endpoint.
suggestionName: El nombre de su modelo de sugerencias desplegables. Para obtener el nombre, vaya a Search Algorithm Center, elija Search Guidance y haga clic en drop-down suggestion.
appName: El nombre de su instancia. Puede encontrar el nombre en la página de lista de instancias .
query: La palabra clave de búsqueda.
Si utiliza el SDK v4.0.0 o posterior, debe pasar AppName al crear un objeto SuggestionClient. Este parámetro no es obligatorio para versiones del SDK anteriores a v4.0.0.
Para más información sobre esta operación de la API, consulte drop-down suggestion.
Puede descargar el SDK de Java desde download hub.
SDK v4.0.0 y posteriores
package com.example.opensearch;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SuggestionClient;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.charset.Charset;
public class SuggestDemo {
// Replace the placeholders with your actual values.
static private final String host = "";
static private final String appName = "";
static private final String suggestionName = "";
static private final byte hits = 8; // The maximum number of suggestions to return.
OpenSearch openSearch;
OpenSearchClient openSearchClient;
@Before
public void setUp() {
// Configure credentials.
// Read credentials from environment variables.
String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Initialize the OpenSearch client.
openSearch = new OpenSearch(accesskey, secret, host);
openSearchClient = new OpenSearchClient(openSearch);
}
@Test
public void TestEnv() {
// (Optional) Print the default file encoding.
System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));
// Create a client for drop-down suggestions.
SuggestionClient suggestionClient = new SuggestionClient(appName,suggestionName,openSearchClient);
String query = "";
try {
SuggestParams suggestParams = new SuggestParams();
suggestParams.setQuery(query); // Set the search query.
suggestParams.setHits(hits); // Set the maximum number of suggestions.
suggestParams.setUserId("12345678"); // Set the user ID for personalized results.
// By default, the completion feature for Chinese homophones is enabled.
// You can add the re_search parameter to adjust this behavior.
// ReSearch.findByValue(1) disables this feature. ReSearch.findByValue(0) or omitting the parameter enables it.
suggestParams.setReSearch(ReSearch.findByValue(1));
SearchResult result = suggestionClient.execute(suggestParams);
System.out.println(result); // Print the result.
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
}
@After
public void clean() {
openSearch.clear();
}
}
SDK anterior a v4.0.0
package com.example.opensearch;
import com.aliyun.opensearch.OpenSearchClient;
import com.aliyun.opensearch.SuggestionClient;
import com.aliyun.opensearch.sdk.generated.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.nio.charset.Charset;
public class SuggestDemo {
// Replace the placeholders with your actual values.
static private final String host = "";
static private final String suggestionName = "";
static private final byte hits = 8; // The maximum number of suggestions to return.
OpenSearch openSearch;
OpenSearchClient openSearchClient;
@Before
public void setUp() {
// Configure credentials.
// Read credentials from environment variables.
String accesskey = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
String secret = System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
// Initialize the OpenSearch client.
openSearch = new OpenSearch(accesskey, secret, host);
openSearchClient = new OpenSearchClient(openSearch);
}
@Test
public void TestEnv() {
// (Optional) Print the default file encoding.
System.out.println(String.format("file.encoding: %s", System.getProperty("file.encoding")));
System.out.println(String.format("defaultCharset: %s", Charset.defaultCharset().name()));
// Create a client for drop-down suggestions.
SuggestionClient suggestionClient = new SuggestionClient(suggestionName, openSearchClient);
String query = "";
try {
SuggestParams suggestParams = new SuggestParams();
suggestParams.setQuery(query); // Set the search query.
suggestParams.setHits(hits); // Set the maximum number of suggestions.
suggestParams.setUserId("12345678"); // Set the user ID for personalized results.
// By default, the completion feature for Chinese homophones is enabled.
// You can add the re_search parameter to adjust this behavior.
// ReSearch.findByValue(1) disables this feature. ReSearch.findByValue(0) or omitting the parameter enables it.
suggestParams.setReSearch(ReSearch.findByValue(1));
SearchResult result = suggestionClient.execute(suggestParams);
System.out.println(result); // Print the result.
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
}
@After
public void clean() {
openSearch.clear();
}
}