Se usó la API de Cloud Translation para traducir esta página.
Switch to English

Buscar trabajos con una consulta de histograma (v4beta1)

Busca trabajos con una consulta de histograma.

Páginas de documentación que incluyen esta muestra de código

Para ver la muestra de código usada en contexto, consulta la siguiente documentación:

Muestra de código

Comienza a usarlo

import (

	talent ""
	talentpb ""

// 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 {
		return fmt.Errorf("talent.NewJobClient: %v", 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: "",
		HistogramQueries: []*talentpb.HistogramQuery{
				// More info on histogram facets, constants, and built-in functions:
				HistogramQuery: "count(base_compensation, [bucket(12, 20)])",
	if companyID != "" {
		req.JobQuery = &talentpb.JobQuery{
			Companies: []string{fmt.Sprintf("projects/%s/companies/%s", projectID, companyID)},

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

	for _, job := range resp.GetMatchingJobs() {
		fmt.Fprintf(w, "Job: %q\n", job.GetJob().GetName())

	return nil



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 = "";
      String sessionId = "Hashed session identifier";
      String userId = "Hashed user identifier";
      RequestMetadata requestMetadata =
      HistogramQuery histogramQueriesElement =
      SearchJobsRequest request =

      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());


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

 * Search Jobs with histogram queries
 * @param query {string} Histogram query
 * More info on histogram facets, constants, and built-in functions:
function sampleSearchJobs(projectId, tenantId, query) {
  const client = new talent.JobServiceClient();
  // Iterate over all elements.
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const query = 'count(base_compensation, [bucket(12, 20)])';
  const formattedParent = client.tenantPath(projectId, tenantId);
  const domain = '';
  const sessionId = 'Hashed session identifier';
  const userId = 'Hashed user identifier';
  const requestMetadata = {
    domain: domain,
    sessionId: sessionId,
    userId: userId,
  const histogramQueriesElement = {
    histogramQuery: query,
  const histogramQueries = [histogramQueriesElement];
  const request = {
    parent: formattedParent,
    requestMetadata: requestMetadata,
    histogramQueries: histogramQueries,

    .then(responses => {
      const resources = responses[0];
      for (const resource of resources.matchingJobs) {
        console.log(`Job summary: ${resource.jobSummary}`);
        console.log(`Job title snippet: ${resource.jobTitleSnippet}`);
        const job = resource.job;
        console.log(`Job name: ${}`);
        console.log(`Job title: ${job.title}`);
    .catch(err => {


from import talent
import six

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

      query Histogram query
      More info on histogram facets, constants, and built-in functions:

    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 = ""
    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(
    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
        print("Job name: {}")
        print("Job title: {job.title}")
    return results


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 = ""
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: #{}"
  puts "Job title: #{job.title}"

¿Qué sigue?

A fin de buscar y filtrar muestras de código para otros productos de Google Cloud, consulta el navegador de muestra de Google Cloud.