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. Video tutorials and interactive codelabs are also available.

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.


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 {
    // 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).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

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


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

Ruby

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

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 optional)"
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#

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

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

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.


import com.google.cloud.talent.v4beta1.CompleteQueryRequest;
import com.google.cloud.talent.v4beta1.CompleteQueryResponse;
import com.google.cloud.talent.v4beta1.CompletionClient;
import com.google.cloud.talent.v4beta1.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()
              .setParent(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());
      }
    }
  }
}

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 import enums
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 = client.tenant_path(project_id, tenant_id)

    response = client.complete_query(
        parent,
        query,
        page_size=5,  # limit for number of results
        language_codes=["en-US"],  # language code
    )
    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.

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 optional)"
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 parent:         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_TITLE
  puts "Suggestion type: #{result.type}"
end

C#

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

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