リアルタイムのユーザー イベントを記録する

このページでは、ユーザー イベントをリアルタイムで記録する方法について説明します。

記録できるユーザー イベントのタイプについては、userEvents オブジェクトの eventType フィールドをご覧ください。ユーザー イベントを取り込むことで、結果の品質を改善できます。たとえば、ユーザー イベントは検索結果のランキングに影響します。クリック率が高い結果はブーストされ、クリック率が低い結果は非表示になります。まだインポートしていないドキュメントのユーザー イベントを記録しないでください。

複数のデータストアが接続されたアプリを使用している場合は、データストア レベルではなく、ロケーション レベルでユーザー イベントを取り込むことをおすすめします。これにより、特定のユーザー イベントを関連付けられているデータストアに送信できます。データストア レベルではなくロケーション レベルで、異なる 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 キー] を選択します。リファラー制限を追加しないでください。一部のユーザーのプライバシー設定では、参照 URL が渡されません。

    • 生成された API キーをメモします。このキーは、ユーザー イベント ロギングを呼び出すときに使用します。
  4. セキュリティを強化するには、API キーに HTTP 制限を追加して、https://discoveryengine.googleapis.com/* での Gemini Enterprise サービスへのアクセスを制限します。

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#

このサンプルを試す前に、Gemini Enterprise クイックスタート: クライアント ライブラリの使用にある C# の設定手順を完了してください。 詳細については、Gemini Enterprise C# API リファレンス ドキュメントをご覧ください。

Gemini Enterprise に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

このサンプルを試す前に、Gemini Enterprise クイックスタート: クライアント ライブラリの使用にある Go の設定手順を完了してください。 詳細については、Gemini Enterprise Go API リファレンス ドキュメントをご覧ください。

Gemini Enterprise に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。


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

このサンプルを試す前に、Gemini Enterprise クイックスタート: クライアント ライブラリの使用にある Java の設定手順を完了してください。 詳細については、Gemini Enterprise Java API リファレンス ドキュメントをご覧ください。

Gemini Enterprise に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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

このサンプルを試す前に、Gemini Enterprise クイックスタート: クライアント ライブラリの使用にある Python の設定手順を完了してください。 詳細については、Gemini Enterprise Python API リファレンス ドキュメントをご覧ください。

Gemini Enterprise に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

# 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

このサンプルを試す前に、Gemini Enterprise クイックスタート: クライアント ライブラリの使用にある Ruby の設定手順を完了してください。 詳細については、Gemini Enterprise Ruby API リファレンス ドキュメントをご覧ください。

Gemini Enterprise に対する認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

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