All Products
Search
Document Center

OpenSearch:Demo code for pushing documents

Last Updated:Aug 07, 2023

Configure environment variables

Configure the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables.

Important
  • The AccessKey pair of an Alibaba Cloud account can be used to access all API operations. We recommend that you use a Resource Access Management (RAM) user to call API operations or perform routine O&M. For information about how to use a RAM user, see Create a RAM user.

  • For information about how to create an AccessKey pair, see Create an AccessKey pair.

  • If you use the AccessKey pair of a RAM user, make sure that the required permissions are granted to the AliyunServiceRoleForOpenSearch role by using your Alibaba Cloud account. For more information, see AliyunServiceRoleForOpenSearch and Access authorization rules.

  • We recommend that you do not include your AccessKey pair in materials that are easily accessible to others, such as the project code. Otherwise, your AccessKey pair may be leaked and resources in your account become insecure.

  • Linux and macOS

    Run the following commands. Replace <access_key_id> and <access_key_secret> with the AccessKey ID and AccessKey secret of the RAM user that you use.

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

    1. Create an environment variable file, add the ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET environment variables to the file, and then set the environment variables to your AccessKey ID and AccessKey secret.

    2. Restart Windows for the AccessKey pair to take effect.

Sample 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)
}
Note

For more information, see Process data.