Démarrage rapide : effectuer une recherche

Cloud Talent Solution vous permet de rechercher toutes les offres d'emploi actuellement actives que vous avez publiées sur le système CTS. Lorsque vous êtes en mesure de créer des requêtes de recherche, veillez à mettre en œuvre le framework d'analyse des offres d'emploi et les événements client. Ce framework est ce qui constitue toute la puissance de Cloud Talent Solution. Il a une incidence directe sur l'amélioration des résultats de recherche. Des tutoriels vidéo et des ateliers de programmation interactifs sont également disponibles.

Obtenir un histogramme du nombre d'offres d'emploi dans un domaine

L'API de recherche renvoie également un histogramme de toutes les offres d'emploi pertinentes indexées dans Cloud Talent Solution et qui correspondent aux filtres de la requête de recherche. Maintenant que vous avez obtenu les résultats de la recherche, vous pouvez obtenir un décompte des offres d'emploi selon différents attributs. Tirez parti de l'API d'histogramme pour obtenir le nombre d'offres d'emploi en fonction de certains attributs.

Go

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"google.golang.org/api/iterator"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
)

// histogramSearch searches for jobs with histogram queries.
func histogramSearch(w io.Writer, projectID, companyID string) error {
	ctx := context.Background()

	// Initialize a jobService client.
	c, err := talent.NewJobClient(ctx)
	if err != nil {
		fmt.Printf("talent.NewJobClient: %v\n", err)
		return err
	}

	// Construct a searchJobs request.
	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",
		},
		HistogramQueries: []*talentpb.HistogramQuery{
			{
				// More info on histogram facets, constants, and built-in functions:
				// https://godoc.org/google.golang.org/genproto/googleapis/cloud/talent/v4beta1#SearchJobsRequest
				HistogramQuery: "count(base_compensation, [bucket(12, 20)])",
			},
		},
	}
	if companyID != "" {
		req.JobQuery = &talentpb.JobQuery{
			CompanyNames: []string{fmt.Sprintf("projects/%s/companies/%s", projectID, companyID)},
		}
	}

	it := c.SearchJobs(ctx, req)

	for {
		resp, err := it.Next()
		if err == iterator.Done {
			return nil
		}
		if err != nil {
			fmt.Printf("it.Next: %v\n", err)
			return err
		}
		fmt.Fprintf(w, "Job: %q\n", resp.Job.GetName())
	}
}

Java

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.


import com.google.cloud.talent.v4.HistogramQuery;
import com.google.cloud.talent.v4.Job;
import com.google.cloud.talent.v4.JobServiceClient;
import com.google.cloud.talent.v4.RequestMetadata;
import com.google.cloud.talent.v4.SearchJobsRequest;
import com.google.cloud.talent.v4.SearchJobsResponse;
import com.google.cloud.talent.v4.TenantName;
import java.io.IOException;

public class HistogramSearchJobs {

  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";
    String query = "count(base_compensation, [bucket(12, 20)])";
    searchJobs(projectId, tenantId, query);
  }

  // Search Jobs with histogram queries.
  public static void searchJobs(String projectId, String tenantId, String query)
      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 = "http://www.jobUrl.com";
      String sessionId = "Hashed session identifier";
      String userId = "Hashed user identifier";
      RequestMetadata requestMetadata =
          RequestMetadata.newBuilder()
              .setDomain(domain)
              .setSessionId(sessionId)
              .setUserId(userId)
              .build();
      HistogramQuery histogramQueriesElement =
          HistogramQuery.newBuilder().setHistogramQuery(query).build();
      SearchJobsRequest request =
          SearchJobsRequest.newBuilder()
              .setParent(parent.toString())
              .setRequestMetadata(requestMetadata)
              .addHistogramQueries(histogramQueriesElement)
              .build();

      for (SearchJobsResponse.MatchingJob responseItem :
          jobServiceClient.searchJobs(request).getMatchingJobsList()) {
        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

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.


from google.cloud import talent
import six

def search_jobs(project_id, tenant_id, query):
    """
    Search Jobs with histogram queries

    Args:
      query Histogram query
      More info on histogram facets, constants, and built-in functions:
      https://godoc.org/google.golang.org/genproto/googleapis/cloud/talent/v4beta1#SearchJobsRequest
    """

    client = talent.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # query = 'count(base_compensation, [bucket(12, 20)])'

    if isinstance(project_id, six.binary_type):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, six.binary_type):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(query, six.binary_type):
        query = query.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 = {"domain": domain, "session_id": session_id, "user_id": user_id}
    histogram_queries_element = {"histogram_query": query}
    histogram_queries = [histogram_queries_element]

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

