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 obtener 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 los recursos de su cuenta quedarían expuestos.
-
Linux y macOS
Ejecute los siguientes comandos. Reemplace
<access_key_id>y<access_key_secret>con el ID de AccessKey y el secreto de AccessKey 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 de entorno ALIBABA_CLOUD_ACCESS_KEY_ID y ALIBABA_CLOUD_ACCESS_KEY_SECRET al archivo y, a continuación, establezca las variables de entorno con su ID de AccessKey y su secreto de AccessKey.
Reinicie Windows para que el par de AccessKey surta efecto.
Código de demostración para implementar la función de análisis de consultas mediante OpenSearch SDK for Java V3.1.3
package com.aliyun.opensearch;
import com.alibaba.fastjson.JSONArray;
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.OpenSearch;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchClientException;
import com.aliyun.opensearch.sdk.generated.commons.OpenSearchException;
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 com.aliyun.opensearch.search.SearchParamsBuilder;
import com.aliyun.opensearch.search.SearchResultDebug;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class testQueryProcessor {
private static String appName = "Name of the OpenSearch application that you want to manage";
private static String host = "Endpoint of the OpenSearch API in your region";
public static void main(String[] args) {
// Specify your AccessKey pair.
// Obtain the AccessKey ID and AccessKey secret from the environment variables. You must configure the environment variables before you run the sample code.
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()));
// Create an OpenSearch object.
OpenSearch openSearch = new OpenSearch(accesskey, secret, host);
// Use the OpenSearch object as a parameter to create an OpenSearchClient object.
OpenSearchClient serviceClient = new OpenSearchClient(openSearch);
// Use the OpenSearchClient object as a parameter to create a SearcherClient object.
SearcherClient searcherClient = new SearcherClient(serviceClient);
// Create a Config object and use the config clause to configure parameters such as the application name, paging-related parameters, and data format of returned results.
Config config = new Config(Lists.newArrayList(appName));
config.setStart(0);
config.setHits(5);
// Specify the data format of return results. OpenSearch SDK for Java V3.1.2 supports XML and JSON but not FULLJSON. The FULLJSON format is supported by OpenSearch SDK for Java V3.1.3.
config.setSearchFormat(SearchFormat.FULLJSON);
// Create a SearchParams object.
SearchParams searchParams = new SearchParams(config);
// Specify the query clause. You can specify multiple keywords to perform a query based on multiple index fields. In this case, you must specify the index fields in one setQuery call. If you specify each index field in a separate setQuery call, the last clause overwrites the preceding clauses.
searchParams.setQuery("name:'kfc'");// If the query keyword is kfc, the return results are the documents that are related to KFC.
List<String> qpname = new ArrayList<String>();
qpname.add("qptest"); // Set a name for the query analyzer.
searchParams.setQueryProcessorNames(qpname);
// Create a SearchParamsBuilder object. As the utility class of SearchParams, the SearchParamsBuilder class allows you to configure query-related parameters with ease.
SearchParamsBuilder paramsBuilder = SearchParamsBuilder.create(searchParams);
// Run the query and return the results.
SearchResult searchResult;
try {
searchResult = searcherClient.execute(paramsBuilder);
String result = searchResult.getResult();
JSONObject obj = new JSONObject(result);
// Determine whether an error has occurred. If no error has occurred, the search results are returned. If an error has occurred, the following code is run:
if(obj.get("errors").toString().length()>2){
JSONArray jsonarr = JSONArray.parseArray(obj.get("errors").toString());
System.out.println("error code:"+jsonarr.getJSONObject(0).get("code"));
System.out.println("error message:"+jsonarr.getJSONObject(0).get("message"));
}else{
// Display the search results.
System.out.println("output:"+obj.toString());
// You may need the information about request addresses for debugging.
SearchResultDebug srd = searcherClient.executeDebug(searchParams);
System.out.println(srd.getRequestUrl().toString());
}
} catch (OpenSearchException e) {
e.printStackTrace();
} catch (OpenSearchClientException e) {
e.printStackTrace();
}
}
}