All Products
Search
Document Center

OpenSearch:Demo code for pushing behavioral data

Last Updated:Mar 13, 2024

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
  }


  // item_id: the ID of the primary key returned in search results.
  itemId := "<item_id>"

  // ops_request_misc: the request miscellaneous information returned in search results.
  opsRequestMisc :="<ops_request_misc>"


  // bhv_type: the event type of the behavioral data. Valid values:
  // cart: adds a commodity to the shopping cart.
  // collect: adds a commodity to favorites.
  // like: likes a commodity.
  // comment: posts a comment on a commodity.
  // buy: purchases a commodity.
  // click: clicks or views a commodity.
  bhvType := "<bhv_type>"

  // requestId: the request ID returned in search results.
  requestId :="<request_id>"

  // reach_time: The time when the data is received by the server. The value is a UNIX timestamp that is accurate to the second.
  reachTime :="<reach_time>"


  // user_id: the unique ID of the user who sent the request. 
  // * In most cases, the ID is that of the user that has logged on. 
  // * If the user sent the request from a PC client and has not logged on, the ID is the cookie ID.
  user_id:="<user_id>"
  behavior_fields :=map[string]interface{}{
      "item_id": itemId,
      "sdk_type": "opensearch_sdk",
      "sdk_version": "<sdk_version>",  // The version number of OpenSearch SDK for Go.
      "trace_id": "ALIBABA",  // The service provider.
      "trace_info": opsRequestMisc,
      "bhv_type": bhvType,
      "item_type": "item",
      "rn": requestId,
      "biz_id":"<biz_id>",  // The numerical ID that is used by mobile applications or application clients to differentiate business. This parameter can be associated with OpenSearch applications and Artificial Intelligence Recommendation (AIRec) instances.
      "reach_time": reachTime,
      "user_id": user_id,

  }

  bhv_actions := []string{"like", "comment", "buy"}
  if IsContain(bhv_actions,bhvType){  // If the type of a behavior is one of the types specified by the bhv_actions parameter, more detailed information about the behavior needs to be provided.

      // The description of the behavior. Format: key=value{,key=value}
      behavior_fields["bhv_detail"] ="<bhv_detail>"

      // The numerical information about the behavior, such as the stay duration and the number of purchased commodities.
      behavior_fields["bhv_value"] ="<bhv_value>"
  }
  behavior_document := map[string]interface{}{
      "cmd": "ADD",
      "fields": behavior_fields,
  }

  // Add the documents to an array. Each document contains the operation to be performed on the document.
  requestBody := []interface{}{behavior_document}

  // 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 data, you must specify the appName and dataCollectionName parameters.
    // appName: the name of the application to which you want to push data. Do not set this parameter to the version information of an application.
    appName := "<appName>"
    dataCollectionName := "<dataCollectionName>"

    // Specify the dataCollectionType parameter. By default, this value is set to BEHAVIOR.
    dataCollectionType := "BEHAVIOR"

    // Call the method for sending a request.
  _reponse, _request_err := client.Request(
      tea.String("POST"),
      tea.String("/v3/openapi/app-groups/"+appName+"/data-collections/"+dataCollectionName+"/data-collection-type/"+dataCollectionType+"/actions/bulk"),
      nil,
      nil,
      requestBody,
      runtime)

  // If an exception occurs when the system sends the request, _request_err is not nil. In this case, display the error information.
  if _request_err != nil {
      fmt.Println(_request_err)
      return
  }

  // Display the response if no exception occurs.
  fmt.Println(_reponse)
}

func IsContain(items []string, item string) bool {
   for _, eachItem := range items {
       if eachItem == item {
           return true
       }
   }
   return false
}