Behavioral data push demo

更新时间:
复制 MD 格式

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.

Install package dependencies

The package dependency is available 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 code provides a sample for the C# SDK:

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
            {
                // Configure a unified request endpoint. You can obtain this information from the console.
                Endpoint = "opensearch-cn-hangzhou.aliyuncs.com",

                // The protocol can be set to HTTPS or HTTP.
                Protocol = "HTTPS",

                /* User identity information.
                Reads the AccessKey ID and AccessKey secret from environment variables.
                Before you run the sample code, you must configure the environment variables. For more information, see the "Configure environment variables" section in this document. */
                AccessKeyId =  System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_ID"),
                AccessKeySecret = System.Environment.GetEnvironmentVariable("ALIBABA_CLOUD_ACCESS_KEY_SECRET"),

                // The type parameter specifies the authentication method, which can be sts or access_key. The default value is access_key. To use RAM-STS authentication, set this parameter to sts.
                // Valid values: sts and access_key.
                Type = "access_key",

                // If you use RAM-STS authentication, you must configure security_token. You can call the Alibaba Cloud AssumeRole operation to obtain the STS authentication structure.
                SecurityToken = "",
            };

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

            // The appName to search.
            var appName = "appName";

            // Custom HttpHeaders.
            var header = new Dictionary<string, string>();

            // ---------------  Behavioral logs ---------------
            

            // The item_id is the primary key returned in the search results. It is the primary key ID.
            string item_id = "358713";

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

            // The bhv_type is the feature information of a behavioral event. The following values are supported:
            // cart (add to shopping cart)
            // collect (add to favorites)
            // like (give a like)
            // comment (post a comment)
            // buy (make a purchase)
            // click (click or view)
            string bhv_type = "click";

            // The request_id is the request_id information returned in the search request.
            string request_id = "161777635816780357273903";

            // The time when the data arrives at the server-side. Format: UNIX timestamp. Unit: seconds.
            string reach_time = "1709708439";

            // The ID that uniquely identifies a user on the client application.
            // * This is typically the ID of the logged-on user.
            // * For a PC client, if the user is not logged on, you can set this to 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 the OpenSearch SDK that you are using.
                {"trace_id", "ALIBABA"}, // Used to identify which service provider is called.
                {"trace_info", ops_request_misc},
                {"bhv_type", bhv_type},
                {"item_type", "item"},
                {"rn", request_id},
                {"biz_id", "<biz_id>"}, // A numeric ID used by the mobile phone or client application to distinguish between services. This field can be used to associate the application with an application in OpenSearch or an instance in AIRec.
                {"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.