Tous les produits
Search
Centre de documentation

OpenSearch:Exemple de code pour l'envoi de documents

Dernière mise à jour :Aug 10, 2026

Cette rubrique fournit un exemple de code Go pour envoyer des documents vers une application OpenSearch.

Configurer les variables d'environnement

Configurez les variables d'environnement ALIBABA_CLOUD_ACCESS_KEY_ID et ALIBABA_CLOUD_ACCESS_KEY_SECRET.

Important
  • La paire AccessKey d'un compte Alibaba Cloud permet d'accéder à toutes les opérations API. Nous vous recommandons d'utiliser un utilisateur Resource Access Management (RAM) pour appeler les opérations API ou gérer les tâches courantes d'exploitation et de maintenance. Pour savoir comment utiliser un utilisateur RAM, consultez la rubrique Créer un utilisateur RAM.

  • Pour savoir comment créer une paire AccessKey, consultez la rubrique Créer une paire AccessKey.

  • Si vous utilisez la paire AccessKey d'un utilisateur RAM, assurez-vous que le rôle AliyunServiceRoleForOpenSearch dispose des autorisations requises via votre compte Alibaba Cloud. Pour plus d'informations, consultez les rubriques AliyunServiceRoleForOpenSearch et Règles d'autorisation d'accès.

  • Nous vous déconseillons d'inclure votre paire AccessKey dans des supports facilement accessibles à des tiers, tels que le code du projet. Dans le cas contraire, votre paire AccessKey risque d'être divulguée, ce qui compromettrait la sécurité des ressources de votre compte.

  • Linux et macOS

    Exécutez les commandes suivantes. Remplacez <access_key_id> et <access_key_secret> par l'AccessKey ID et l'AccessKey Secret de l'utilisateur RAM utilisé.

    export ALIBABA_CLOUD_ACCESS_KEY_ID=<access_key_id> 
    export ALIBABA_CLOUD_ACCESS_KEY_SECRET=<access_key_secret>
  • Windows

    1. Créez un fichier de variables d'environnement, ajoutez-y les variables d'environnement ALIBABA_CLOUD_ACCESS_KEY_ID et ALIBABA_CLOUD_ACCESS_KEY_SECRET, puis définissez-les avec votre AccessKey ID et votre AccessKey Secret.

    2. Redémarrez Windows pour que la paire AccessKey prenne effet.

Exemple de code

// 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)
}
Remarque

Pour plus d'informations, consultez la rubrique Traitement des données.