记录实时用户事件

本页介绍了如何实时记录用户事件。媒体推荐需要用户事件。如果您不使用媒体推荐功能,则无需导入用户事件。不过,建议媒体搜索应用记录用户事件。

如需了解您可以记录的用户事件类型,请参阅 userEvents 对象的 eventType 字段。通过提取用户事件,您可以提高推荐内容的质量以及搜索结果的排名。点击率较高的结果会被提升,而点击率较低的结果会被隐藏。对于尚未导入的文档,请勿记录其用户事件。

如果您使用的搜索应用附加了多个数据存储区,Google 建议您在位置级别(而非数据存储区级别)注入用户事件。这样一来,系统便可将指定的用户事件发送到与其关联的数据存储区。如需在位置级(而非数据存储区级)注入包含来自不同 dataStores 的文档的用户事件,请参阅 userEvents.write

如需批量导入历史用户事件,请参阅导入历史用户事件

您可以通过以下方式记录用户事件:

如需了解用户事件的 JSON 表示法,请参阅 API 参考文档中的 userEvents

准备工作

在导入用户事件之前,请确保:

  • 创建数据存储区和应用。
  • 如需了解用户事件要求,请参阅用户事件简介

使用 JavaScript 像素记录实时用户事件

如需使用 JavaScript 像素记录用户事件,请执行以下操作:

  1. 为调用 userEvents.Collect 方法创建 API 密钥
  2. 如需查看收集用户事件的 JavaScript 代码示例,请参阅 JavaScript 像素示例

创建 API 密钥

如果您使用 JavaScript 像素从用户的浏览器收集用户事件,则必须使用 API 密钥。

如需为调用 userEvents.Collect 方法创建 API 密钥,请完成以下步骤:

  1. 在 Google Cloud 控制台中,转到凭据页面。

    凭据

  2. 在 Google Cloud 控制台页面顶部的项目下拉菜单中,选择您的项目(该项目可能已被选中)。

  3. 点击创建凭据,然后选择 API 密钥请勿添加任何引荐来源网址限制。部分用户隐私设置不会传递引荐来源网址。

    • 请记下生成的 API 密钥,将用于调用用户事件日志记录。
  4. 为提高安全性,请向您的 API 密钥添加 HTTP 限制,以限制对 https://discoveryengine.googleapis.com/* 的 Vertex AI Agent Builder 服务的访问权限。

JavaScript 像素示例

以下示例使用 JavaScript 像素记录 view-item 用户事件。

如需了解用户事件的 JSON 表示法,请参阅 API 参考文档中的 userEvents

<script type="text/javascript">
var user_event = {
  "eventType" : "view-item",
  "userPseudoId": "USER_PSEUDO_ID",
  "userInfo": {
      "userId": "USER_ID"
  },
  "attributionToken": "ATTRIBUTION_TOKEN",
  "tagIds": "TAG_ID",
  "documents": [
      {
        "id": "DOCUMENT_ID"
      }
  ]
};

var _gre = _gre || {};
// Credentials for project.
_gre.apiKey = '[API_KEY]';
_gre.logEvent = user_event;
_gre.projectId = 'PROJECT_ID';
_gre.locationId = 'LOCATION_ID';
_gre.dataStoreId = 'DATA_STORE_ID';

(function() {
  var gre = document.createElement('script'); gre.type = 'text/javascript'; gre.async = true;
  gre.src = 'https://www.gstatic.com/discoveryengine/v1beta_event.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(gre, s);
})();

</script>

使用 userEvents.write 方法记录实时用户事件

REST

您可以使用 userEvents.write 方法从后端服务器直接将用户事件发送到 API。

如要记录用户事件,请向 userEvents.write 方法发送 POST 请求,并提供相应的请求正文。如需了解用户事件的 JSON 表示形式,请参阅 API 参考文档中的 userEvents

如果您的应用有多个数据存储区,Google 建议您在位置级别注入事件。在这种情况下,请使用端点 https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_NUMBER/locations/LOCATION/userEvents:write

export GOOGLE_APPLICATION_CREDENTIALS=/tmp/my-key.json
curl -X POST \
     -H "Authorization: Bearer $(gcloud auth print-access-token)" \
     -H "Content-Type: application/json; charset=utf-8" \
     --data "{
         'eventType': 'view-item',
         'userPseudoId': 'visitor0',
         'eventTime': '2020-01-01T03:33:33.000001Z',
         'tagIds': ['321'],
         'attributionToken': 'ABC',
         'attributes': {
            'example_text_attribute': {
              'text': ['text_1', 'text_2']
            },
            'example_number_attribute': {
               'numbers': [3.14, 42, 1.2345]
            }
         },
         'documents': [{
            'id': 'abc'
          }],
         'userInfo': {
           'userId': 'abc',
           'userAgent': 'Mozilla/5.0'
         },
         'pageInfo': {
          'uri': 'http://example',
          'referrerUri': 'http://example',
          'pageViewId': 'currentPageUri'
        }
}" \\
"https://discoveryengine.googleapis.com/v1beta/projects/PROJECT_NUMBER/locations/global/dataStores/DATA_STORE_ID/userEvents:write"

