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

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

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

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

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

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

במאמרי העזרה של ה-API, בקטע userEvents, מוסבר איך לייצג אירועי משתמשים בפורמט JSON.

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

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

תיעוד אירועי משתמשים בזמן אמת באמצעות פיקסל 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. אל תוסיפו הגבלות על גורמים מפנים. חלק מהגדרות הפרטיות של המשתמשים לא מעבירות את כתובת ה-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

אתם יכולים להשתמש ב-method‏ userEvents.write כדי לשלוח אירועי משתמשים ישירות ל-API משרת הבק-אנד.

כדי לתעד אירועי משתמשים, שולחים בקשת POST ל-method ‏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#

מידע נוסף מופיע במאמרי העזרה של Agent Search C# API.

כדי לבצע אימות ב-"חיפוש מבוסס סוכנים", צריך להגדיר את 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

מידע נוסף מופיע במאמרי העזרה של Agent Search Go API.

כדי לבצע אימות ב-"חיפוש מבוסס סוכנים", צריך להגדיר את 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

מידע נוסף מופיע במאמרי העזרה של Agent Search Java API.

כדי לבצע אימות ב-"חיפוש מבוסס סוכנים", צריך להגדיר את 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

מידע נוסף מופיע במאמרי העזרה של Agent Search Python API.

כדי לבצע אימות ב-"חיפוש מבוסס סוכנים", צריך להגדיר את 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

מידע נוסף מופיע במאמרי העזרה של Agent Search Ruby API.

כדי לבצע אימות ב-"חיפוש מבוסס סוכנים", צריך להגדיר את 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