Quickstart: Search

Cloud Talent Solution allows you to search for any currently active Jobs that you have posted to the Cloud Talent Solution system. Once you are able to make search requests, be sure to implement the Jobs analytics framework and implement client events. This is core to the value of Cloud Talent Solution and directly impacts improved search results.

Get a histogram of the number of Jobs by a certain field

The search API can return a histogram of all relevant Jobs indexed in Cloud Talent Solution that match the filters of the search query. Now that you've gotten the search results, you can get a count of the jobs by different facets. Leverage the histogram API to get the count of jobs by certain facets.

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

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

/*
 * Please include the following imports to run this sample.
 *
 * 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.MatchingJob;
 * import com.google.cloud.talent.v4beta1.TenantName;
 * import com.google.cloud.talent.v4beta1.TenantOrProjectName;
 * import java.util.Arrays;
 * import java.util.List;
 */

/**
 * Search Jobs with histogram queries
 *
 * @param 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
 */
public static void sampleSearchJobs(String projectId, String tenantId, String query) {
  try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
    // projectId = "Your Google Cloud Project ID";
    // tenantId = "Your Tenant ID (using tenancy is optional)";
    // query = "count(base_compensation, [bucket(12, 20)])";
    TenantOrProjectName 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();
    HistogramQuery histogramQueriesElement =
        HistogramQuery.newBuilder().setHistogramQuery(query).build();
    List<HistogramQuery> histogramQueries = Arrays.asList(histogramQueriesElement);
    SearchJobsRequest request =
        SearchJobsRequest.newBuilder()
            .setParent(parent.toString())
            .setRequestMetadata(requestMetadata)
            .addAllHistogramQueries(histogramQueries)
            .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());
    }
  } catch (Exception exception) {
    System.err.println("Failed to create the client due to: " + exception);
  }
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


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

/**
 * 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
 */
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 = 'www.example.com';
  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,
  };

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

PHP

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

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

}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


from google.cloud import talent_v4beta1
import six


def sample_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_v4beta1.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 = client.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
    for response_item in client.search_jobs(
            parent, request_metadata, histogram_queries=histogram_queries):
        print('Job summary: {}'.format(response_item.job_summary))
        print('Job title snippet: {}'.format(response_item.job_title_snippet))
        job = response_item.job
        print('Job name: {}'.format(job.name))
        print('Job title: {}'.format(job.title))


Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


 # 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, custom_ranking_info: custom_ranking_info, order_by: order_by).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

In this case, we're getting the count of all jobs in the system, that are accepted by the filters specified, across the various facets - CATEGORY and CITY.

Use the autocomplete API to get suggested job titles

The complete API suggests job titles or company titles that the job seeker might be interested in based on what they've already typed. Use this to autocomplete potential results in the search bar of your UI.

Go

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

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

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

/*
 * Please include the following imports to run this sample.
 *
 * import com.google.cloud.talent.v4beta1.CompleteQueryRequest;
 * import com.google.cloud.talent.v4beta1.CompleteQueryResponse;
 * import com.google.cloud.talent.v4beta1.CompleteQueryResponse.CompletionResult;
 * import com.google.cloud.talent.v4beta1.CompletionClient;
 * import com.google.cloud.talent.v4beta1.TenantName;
 * import com.google.cloud.talent.v4beta1.TenantOrProjectName;
 * import java.util.Arrays;
 * import java.util.List;
 */

/**
 * Complete job title given partial text (autocomplete)
 *
 * @param projectId Your Google Cloud Project ID
 * @param tenantId Identifier of the Tenantd
 */
