UI に通勤検索を実装する(v4beta1)

UI に通勤検索を統合すると、求職者は通勤時間によって特定された地域内の求人情報を検索できるようになります。通勤検索では、ユーザーが選択した交通機関モードと移動時刻に基づいて通勤時間が推測されます。

  1. 通勤検索を実装する前に、Cloud Talent Solution を UI に接続する必要があります。<atarget="_blank" class="external" l10n-attrs-original-order="href,target,class" l10n-encrypted-href="I2bjjCb1CfjxAHi33R1uSZFGBtNXMtSEozqMDCbrBLAVTmdE5Zm3DKcU3qbzRuF63VaMACw+gvDqWC/9WAxKePGKDAnihfIk/OpwQPRVH65wl/sHYgP9zxpmH4qLkPOM">quickstart guides to set up Cloud Talent Solution.</atarget="_blank"> に従ってください。

  2. 通勤検索では、CTS の実装時に求人情報とともにアップロードされた住所データを使用して通勤時間を計算します。既存の CTS UI でこの機能を有効にするには、jobs.search リクエストを送信し、CommuteFilter オブジェクトを JobQuery.commuteFilter フィールドに含めます。commuteMethodtravelDurationstartCoordinates、および roadTraffic または departureTime は必須項目です。

Go

CTS 用のクライアント ライブラリをインストールして使用する方法については、CTS クライアント ライブラリをご覧ください。 詳細については、CTS Go API のリファレンス ドキュメントをご覧ください。

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

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"cloud.google.com/go/talent/apiv4beta1/talentpb"
	"github.com/golang/protobuf/ptypes/duration"
	"google.golang.org/genproto/googleapis/type/latlng"
)

// commuteSearch searches for jobs within commute filter.
func commuteSearch(w io.Writer, projectID, companyID string) error {
	ctx := context.Background()

	// Initialize a jobService client.
	c, err := talent.NewJobClient(ctx)
	if err != nil {
		return fmt.Errorf("talent.NewJobClient: %w", err)
	}
	defer c.Close()

	// Construct a jobQuery request with a commute filter.
	jobQuery := &talentpb.JobQuery{
		CommuteFilter: &talentpb.CommuteFilter{
			CommuteMethod:  talentpb.CommuteMethod_TRANSIT,
			TravelDuration: &duration.Duration{Seconds: 1800},
			StartCoordinates: &latlng.LatLng{
				Latitude:  37.422408,
				Longitude: -122.085609,
			},
		},
	}
	if companyID != "" {
		jobQuery.Companies = []string{fmt.Sprintf("projects/%s/companies/%s", projectID, companyID)}
	}

	// Construct a searchJobs request with a jobQuery.
	req := &talentpb.SearchJobsRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		// Make sure to set the RequestMetadata the same as the associated
		// search request.
		RequestMetadata: &talentpb.RequestMetadata{
			// Make sure to hash your userID.
			UserId: "HashedUsrID",
			// Make sure to hash the sessionID.
			SessionId: "HashedSessionID",
			// Domain of the website where the search is conducted.
			Domain: "www.googlesample.com",
		},
		// Set the actual search term as defined in the jobQuery.
		JobQuery: jobQuery,
	}

	resp, err := c.SearchJobs(ctx, req)
	if err != nil {
		return fmt.Errorf("SearchJobs: %w", err)
	}

	for _, job := range resp.GetMatchingJobs() {
		fmt.Fprintf(w, "Matcing Job: %q\n", job.GetJob().GetName())
		fmt.Fprintf(w, "Job address: %v\n", job.GetCommuteInfo().GetJobLocation().GetPostalAddress().GetAddressLines())
	}

	return nil
}

Java

Cloud Talent Solution クライアントのインストールと作成の詳細については、Cloud Talent Solution クライアント ライブラリをご覧ください。


import com.google.cloud.talent.v4beta1.CommuteFilter;
import com.google.cloud.talent.v4beta1.CommuteMethod;
import com.google.cloud.talent.v4beta1.Job;
import com.google.cloud.talent.v4beta1.JobQuery;
import com.google.cloud.talent.v4beta1.JobServiceClient;
import com.google.cloud.talent.v4beta1.RequestMetadata;
import com.google.cloud.talent.v4beta1.SearchJobsRequest;
import com.google.cloud.talent.v4beta1.SearchJobsResponse;
import com.google.cloud.talent.v4beta1.TenantName;
import com.google.protobuf.Duration;
import com.google.type.LatLng;
import java.io.IOException;

public class CommuteSearchJobs {

