Histograma

O Cloud Talent Solution permite acessar uma representação de histograma do número de vagas associadas a uma determinada pesquisa. Uma pesquisa de histograma retorna uma contagem de todas as vagas que correspondem a uma consulta específica, dividida pelo SearchMode solicitado. Por exemplo, uma pesquisa de histograma pode retornar o número de vagas por tipo de emprego (período integral, meio período etc.) existentes em Mountain View, CA.

Os histogramas geralmente são executados em paralelo a uma chamada de pesquisa, usando o mesmo JobQuery e o mesmo requestMetadata.

O histograma é definido pelo campo histogramQuery, uma expressão de string única. Para detalhes sobre as funções disponíveis para consultas de histograma, consulte a documentação de histogramQuery.

Como recuperar um histograma

O código de exemplo a seguir retorna resultados de histograma:

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

Para mais informações sobre a instalação e criação de um cliente do Cloud Talent Solution, consulte Bibliotecas de cliente do Cloud Talent Solution.


import com.google.cloud.talent.v4beta1.HistogramQuery;
import com.google.cloud.talent.v4beta1.Job;
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 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 {
    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).iterateAll()) {
        System.out.printf("Job summary: %s\n", responseItem.getJobSummary());
        System.out.printf("Job title snippet: %s\n", responseItem.getJobTitleSnippet());
        Job job = responseItem.getJob();
        System.out.printf("Job name: %s\n", job.getName());
        System.out.printf("Job title: %s\n", job.getTitle());
      }
    }
  }
}

PHP

Para mais informações sobre a instalação e criação de um cliente no Cloud Talent Solution, consulte Bibliotecas de clientes do Cloud Talent Solution.

require __DIR__ . '/vendor/autoload.php';

use Google\Cloud\Talent\V4beta1\JobServiceClient;
use Google\Cloud\Talent\V4beta1\HistogramQuery;
use Google\Cloud\Talent\V4beta1\RequestMetadata;

/**
 * Search Jobs with histogram queries.
 *
 * @param string $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
 */
function sampleSearchJobs($projectId, $tenantId, $query)
{

    $jobServiceClient = new JobServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    // $query = 'count(base_compensation, [bucket(12, 20)])';
    $formattedParent = $jobServiceClient->tenantName($projectId, $tenantId);
    $domain = 'www.example.com';
    $sessionId = 'Hashed session identifier';
    $userId = 'Hashed user identifier';
    $requestMetadata = new RequestMetadata();
    $requestMetadata->setDomain($domain);
    $requestMetadata->setSessionId($sessionId);
    $requestMetadata->setUserId($userId);
    $histogramQueriesElement = new HistogramQuery();
    $histogramQueriesElement->setHistogramQuery($query);
    $histogramQueries = [$histogramQueriesElement];

    try {
        // Iterate through all elements
        $pagedResponse = $jobServiceClient->searchJobs($formattedParent, $requestMetadata, ['customRankingInfo' => $customRankingInfo, 'orderBy' => $orderBy]);
        foreach ($pagedResponse->iterateAllElements() as $responseItem) {
            printf('Job summary: %s'.PHP_EOL, $responseItem->getJobSummary());
            printf('Job title snippet: %s'.PHP_EOL, $responseItem->getJobTitleSnippet());
            $job = $responseItem->getJob();
            printf('Job name: %s'.PHP_EOL, $job->getName());
            printf('Job title: %s'.PHP_EOL, $job->getTitle());
        }
    } finally {
        $jobServiceClient->close();
    }

}

Ruby

Para mais informações sobre a instalação e criação de um cliente no Cloud Talent Solution, consulte Bibliotecas de clientes do Cloud Talent Solution.


# Search Jobs with histogram queries
#
# @param query {String} Histogram query
# More info on histogram facets, constants, and built-in functions:
# https://godoc.org/google.golang.org/genproto/googleapis/cloud/talent/v4beta1#SearchJobsRequest
def sample_search_jobs project_id, tenant_id, query
  # Instantiate a client
  job_client = Google::Cloud::Talent::JobService.new version: :v4beta1

  # project_id = "Your Google Cloud Project ID"
  # tenant_id = "Your Tenant ID (using tenancy is optional)"
  # query = "count(base_compensation, [bucket(12, 20)])"
  formatted_parent = job_client.class.tenant_path(project_id, 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.
  job_client.search_jobs(formatted_parent, request_metadata, histogram_queries: histogram_queries).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
end

C#

Para mais informações sobre a instalação e criação de um cliente no Cloud Talent Solution, consulte Bibliotecas de clientes do 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;
}

Limite de relevância

As solicitações de histograma não usam limite de relevância. Para garantir a consistência das contagens entre pesquisas de histograma e pesquisas de vagas idênticas, é preciso que disableKeywordMatch seja false na pesquisa de vagas.