Este tema proporciona código de ejemplo en Go para enviar documentos a una aplicación de OpenSearch.
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 utilice.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 ejemplo
// This file is auto-generated, don't edit it. Thanks.
package main
import (
"fmt"
util "github.com/alibabacloud-go/tea-utils/service"
"github.com/alibabacloud-go/tea/tea"
opensearch "main/client"
)
func main() {
// Create a client instance for sending requests.
// Endpoint: the endpoint of the OpenSearch API in your region.
// AccessKeyId and AccessKeySecret: the AccessKey pair used for authentication.
config := &opensearch.Config{
Endpoint: tea.String( "<Endpoint>"),
// Specify your AccessKey pair.
// Obtain the AccessKey ID and AccessKey secret from environment variables.
// You must configure environment variables before you run this code. For more information, see the "Configure environment variables" section of this topic.
// Specify the AccessKey ID.
AccessKeyId: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_ID")),
AccessKeySecret: tea.String(os.Getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")),
}
// Create a client for sending requests.
client, _clientErr := opensearch.NewClient(config)
// If an exception occurs when the system creates the client, _clientErr is not nil. In this case, display the error information.
if _clientErr != nil {
fmt.Println(_clientErr)
return
}
// Create documents to be pushed.
// Make sure that a document contains a primary key field. This field will be used as the primary key field of the table to which the document is pushed. If you do not specify a primary key field, you cannot update the document.
// To update a document, specify the fields to be updated and their values. Use UTF-8 to encode the document.
// OpenSearch allows you to create, update, or delete a document by using the ADD, UPDATE, or DELETE command.
document1st := map[string]interface{}{
"cmd": "ADD",
"fields": map[string]interface{}{
"id": 1, // The primary key field of the document.
"describe": "123456", // A regular field in the document.
},
}
// You can specify the timestamp field to customize the order of document updates. OpenSearch uses the values of this field to update documents with the same primary key field in the specified order.
// If this parameter is not specified, OpenSearch updates documents based on the order in which OpenSearch receives the documents.
document2nd := map[string]interface{}{
"cmd": "ADD",
"timestamp": 1401342874778,
"fields": map[string]interface{}{
"id": 2,
"describe": "123456",
},
}
// Add the documents to an array. Each document contains the operation to be performed on the document.
requestBody := []interface{}{document1st}
// You can call the append method to add more documents.
requestBody = append(requestBody, document2nd)
// Specify the parameters that are used to configure the request and connection pool.
runTime := &util.RuntimeOptions{
ConnectTimeout: tea.Int(5000),
ReadTimeout: tea.Int(10000),
Autoretry: tea.Bool(false),
IgnoreSSL: tea.Bool(false),
MaxIdleConns: tea.Int(50),
}
// To push documents, you must specify the appName and tableName parameters.
// appName: the name or version information of the application to which you want to push documents.
// tableName: the name of the table to which you want to push documents. You can view the tables of an application in the OpenSearch console.
appName := "<appName>"
tableName := "<tableName>"
// Call the method for sending a request.
response, _requestErr := client.Request(
tea.String("POST"),
tea.String("/v3/openapi/apps/"+appName+"/"+tableName+"/actions/bulk"),
nil,
nil,
requestBody,
runTime)
// If an exception occurs when the system sends the request, _requestErr is not nil. In this case, display the error information.
if _requestErr != nil {
fmt.Println(_requestErr)
return
}
// Display the response if no exception occurs.
fmt.Println(response)
}
Para obtener más información, consulte Process data.