תיעוד אירועים של משתמשים בזמן אמת

בדף הזה מוסבר איך לתעד אירועים של משתמשים בזמן אמת. אירועים שקשורים למשתמשים נדרשים באפליקציות מדיה. אם אתם לא משתמשים באפליקציות מדיה, לא צריך לייבא אירועים של משתמשים. עם זאת, מומלץ לתעד אירועים של משתמשים באפליקציות של המלצות וחיפושים מותאמים אישית.

בקטע eventType של אובייקט userEvents מפורטים סוגי האירועים של המשתמשים שאפשר לתעד. הוספת אירועים של משתמשים יכולה לשפר את איכות התוצאות. לדוגמה, אירועים שקשורים למשתמשים משפיעים על הדירוג של תוצאות החיפוש. תוצאות עם שיעורי קליקים גבוהים יותר מקבלות דחיפה, ותוצאות עם שיעורי קליקים נמוכים יותר נדחקות למטה. לא מתבצעת הקלטה של אירועים של משתמשים במסמכים שלא ייובאו.

אם אתם משתמשים באפליקציה עם כמה מאגרי נתונים שמחוברים אליה, כדאי להטמיע אירועים של משתמשים ברמת המיקום ולא ברמת מאגר הנתונים. כך אפשר לשלוח אירוע משתמש מסוים למאגר הנתונים שאליו הוא משויך. כשמתעדים אירועים של משתמשים ברמת המיקום, צריך לכלול את השדה engine באירועים של המשתמשים כדי לשייך את האירוע לאפליקציה הנכונה. דוגמאות לאירועים של משתמשים שכוללים את השדה engine:

כדי לייבא אירועים היסטוריים של משתמשים בכמות גדולה, אפשר לקרוא את המאמר ייבוא אירועים היסטוריים של משתמשים.

אפשר להקליט אירועים של משתמשים בדרכים הבאות:

למידע על ייצוג JSON של אירועים שקשורים למשתמשים, אפשר לעיין בuserEvents בהפניה ל-API.

לפני שמתחילים

לפני שמייבאים אירועים של משתמשים:

תיעוד אירועים של משתמשים בזמן אמת באמצעות פיקסל JavaScript

כדי לתעד אירועים של משתמשים באמצעות פיקסל JavaScript:

  1. יוצרים מפתח API לקריאות ל-method‏ userEvents.collect.
  2. בדוגמה לפיקסל JavaScript אפשר לראות דוגמה לתג JavaScript שאוסף אירועים של משתמשים.

יצירה של מפתח API

מפתח API נדרש אם משתמשים בפיקסל JavaScript כדי לאסוף אירועים של משתמשים מדפדפני המשתמשים.

כדי ליצור מפתח API לקריאות ל-method‏ userEvents.collect, מבצעים את השלבים הבאים:

  1. נכנסים לדף Credentials במסוף Google Cloud .

    פרטי כניסה

  2. ברשימת הפרויקטים בחלק העליון של הדף במסוף Google Cloud , בוחרים את הפרויקט (יכול להיות שהוא כבר נבחר).

  3. לוחצים על Create credentials ואז על API key. לא להוסיף הגבלות על מפנים. חלק מהגדרות הפרטיות של המשתמשים לא מעבירות את כתובת ה-URL של הדף המפנה.

    • חשוב לשים לב למפתח ה-API שנוצר, כי תצטרכו להשתמש בו כשמפעילים רישום ביומן של אירועי משתמש.
  4. כדי לשפר את האבטחה, מוסיפים הגבלת HTTP למפתח ה-API כדי להגביל את הגישה לשירות Agent Search בכתובת https://discoveryengine.googleapis.com/*.

דוגמה לפיקסל JavaScript

בדוגמה הבאה מתועד אירוע משתמש view-item באמצעות פיקסל JavaScript.

לייצוג JSON של אירועים של משתמשים, אפשר לעיין ב-userEvents בהפניה ל-API.

<script type="text/javascript">
var user_event = {
  "eventType" : "view-item",
  "userPseudoId": "USER_PSEUDO_ID",
  "engine": "projects/PROJECT_ID/locations/LOCATION_ID/collections/default_collection/engines/APP_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 מהשרת העורפי.

כדי לתעד אירועים של משתמשים, שולחים בקשת POST לשיטה userEvents.write ומספקים את גוף הבקשה המתאים. למידע על ייצוג JSON של אירועי משתמשים, ראו userEvents בהפניית ה-API.

אם אתם מתעדים אירועים של משתמשים ברמת המיקום, אתם צריכים להשתמש בנקודת הקצה 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" \
     "https://discoveryengine.googleapis.com/v1/projects/PROJECT_NUMBER/locations/global/userEvents:write" \
     -d '{
         "eventType": "view-item",
         "userPseudoId": "visitor0",
         "engine": "projects/PROJECT_NUMBER/locations/global/collections/default_collection/engines/APP_ID",
         "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"
         }
        }'

C#

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים C#.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Go.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


//go:build examples

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Java.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Python.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

# 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

מידע נוסף מופיע בתיעוד העזר של ה-API של חיפוש מבוסס סוכנים Ruby.

כדי לבצע אימות ב-חיפוש מבוסס סוכנים, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

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