記錄即時使用者事件

本頁說明如何即時記錄使用者事件。媒體應用程式需要使用者事件。如果您不使用媒體應用程式,則不需要匯入使用者事件。不過,建議您為自訂搜尋和推薦應用程式記錄使用者事件。

如要瞭解可記錄的使用者事件類型,請參閱 userEvents 物件的 eventType 欄位。您可以擷取使用者事件,改善結果品質。舉例來說,使用者事件會影響搜尋結果的排名。點閱率較高的結果會獲得提升,點閱率較低的結果則會被埋沒。請勿為尚未匯入的文件記錄使用者事件。

如果您使用的是附加多個資料儲存區的搜尋應用程式,Google 建議您在位置層級擷取使用者事件,而非在資料儲存層級擷取。這樣一來,系統就能將特定使用者事件傳送至相關聯的資料儲存庫。如要在位置層級 (而非資料儲存庫層級) 擷取來自不同 dataStores 的文件使用者事件,請參閱 userEvents.write

如要大量匯入歷來使用者事件,請參閱「匯入歷來使用者事件」。

您可以透過下列方式記錄使用者事件:

如要瞭解使用者事件的 JSON 表示法,請參閱 API 參考資料中的 userEvents

事前準備

匯入使用者事件前:

使用 JavaScript 像素記錄即時使用者事件

如要使用 JavaScript 像素記錄使用者事件,請按照下列步驟操作:

  1. 建立 API 金鑰,用於呼叫 userEvents.collect 方法。
  2. 如要查看收集使用者事件的 JavaScript 代碼範例,請參閱JavaScript 像素範例

建立 API 金鑰

如果您使用 JavaScript 像素收集使用者瀏覽器的使用者事件,就必須使用 API 金鑰。

如要建立 API 金鑰以呼叫 userEvents.collect 方法,請完成下列步驟:

  1. 前往 Google Cloud 控制台的「憑證」頁面。

    憑證

  2. 在 Google Cloud 控制台頁面頂端的專案下拉式選單中,選取專案 (專案可能已選取)。

  3. 按一下「建立憑證」,然後選取「API 金鑰」請勿加入任何參照網址限制。部分使用者隱私權設定不會傳遞參照網址。

    • 請記下產生的 API 金鑰,您會在呼叫使用者事件記錄時使用這組金鑰。
  4. 為提升安全性,請在 API 金鑰中新增 HTTP 限制,限制對 https://discoveryengine.googleapis.com/* 中的 AI 應用程式服務存取權。

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

如果您要記錄位置層級的使用者事件,請使用 https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/LOCATION/userEvents:write 端點。

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/v1/projects/PROJECT_NUMBER/locations/global/dataStores/DATA_STORE_ID/userEvents:write"

C#

詳情請參閱 AI Applications C# API 參考說明文件

如要向 AI Applications 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

詳情請參閱 AI Applications Go API 參考說明文件

如要向 AI Applications 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。


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

詳情請參閱 AI Applications Java API 參考說明文件

如要向 AI Applications 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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

詳情請參閱 AI Applications Python API 參考說明文件

如要向 AI Applications 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

# 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

詳情請參閱 AI Applications Ruby API 參考說明文件

如要向 AI Applications 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

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