C#

如需了解详情,请参阅 Vertex AI Agent Builder C# API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

using Google.Cloud.DiscoveryEngine.V1;

public sealed partial class GeneratedUserEventServiceClientSnippets
{
    /// <summary>Snippet for WriteUserEvent</summary>
    /// <remarks>
    /// This snippet has been automatically generated and should be regarded as a code template only.
    /// It will require modifications to work:
    /// - It may require correct/in-range values for request initialization.
    /// - It may require specifying regional endpoints when creating the service client as shown in
    ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
    /// </remarks>
    public void WriteUserEventRequestObject()
    {
        // Create client
        UserEventServiceClient userEventServiceClient = UserEventServiceClient.Create();
        // Initialize request argument(s)
        WriteUserEventRequest request = new WriteUserEventRequest
        {
            ParentAsDataStoreName = DataStoreName.FromProjectLocationDataStore("[PROJECT]", "[LOCATION]", "[DATA_STORE]"),
            UserEvent = new UserEvent(),
            WriteAsync = false,
        };
        // Make the request
        UserEvent response = userEventServiceClient.WriteUserEvent(request);
    }
}

Go

如需了解详情,请参阅 Vertex AI Agent Builder Go API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证


package main

import (
	"context"

	discoveryengine "cloud.google.com/go/discoveryengine/apiv1"
	discoveryenginepb "cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb"
)

func main() {
	ctx := context.Background()
	// This snippet has been automatically generated and should be regarded as a code template only.
	// It will require modifications to work:
	// - It may require correct/in-range values for request initialization.
	// - It may require specifying regional endpoints when creating the service client as shown in:
	//   https://pkg.go.dev/cloud.google.com/go#hdr-Client_Options
	c, err := discoveryengine.NewUserEventClient(ctx)
	if err != nil {
		// TODO: Handle error.
	}
	defer c.Close()

	req := &discoveryenginepb.WriteUserEventRequest{
		// TODO: Fill request struct fields.
		// See https://pkg.go.dev/cloud.google.com/go/discoveryengine/apiv1/discoveryenginepb#WriteUserEventRequest.
	}
	resp, err := c.WriteUserEvent(ctx, req)
	if err != nil {
		// TODO: Handle error.
	}
	// TODO: Use resp.
	_ = resp
}

Java

如需了解详情,请参阅 Vertex AI Agent Builder Java API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

import com.google.cloud.discoveryengine.v1.DataStoreName;
import com.google.cloud.discoveryengine.v1.UserEvent;
import com.google.cloud.discoveryengine.v1.UserEventServiceClient;
import com.google.cloud.discoveryengine.v1.WriteUserEventRequest;

public class SyncWriteUserEvent {

  public static void main(String[] args) throws Exception {
    syncWriteUserEvent();
  }

  public static void syncWriteUserEvent() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (UserEventServiceClient userEventServiceClient = UserEventServiceClient.create()) {
      WriteUserEventRequest request =
          WriteUserEventRequest.newBuilder()
              .setParent(
                  DataStoreName.ofProjectLocationDataStoreName(
                          "[PROJECT]", "[LOCATION]", "[DATA_STORE]")
                      .toString())
              .setUserEvent(UserEvent.newBuilder().build())
              .setWriteAsync(true)
              .build();
      UserEvent response = userEventServiceClient.writeUserEvent(request);
    }
  }
}

Python

如需了解详情,请参阅 Vertex AI Agent Builder Python API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
#   client as shown in:
#   https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import discoveryengine_v1


def sample_write_user_event():
    # Create a client
    client = discoveryengine_v1.UserEventServiceClient()

    # Initialize request argument(s)
    request = discoveryengine_v1.WriteUserEventRequest(
        parent="parent_value",
    )

    # Make the request
    response = client.write_user_event(request=request)

    # Handle the response
    print(response)

Ruby

如需了解详情,请参阅 Vertex AI Agent Builder Ruby API 参考文档

如需向 Vertex AI Agent Builder 进行身份验证,请设置应用默认凭据。 如需了解详情,请参阅为本地开发环境设置身份验证

require "google/cloud/discovery_engine/v1"

##
# Snippet for the write_user_event call in the UserEventService service
#
# This snippet has been automatically generated and should be regarded as a code
# template only. It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in https://cloud.google.com/ruby/docs/reference.
#
# This is an auto-generated example demonstrating basic usage of
# Google::Cloud::DiscoveryEngine::V1::UserEventService::Client#write_user_event.
#
def write_user_event
  # Create a client object. The client can be reused for multiple calls.
  client = Google::Cloud::DiscoveryEngine::V1::UserEventService::Client.new

  # Create a request. To set request fields, pass in keyword arguments.
  request = Google::Cloud::DiscoveryEngine::V1::WriteUserEventRequest.new

  # Call the write_user_event method.
  result = client.write_user_event request

  # The returned object is of type Google::Cloud::DiscoveryEngine::V1::UserEvent.
  p result
end