Ruby

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.

require "google/cloud/talent"

# Instantiate a client
job_service = Google::Cloud::Talent.job_service

# project_id = "Your Google Cloud Project ID"
# tenant_id = "Your Tenant ID (using tenancy is required)"
formatted_parent = job_service.tenant_path project: project_id, tenant: tenant_id
domain = "www.example.com"
session_id = "Hashed session identifier"
user_id = "Hashed user identifier"
request_metadata = {
  domain:     domain,
  session_id: session_id,
  user_id:    user_id
}

# query = "count(base_compensation, [bucket(12, 20)])"
histogram_queries_element = { histogram_query: query }
histogram_queries = [histogram_queries_element]

# Iterate over all results.
response = job_service.search_jobs parent:            formatted_parent,
                                   request_metadata:  request_metadata,
                                   histogram_queries: histogram_queries
response.matching_jobs.each do |element|
  puts "Job summary: #{element.job_summary}"
  puts "Job title snippet: #{element.job_title_snippet}"
  job = element.job
  puts "Job name: #{job.name}"
  puts "Job title: #{job.title}"
end

C#

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.

public static object HistogramSearchJobs(string projectId, string tenantId, string query)
{
    JobServiceClient jobServiceClient = JobServiceClient.Create();
    TenantName name = TenantName.FromProjectTenant(projectId, tenantId);

    string domain = "www.example.com";
    string sessionId = "Hashed session identifier";
    string userId = "Hashed user identifier";
    RequestMetadata requestMetadata = new RequestMetadata
    {
        Domain = domain,
        SessionId = sessionId,
        UserId = userId
    };

    // Examples and formats are explained in the following link:
    // https://cloud.google.com/talent-solution/job-search/docs/reference/rest/v4beta1/projects.tenants.jobs/search#body.request_body.FIELDS.histogram_queries
    HistogramQuery histogramQuery = new HistogramQuery
    {
        HistogramQuery_ = query
    };

    SearchJobsRequest request = new SearchJobsRequest
    {
        ParentAsTenantName = name,
        RequestMetadata = requestMetadata,
    };
    request.HistogramQueries.Add(histogramQuery);

    var response = jobServiceClient.SearchJobs(request);
    foreach (var result in response)
    {
        Console.WriteLine($"Job summary: {result.JobSummary}");
        Console.WriteLine($"Job title snippet: {result.JobTitleSnippet}");
        Job job = result.Job;
        Console.WriteLine($"Job name: {job.Name}");
        Console.WriteLine($"Job title: {job.Title}");
    }

    return 0;
}

Dans ce cas, nous obtenons le nombre d'offres d'emploi qui se trouvent dans le système, acceptées par les filtres spécifiés et pour les différents attributs (CATEGORY et CITY).

Utiliser l'API de saisie semi-automatique pour obtenir le nom des offres d'emploi suggérées

L'API complète suggère des intitulés de postes ou des noms d'entreprises susceptibles d'intéresser le demandeur d'emploi, en fonction de ce qu'il a déjà saisi. Utilisez cette fonction pour saisir les résultats potentiels dans la barre de recherche de l'interface utilisateur de manière semi-automatique.

Go

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
)

// jobTitleAutoComplete suggests the job titles of the given
// company identifier on query.
func jobTitleAutocomplete(w io.Writer, projectID, query string) (*talentpb.CompleteQueryResponse, error) {
	ctx := context.Background()

	// Initialize a completionService client.
	c, err := talent.NewCompletionClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("talent.NewCompletionClient: %v", err)
	}

	// Construct a completeQuery request.
	req := &talentpb.CompleteQueryRequest{
		Parent:        fmt.Sprintf("projects/%s", projectID),
		Query:         query,
		LanguageCodes: []string{"en-US"},
		PageSize:      5, // Number of completion results returned.
		Scope:         talentpb.CompleteQueryRequest_PUBLIC,
		Type:          talentpb.CompleteQueryRequest_JOB_TITLE,
	}

	resp, err := c.CompleteQuery(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CompleteQuery(%s): %v", query, err)
	}

	fmt.Fprintf(w, "Auto complete results:")
	for _, c := range resp.GetCompletionResults() {
		fmt.Fprintf(w, "\t%v\n", c.Suggestion)
	}

	return resp, nil
}

Java

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.


import com.google.cloud.talent.v4.CompleteQueryRequest;
import com.google.cloud.talent.v4.CompleteQueryResponse;
import com.google.cloud.talent.v4.CompletionClient;
import com.google.cloud.talent.v4.TenantName;
import java.io.IOException;

public class JobSearchAutoCompleteJobTitle {

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