  public static void searchJobs() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String tenantId = "your-tenant-id";
    searchJobs(projectId, tenantId);
  }

  // Search Jobs with histogram queries.
  public static void searchJobs(String projectId, String tenantId) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
      TenantName parent = TenantName.of(projectId, tenantId);
      String domain = "www.example.com";
      String sessionId = "Hashed session identifier";
      String userId = "Hashed user identifier";
      RequestMetadata requestMetadata =
          RequestMetadata.newBuilder()
              .setDomain(domain)
              .setSessionId(sessionId)
              .setUserId(userId)
              .build();

      CommuteMethod commuteMethod = CommuteMethod.DRIVING;
      long seconds = 3600L;
      Duration travelDuration = Duration.newBuilder().setSeconds(seconds).build();

      double latitude = 37.422408;
      double longitude = -122.084068;
      LatLng startCoordinates =
          LatLng.newBuilder().setLatitude(latitude).setLongitude(longitude).build();

      CommuteFilter commuteFilter =
          CommuteFilter.newBuilder()
              .setCommuteMethod(commuteMethod)
              .setTravelDuration(travelDuration)
              .setStartCoordinates(startCoordinates)
              .build();

      JobQuery jobQuery = JobQuery.newBuilder().setCommuteFilter(commuteFilter).build();
      SearchJobsRequest request =
          SearchJobsRequest.newBuilder()
              .setParent(parent.toString())
              .setRequestMetadata(requestMetadata)
              .setJobQuery(jobQuery)
              .build();

      for (SearchJobsResponse.MatchingJob responseItem :
          jobServiceClient.searchJobs(request).iterateAll()) {
        System.out.format("Job summary: %s%n", responseItem.getJobSummary());
        System.out.format("Job title snippet: %s%n", responseItem.getJobTitleSnippet());
        Job job = responseItem.getJob();
        System.out.format("Job name: %s%n", job.getName());
        System.out.format("Job title: %s%n", job.getTitle());
      }
    }
  }
}

Python

Cloud Talent Solution クライアントのインストールと作成の詳細については、Cloud Talent Solution クライアント ライブラリをご覧ください。


from google.cloud import talent

def search_jobs(project_id, tenant_id):
    """Search Jobs using commute distance"""

    client = talent.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'

    if isinstance(project_id, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    parent = f"projects/{project_id}/tenants/{tenant_id}"
    domain = "www.example.com"
    session_id = "Hashed session identifier"
    user_id = "Hashed user identifier"
    request_metadata = talent.RequestMetadata(
        domain=domain, session_id=session_id, user_id=user_id
    )
    commute_method = talent.CommuteMethod.TRANSIT
    seconds = 1800
    travel_duration = {"seconds": seconds}
    latitude = 37.422408
    longitude = -122.084068
    start_coordinates = {"latitude": latitude, "longitude": longitude}
    commute_filter = talent.CommuteFilter(
        commute_method=commute_method,
        travel_duration=travel_duration,
        start_coordinates=start_coordinates,
    )
    job_query = talent.JobQuery(commute_filter=commute_filter)

    # Iterate over all results
    results = []
    request = talent.SearchJobsRequest(
        parent=parent,
        request_metadata=request_metadata,
        job_query=job_query,
    )
    for response_item in client.search_jobs(request=request).matching_jobs:
        print(f"Job summary: {response_item.job_summary}")
        print(f"Job title snippet: {response_item.job_title_snippet}")
        job = response_item.job
        results.append(job.name)
        print(f"Job name: {job.name}")
        print(f"Job title: {job.title}")
    return results

UI に関する推奨事項

  1. Cloud Talent Solution では、同じ API 呼び出しで距離(CTS ロケーション フィルタを使用)と通勤時間の両方で検索することはできません。求職者が両方のオプションにアクセスできるようにする場合は、2 つのタブを用意するなどの手法を用います。

  2. バックエンドによって求職者の関連情報が通勤フィルタに自動的に入力されるように、アプリケーションのフロントエンドを変更します。バックエンドは、通常の検索リクエストと同様に API を呼び出す必要があります。

  3. UI にアイテムを追加する:

    • 距離検索または通勤検索を選択するためのオプション。検索 UI は、たとえば次のようになります。

    • 通勤手段のオプションを選択するためのプルダウン メニュー。

    • 交通状況を調整するためのオプション。

    • 合計移動時間(サポートされている最大移動時間は 60 分です)。

    • 通勤の出発時刻。

  4. API から返された通勤時間の情報は、求職者に情報を表示するために使用されます。関連度の高い求人情報のうち、指定した通勤時間の圏内にあるものだけが結果リストとして返されます。結果として返される通勤時間圏内の求人情報の順序と件数を調整する方法については、求人検索のおすすめの方法のドキュメントをご覧ください。

  5. 通勤に関する検索の結果は、実際の交通状況ではなく、過去の集計データに基づいています。departureTime の交通状況は、指定された時刻の平均的な交通状況から計算されます。roadTrafficBUSY_HOUR/TRAFFIC_FREE オプションは、それぞれ朝のラッシュアワーと深夜の平均的な交通状況です。ユーザーは、クエリを送信した時刻に関係なく、同じ通勤に関する検索結果を受け取ります。

Google マップを利用して、CTS から返された通勤時間情報に基づいて地図を生成し、求職者に返される結果に埋め込むことができます。Maps API スイートには、マップを表示するためのオプションがいくつか用意されています。Maps API オプションの中には、他のオプションよりも効果的なものがあります。たとえば、求職者に返される関連性の高い求人を効果的に可視化する方法として、Google Maps JavaScript ヒートマップ可視化マーカー クラスタリングを組み合わせて使用すると、求職者が通勤設定で指定した地域内での求人を可視化できます。逆に、ルート検索モードは、検索リクエストで返されたすべてのジョブを表示しないのでおすすめできません。

通勤時間に基づく検索の実装の詳細については、通勤検索に関する入門ガイドをご覧ください。