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.

Add dependencies

Download dependency packages at https://www.nuget.org/packages.

dotnet add package AlibabaCloud.TeaUtil --version  0.1.5
dotnet add package AlibabaCloud.OpenSearchUtil --version 1.0.2
dotnet add package Aliyun.Credentials --version  1.2.1
dotnet add package Tea --version 0.4.0

Sample code

The following sample code shows how to push behavioral data by using the SDK for C#:

using System;
using System.Collections.Generic;
using AlibabaCloud.TeaUtil.Models;
using Tea;

namespace ConsoleApp2
{
    internal class Program
    {
        public static Dictionary<string, object> behaviorBulk(Client opensearchClient, string appName,
            string collectionName, List<object> docContent, Dictionary<string, string> header, RuntimeOptions runTime)
        {
            string pathName = "/v3/openapi/app-groups/" + appName + "/data-collections/" + collectionName +
                              "/data-collection-type/BEHAVIOR/actions/bulk";
            try
            {
                return opensearchClient._request("POST", pathName, null, header, docContent, runTime);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }


        private static void Main(string[] args)
        {
            var runtime = new RuntimeOptions
            {
                ConnectTimeout = 5000,
                ReadTimeout = 10000,
                MaxAttempts = 0,
                Autoretry = false,
                IgnoreSSL = false,
                MaxIdleConns = 50
            };

            var config = new Config
            {
                // Specify the endpoint of the OpenSearch API. You can obtain the endpoint from the OpenSearch console.
                Endpoint = "opensearch-cn-hangzhou.aliyuncs.com",

                // Specify the request protocol. Valid values: HTTPS and HTTP.
                Protocol = "HTTPS",

                // 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.
                AccessKeyId =  System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),

                // Specify the authentication method. Default value: access_key. A value of sts indicates authentication based on Resource Access Management (RAM) and Security Token Service (STS).
                // Valid values: sts and access_key.
                Type = "access_key",

                // If you use authentication based on RAM and STS, you must specify the SecurityToken parameter. You can call the AssumeRole operation of Alibaba Cloud RAM to obtain an STS token.
                SecurityToken = "",
            };

            // Create an OpenSearch client instance.
            var openSearch = new Client(config);

            // Specify the name of the application to which you want to push data.
            var appName = "appName";

            // Customize HTTP headers.
            var header = new Dictionary<string, string>();

            // --------------- Push behavior logs ---------------
            

            // item_id: the ID of the primary key returned in search results.
            string item_id = "358713";

            // ops_request_misc: the request miscellaneous information returned in search results.
            string ops_request_misc =
                "%7B%22request%5Fid%22%3A%22161777635816780357273903%22%2C%22scm%22%3A%2220140713.130149759..%22%7D";

            // 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.
            string bhv_type = "click";

            // request_id: the request ID returned in search results.
            string request_id = "161777635816780357273903";

            // reach_time: The time when the data is received by the server. The value is a UNIX timestamp that is accurate to the second.
            string reach_time = "1709708439";

            // 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.
            string user_id = "a7a0d37c824b659f36a5b9e3b819fcdd";

            List<object> behaviorDocs = new List<object>();
            Dictionary<string, object> behaviorDoc = new Dictionary<string, object>();

            Dictionary<string, object> behaviorDocFields = new Dictionary<string, object>()
            {
                {"item_id", item_id},
                {"sdk_type", "opensearch_sdk"},
                {"sdk_version", "<sdk_version>"}, // The version number of OpenSearch SDK for C#.
                {"trace_id", "ALIBABA"}, // The service provider.
                {"trace_info", ops_request_misc},
                {"bhv_type", bhv_type},
                {"item_type", "item"},
                {"rn", request_id},
                {"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", reach_time},
                {"user_id", user_id}
            };

            behaviorDoc.Add("cmd", "ADD");
            behaviorDoc.Add("fields", behaviorDocFields);

            behaviorDocs.Add(behaviorDoc);
            try
            {
                behaviorBulk(openSearch, appName, appName, behaviorDocs, header, runtime);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }
}
Note

For more information, see Push collected data.