记录实时用户事件

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

如需了解您可以记录的用户事件类型,请参阅 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. 为提高安全性,请添加 HTTP 限制 您的 API 密钥,以限制对 Vertex AI Agent Builder 服务的访问权限 https://discoveryengine.googleapis.com/*

JavaScript 像素示例

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

如需了解用户事件的 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