  // Complete job title given partial text (autocomplete).
  public static void completeQuery(String projectId, String tenantId, String query)
      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 (CompletionClient completionClient = CompletionClient.create()) {
      TenantName parent = TenantName.of(projectId, tenantId);
      CompleteQueryRequest request =
          CompleteQueryRequest.newBuilder()
              .setTenant(parent.toString())
              .setQuery(query)
              .setPageSize(5) // limit for number of results
              .addLanguageCodes("en-US") // language code
              .build();
      CompleteQueryResponse response = completionClient.completeQuery(request);
      for (CompleteQueryResponse.CompletionResult result : response.getCompletionResultsList()) {
        System.out.format("Suggested title: %s%n", result.getSuggestion());
        // Suggestion type is JOB_TITLE or COMPANY_TITLE
        System.out.format("Suggestion type: %s%n", result.getType());
      }
    }
  }
}

Node.js

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.


const talent = require('@google-cloud/talent').v4;

/**
 * Complete job title given partial text (autocomplete)
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the TenantId
 */
function sampleCompleteQuery(
  projectId,
  tenantId,
  query,
  numResults,
  languageCode
) {
  const client = new talent.CompletionClient();
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const query = '[partially typed job title]';
  // const numResults = 5;
  // const languageCode = 'en-US';
  const formattedParent = client.tenantPath(projectId, tenantId);
  const languageCodes = [languageCode];
  const request = {
    parent: formattedParent,
    query: query,
    pageSize: numResults,
    languageCodes: languageCodes,
  };
  client
    .completeQuery(request)
    .then(responses => {
      const response = responses[0];
      for (const result of response.completionResults) {
        console.log(`Suggested title: ${result.suggestion}`);
        // Suggestion type is JOB_TITLE or COMPANY_TITLE
        console.log(`Suggestion type: ${result.type}`);
      }
    })
    .catch(err => {
      console.error(err);
    });
}

Python

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.


from google.cloud import talent_v4beta1
import six

def complete_query(project_id, tenant_id, query):
    """Complete job title given partial text (autocomplete)"""

    client = talent_v4beta1.CompletionClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # query = '[partially typed job title]'

    if isinstance(project_id, six.binary_type):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, six.binary_type):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(query, six.binary_type):
        query = query.decode("utf-8")

    parent = f"projects/{project_id}/tenants/{tenant_id}"

    request = talent_v4beta1.CompleteQueryRequest(
        parent=parent,
        query=query,
        page_size=5,  # limit for number of results
        language_codes=["en-US"],  # language code
    )
    response = client.complete_query(request=request)
    for result in response.completion_results:
        print(f"Suggested title: {result.suggestion}")
        # Suggestion type is JOB_TITLE or COMPANY_TITLE
        print(
            f"Suggestion type: {talent_v4beta1.CompleteQueryRequest.CompletionType(result.type_).name}"
        )

Ruby

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.

require "google/cloud/talent"

# Instantiate a client
completion_service = Google::Cloud::Talent.completion

# project_id = "Your Google Cloud Project ID"
# tenant_id = "Your Tenant ID (using tenancy is required)"
formatted_parent = completion_service.tenant_path project: project_id, tenant: tenant_id

# language_code = "en-US"
language_codes = [language_code]

# query = "[partially typed job title]"
# page_size: page_size = 5
response = completion_service.complete_query tenant:         formatted_parent,
                                             query:          query,
                                             page_size:      page_size,
                                             language_codes: language_codes

response.completion_results.each do |result|
  puts "Suggested title: #{result.suggestion}"
  # Suggestion type is JOB_TITLE or COMPANY_NAME
  puts "Suggestion type: #{result.type}"
end

C#

Pour en savoir plus sur l'installation et la création d'un client Cloud Talent Solution, consultez la page Bibliothèques clientes Cloud Talent Solution.

public static object CompleteQuery(string projectId, string tenantId, string query)
{
    CompletionClient completionClient = CompletionClient.Create();
    TenantName tenant = TenantName.FromProjectTenant(projectId, tenantId);
    CompleteQueryRequest request = new CompleteQueryRequest
    {
        ParentAsTenantName = tenant,
        Query = query, // partial text for job title
        PageSize = 5, // limit for number of results
        LanguageCodes = { "en-US" } // language code
    };
    var response = completionClient.CompleteQuery(request);
    foreach (var result in response.CompletionResults)
    {
        Console.WriteLine($"Suggested title: {result.Suggestion}");
        // Suggestion type is JOB_TITLE or COMPANY_TITLE
        Console.WriteLine($"Suggestion type: {result.Type}");
    }

    return 0;
}