public static void sampleCompleteQuery(
    String projectId, String tenantId, String query, int numResults, String languageCode) {
  try (CompletionClient completionClient = CompletionClient.create()) {
    // projectId = "Your Google Cloud Project ID";
    // tenantId = "Your Tenant ID (using tenancy is optional)";
    // query = "[partially typed job title]";
    // numResults = 5;
    // languageCode = "en-US";
    TenantOrProjectName parent = TenantName.of(projectId, tenantId);
    List<String> languageCodes = Arrays.asList(languageCode);
    CompleteQueryRequest request =
        CompleteQueryRequest.newBuilder()
            .setParent(parent.toString())
            .setQuery(query)
            .setPageSize(numResults)
            .addAllLanguageCodes(languageCodes)
            .build();
    CompleteQueryResponse response = completionClient.completeQuery(request);
    for (CompleteQueryResponse.CompletionResult result : response.getCompletionResultsList()) {
      System.out.printf("Suggested title: %s\n", result.getSuggestion());
      // Suggestion type is JOB_TITLE or COMPANY_TITLE
      System.out.printf("Suggestion type: %s\n", result.getType());
    }
  } catch (Exception exception) {
    System.err.println("Failed to create the client due to: " + exception);
  }
}

Node.js

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


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

/**
 * Complete job title given partial text (autocomplete)
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the Tenantd
 */
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);
    });
}

PHP

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.

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

use Google\Cloud\Talent\V4beta1\CompletionClient;

/**
 * Complete job title given partial text (autocomplete).
 *
 * @param string $projectId Your Google Cloud Project ID
 * @param string $tenantId  Identifier of the Tenantd
 */
function sampleCompleteQuery($projectId, $tenantId, $query, $numResults, $languageCode)
{

    $completionClient = new CompletionClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    // $query = '[partially typed job title]';
    // $numResults = 5;
    // $languageCode = 'en-US';
    $formattedParent = $completionClient->tenantName($projectId, $tenantId);
    $languageCodes = [$languageCode];

    try {
        $response = $completionClient->completeQuery($formattedParent, $query, $numResults, ['languageCodes' => $languageCodes]);
        foreach ($response->getCompletionResults() as $result) {
            printf('Suggested title: %s'.PHP_EOL, $result->getSuggestion());
            // Suggestion type is JOB_TITLE or COMPANY_TITLE
            printf('Suggestion type: %s'.PHP_EOL, CompleteQueryRequest_CompletionType::name($result->getType()));
        }
    } finally {
        $completionClient->close();
    }

}

Python

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


from google.cloud import talent_v4beta1
from google.cloud.talent_v4beta1 import enums
import six


def sample_complete_query(project_id, tenant_id, query, num_results,
                          language_code):
    """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]'
    # num_results = 5
    # language_code = 'en-US'

    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')

    if isinstance(language_code, six.binary_type):
        language_code = language_code.decode('utf-8')
    parent = client.tenant_path(project_id, tenant_id)
    language_codes = [language_code]

    response = client.complete_query(parent,
                                     query,
                                     num_results,
                                     language_codes=language_codes)
    for result in response.completion_results:
        print('Suggested title: {}'.format(result.suggestion))
        # Suggestion type is JOB_TITLE or COMPANY_TITLE
        print('Suggestion type: {}'.format(
            enums.CompleteQueryRequest.CompletionType(result.type).name))


Ruby

For more on installing and creating a Cloud Talent Solution client, see Cloud Talent Solution Client Libraries.


 # Complete job title given partial text (autocomplete)
 #
 # @param project_id {String} Your Google Cloud Project ID
 # @param tenant_id {String} Identifier of the Tenantd
def sample_complete_query(project_id, tenant_id, query, num_results, language_code)
  # Instantiate a client
  completion_client = Google::Cloud::Talent::Completion.new version: :v4beta1

  # project_id = "Your Google Cloud Project ID"
  # tenant_id = "Your Tenant ID (using tenancy is optional)"
  # query = "[partially typed job title]"
  # num_results = 5
  # language_code = "en-US"
  formatted_parent = completion_client.class.tenant_path(project_id, tenant_id)
  language_codes = [language_code]

  response = completion_client.complete_query(formatted_parent, query, num_results, language_codes: language_codes)
  response.completion_results.each do |result|
    puts "Suggested title: #{result.suggestion}"
    # Suggestion type is JOB_TITLE or COMPANY_TITLE
    puts "Suggestion type: #{result.type}"
  end

end

Var denne siden nyttig? Si fra hva du synes:

Send tilbakemelding om ...

Job Search documentation