Quickstart: Search (v3)

Cloud Talent Solution allows you to search for jobs you have posted to our system in Google Cloud Talent Solution that are currently active. This tutorial provides a simple search call for the job created in the Creating companies and jobs.

Once you are able to make search requests, be sure to implement the Jobs analytics framework (see Improve pre-trained model. This is core to the value of Cloud Talent Solution and directly impacts improved search results.

Search for the job posting

Search for the job created in the tutorial - Creating companies and jobs. Cloud Talent Solution also uses the RequestMetadata to actively ensure that job seekers get a consistent user experience as they search through jobs. It's imperative to ensure that this field is set correctly. Reference the RequestMetadata documentation.

Java

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


/**
 * Simple search jobs with keyword.
 */
public static void basicSearcJobs(String companyName, String query) throws IOException {
  // Make sure to set the requestMetadata the same as the associated search request
  RequestMetadata requestMetadata =
      new RequestMetadata()
          // Make sure to hash your userID
          .setUserId("HashedUserId")
          // Make sure to hash the sessionID
          .setSessionId("HashedSessionID")
          // Domain of the website where the search is conducted
          .setDomain("www.google.com");

  // Perform a search for analyst  related jobs
  JobQuery jobQuery = new JobQuery().setQuery(query);
  if (companyName != null) {
    jobQuery.setCompanyNames(Arrays.asList(companyName));
  }

  SearchJobsRequest searchJobsRequest =
      new SearchJobsRequest()
          .setRequestMetadata(requestMetadata)
          .setJobQuery(jobQuery) // Set the actual search term as defined in the jobQurey
          .setSearchMode("JOB_SEARCH"); // Set the search mode to a regular search

  SearchJobsResponse searchJobsResponse =
      talentSolutionClient
          .projects()
          .jobs()
          .search(DEFAULT_PROJECT_ID, searchJobsRequest)
          .execute();

  System.out.println(searchJobsResponse);
}

Python

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

def basic_keyword_search(client_service, company_name, keyword):
    request_metadata = {
        'user_id': 'HashedUserId',
        'session_id': 'HashedSessionId',
        'domain': 'www.google.com'
    }
    job_query = {'query': keyword}
    if company_name is not None:
        job_query.update({'company_names': [company_name]})
    request = {
        'search_mode': 'JOB_SEARCH',
        'request_metadata': request_metadata,
        'job_query': job_query,
    }

    response = client_service.projects().jobs().search(
        parent=parent, body=request).execute()
    print(response)

C#

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


public static void BasicSearchJobs(string companyName, string query)
{
    RequestMetadata requestMetadata = new RequestMetadata()
    {
        // Make sure to hash your userID
        UserId = "HashedUserId",
        // Make sure to hash the sessionID
        SessionId = "HashedSessionId",
        // Domain of the website where the search is conducted
        Domain = "www.google.com"
    };

    JobQuery jobQuery = new JobQuery()
    {
        Query = query,
        CompanyNames = new List<string>
        {
            companyName
        }
    };

    SearchJobsRequest searchJobRequest = new SearchJobsRequest()
    {
        RequestMetadata = requestMetadata,
        JobQuery = jobQuery,
        SearchMode = "JOB_SEARCH"
    };

    SearchJobsResponse searchJobsResponse = jobServiceClient.Projects.Jobs.Search(searchJobRequest, parent).Execute();

    Console.WriteLine("Jobs searched: " + ToJsonString(searchJobsResponse));
}

Go

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


// basicJobSearch searches for jobs with query.
func basicJobSearch(w io.Writer, projectID, companyName, query string) (*talent.SearchJobsResponse, error) {
	ctx := context.Background()

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	jobQuery := &talent.JobQuery{
		Query: query,
	}
	if companyName != "" {
		jobQuery.CompanyNames = []string{companyName}
	}

	parent := "projects/" + projectID
	req := &talent.SearchJobsRequest{
		// Make sure to set the requestMetadata the same as the associated
		// search request.
		RequestMetadata: &talent.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",
		},
		// Set the actual search term as defined in the jobQuery
		JobQuery: jobQuery,
		// Set the search mode to a regular search
		SearchMode: "JOB_SEARCH",
	}
	resp, err := service.Projects.Jobs.Search(parent, req).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to search for jobs with query %q: %v", query, err)
	}

	fmt.Fprintln(w, "Jobs:")
	for _, j := range resp.MatchingJobs {
		fmt.Fprintf(w, "\t%q\n", j.Job.Name)
	}

	return resp, nil
}

Node.js

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


/**
 * Simple search jobs with keyword.
 */
const basicKeywordSearch = async (jobServiceClient, companyName, keyword) => {
  try {
    const jobQuery = {
      query: keyword,
    };

    if (companyName) {
      jobQuery.companyNames = [companyName];
    }

    const request = {
      parent: `projects/${PROJECT_ID}`,
      resource: {
        jobQuery: jobQuery,
        requestMetadata: REQUEST_META_DATA,
        searchMode: 'JOB_SEARCH',
      },
    };

    const result = await jobServiceClient.projects.jobs.search(request);

    console.log(JSON.stringify(result.data));
  } catch (e) {
    console.error(e);
    throw e;
  }
};

Ruby

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

# project_id      = "Id of the project"
# company_name    = "The resource name of the company listing the job. The format is "projects/{project_id}/companies/{company_id}""
# query           = "Specify the job criteria to match against. These include location, job categories, employment types, text queries, companies, etc"

require "google/apis/jobs_v3"

# Instantiate the client
jobs = Google::Apis::JobsV3
talent_solution_client = jobs::CloudTalentSolutionService.new
# @see
# https://developers.google.com/identity/protocols/application-default-credentials#callingruby
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)
# Make sure to set the request_metadata the same as the associated search request
request_metadata = jobs::RequestMetadata.new user_id:    "HashedUserId",
                                             session_id: "HashedSessionId",
                                             domain:     "www.google.com"

# Perform a search for analyst  related jobs
job_query = jobs::JobQuery.new query: query
job_query.company_names = [company_name] unless company_name.nil?
search_jobs_request = jobs::SearchJobsRequest.new request_metadata: request_metadata,
                                                  job_query:        job_query,
                                                  search_mode:      "JOB_SEARCH"
search_jobs_response = talent_solution_client.search_jobs project_id, search_jobs_request
puts search_jobs_response.to_json
search_jobs_response

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

The search API also returns 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.

Java

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


/**
 * Histogram search
 */
public static void histogramSearch(String companyName) throws IOException {
  // Make sure to set the requestMetadata the same as the associated search request
  RequestMetadata requestMetadata =
      new RequestMetadata()
          // Make sure to hash your userID
          .setUserId("HashedUserId")
          // Make sure to hash the sessionID
          .setSessionId("HashedSessionID")
          // Domain of the website where the search is conducted
          .setDomain(
              "www.google.com");

  HistogramFacets histogramFacets =
      new HistogramFacets()
          .setSimpleHistogramFacets(Arrays.asList("COMPANY_ID"))
          .setCustomAttributeHistogramFacets(
              Arrays.asList(
                  new CustomAttributeHistogramRequest()
                      .setKey("someFieldName1")
                      .setStringValueHistogram(true)));

  // conducted.
  SearchJobsRequest searchJobsRequest =
      new SearchJobsRequest()
          .setRequestMetadata(requestMetadata)
          .setSearchMode("JOB_SEARCH")
          .setHistogramFacets(histogramFacets);
  if (companyName != null) {
    searchJobsRequest.setJobQuery(new JobQuery().setCompanyNames(Arrays.asList(companyName)));
  }

  SearchJobsResponse searchJobsResponse =
      talentSolutionClient
          .projects()
          .jobs()
          .search(DEFAULT_PROJECT_ID, searchJobsRequest)
          .execute();

  System.out.println(searchJobsResponse);
}

Python

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

def histogram_search(client_service, company_name):
    request_metadata = {
        'user_id': 'HashedUserId',
        'session_id': 'HashedSessionId',
        'domain': 'www.google.com'
    }
    custom_attribute_histogram_facet = {
        'key': 'someFieldName1',
        'string_value_histogram': True
    }
    histogram_facets = {
        'simple_histogram_facets': ['COMPANY_ID'],
        'custom_attribute_histogram_facets': [custom_attribute_histogram_facet]
    }
    request = {
        'search_mode': 'JOB_SEARCH',
        'request_metadata': request_metadata,
        'histogram_facets': histogram_facets
    }
    if company_name is not None:
        request.update({'job_query': {'company_names': [company_name]}})
    response = client_service.projects().jobs().search(
        parent=parent, body=request).execute()
    print(response)

C#

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


public static void HistogramSearch(String companyName)
{
    RequestMetadata requestMetadata = new RequestMetadata()
    {
        // Make sure to hash your userID
        UserId = "HashedUserId",
        // Make sure to hash the sessionID
        SessionId = "HashedSessionId",
        // Domain of the website where the search is conducted
        Domain = "www.google.com"
    };

    HistogramFacets histogramFacets = new HistogramFacets()
    {
        SimpleHistogramFacets = new List<String>
        {
            "COMPANY_ID"
        },
        CustomAttributeHistogramFacets = new List<CustomAttributeHistogramRequest>
        {
            new CustomAttributeHistogramRequest()
            {
                Key = "someFieldName1",
                StringValueHistogram = true
            }
        }
    };

    SearchJobsRequest searchJobsRequest = new SearchJobsRequest()
    {
        RequestMetadata = requestMetadata,
        SearchMode = "JOB_SEARCH",
        HistogramFacets = histogramFacets
    };

    if (companyName != null)
    {
        searchJobsRequest.JobQuery = new JobQuery()
        {
            CompanyNames = new List<string>
            {
                companyName
            }
        };
    }

    SearchJobsResponse searchJobsResponse = jobServiceClient.Projects.Jobs.Search(searchJobsRequest, parent).Execute();
    Console.WriteLine("Histogram search: " + ToJsonString(searchJobsResponse));
}

Go

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


// histogramSearch searches for jobs with histogram facets.
func histogramSearch(w io.Writer, projectID, companyName string) (*talent.SearchJobsResponse, error) {
	ctx := context.Background()

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	parent := "projects/" + projectID
	req := &talent.SearchJobsRequest{
		// Make sure to set the RequestMetadata the same as the associated
		// search request.
		RequestMetadata: &talent.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",
		},
		HistogramFacets: &talent.HistogramFacets{
			SimpleHistogramFacets: []string{"COMPANY_ID"},
			CustomAttributeHistogramFacets: []*talent.CustomAttributeHistogramRequest{
				{
					Key:                  "someFieldString",
					StringValueHistogram: true,
				},
			},
		},
		// Set the search mode to a regular search.
		SearchMode:               "JOB_SEARCH",
		RequirePreciseResultSize: true,
	}
	if companyName != "" {
		req.JobQuery = &talent.JobQuery{
			CompanyNames: []string{companyName},
		}
	}

	resp, err := service.Projects.Jobs.Search(parent, req).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to search for jobs with Historgram Facets: %v", err)
	}

	fmt.Fprintln(w, "Jobs:")
	for _, j := range resp.MatchingJobs {
		fmt.Fprintf(w, "\t%q\n", j.Job.Name)
	}

	return resp, nil
}

Node.js

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


/**
 * Histogram search
 */
const histogramSearch = async (jobServiceClient, companyName) => {
  try {
    const requestMetadata = {
      userId: 'HashedUserId',
      sessionId: 'HashedSessionId',
      domain: 'www.google.com',
    };

    const customAttributeHistogramFacet = {
      key: `someFieldName1`,
      stringValueHistogram: true,
    };

    const histogramFacets = {
      simpleHistogramFacets: ['COMPANY_ID'],
      customAttributeHistogramFacets: [customAttributeHistogramFacet],
    };

    const request = {
      parent: `projects/${PROJECT_ID}`,
      resource: {
        searchMode: 'JOB_SEARCH',
        requestMetadata: requestMetadata,
        histogramFacets: histogramFacets,
      },
    };

    if (companyName) {
      request.resource.jobQuery = {companyNames: [companyName]};
    }

    const result = await jobServiceClient.projects.jobs.search(request);

    console.log(JSON.stringify(result.data));
  } catch (e) {
    console.error(e);
    throw e;
  }
};

Ruby

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

  # project_id     = "Id of the project"
  # company_name   = "The resource name of the company listing the job. The format is "projects/{project_id}/companies/{company_id}""
  require "google/apis/jobs_v3"

  # Instantiate the client
  jobs = Google::Apis::JobsV3
  talent_solution_client = jobs::CloudTalentSolutionService.new
  # @see
  # https://developers.google.com/identity/protocols/application-default-credentials#callingruby
  talent_solution_client.authorization = Google::Auth.get_application_default(
    "https://www.googleapis.com/auth/jobs"
  )

  # Make sure to set the request_metadata the same as the associated search request
  request_metadata = jobs::RequestMetadata.new user_id:    "HashedUserId",
                                               session_id: "HashedSessionId",
                                               domain:     "http://careers.google.com"

  custom_attribute_histogram_request =
    jobs::CustomAttributeHistogramRequest.new key:                    "someFieldName1",
                                              string_value_histogram: true
  histogram_facets =
    jobs::HistogramFacets.new simple_histogram_facets:           ["COMPANY_ID"],
                              custom_attribute_histogram_facets: [custom_attribute_histogram_request]
  # Perform a search for analyst  related jobs
  job_query = jobs::JobQuery.new company_names: [company_name]

  search_jobs_request = jobs::SearchJobsRequest.new request_metadata: request_metadata,
                                                    job_query:        job_query,
                                                    histogram_facets: histogram_facets
  search_jobs_response = talent_solution_client.search_jobs project_id, search_jobs_request

  puts search_jobs_response.to_json
  search_jobs_response
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.

Java

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


  /**
   * Auto completes job titles within given companyName.
   */
  public static void jobTitleAutoComplete(String companyName, String query)
      throws IOException {

    Complete complete =
        talentSolutionClient
            .projects()
            .complete(DEFAULT_PROJECT_ID)
            .setQuery(query)
            .setLanguageCode("en-US")
            .setType("JOB_TITLE")
            .setPageSize(10);
    if (companyName != null) {
      complete.setCompanyName(companyName);
    }

    CompleteQueryResponse results = complete.execute();

    System.out.println(results);
  }

  /**
   * Auto completes job titles within given companyName.
   */
  public static void defaultAutoComplete(String companyName, String query)
      throws IOException {
    Complete complete =
        talentSolutionClient
            .projects()
            .complete(DEFAULT_PROJECT_ID)
            .setQuery(query)
            .setLanguageCode("en-US")
            .setPageSize(10);
    if (companyName != null) {
      complete.setCompanyName(companyName);
    }

    CompleteQueryResponse results = complete.execute();

    System.out.println(results);
  }

  public static void main(String... args) throws Exception {
    Company companyToBeCreated = BasicCompanySample.generateCompany().setDisplayName("Google");
    String companyName = BasicCompanySample.createCompany(companyToBeCreated).getName();

    Job jobToBeCreated = BasicJobSample.generateJobWithRequiredFields(companyName)
        .setTitle("Software engineer");
    final String jobName = BasicJobSample.createJob(jobToBeCreated).getName();

    // Wait several seconds for post processing
    Thread.sleep(10000);
    defaultAutoComplete(companyName, "goo");
    defaultAutoComplete(companyName, "sof");
    jobTitleAutoComplete(companyName, "sof");

    BasicJobSample.deleteJob(jobName);
    BasicCompanySample.deleteCompany(companyName);
  }
}

Python

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

def job_title_auto_complete(client_service, query, company_name):
    complete = client_service.projects().complete(
        name=name, query=query,
        languageCode='en-US', type='JOB_TITLE', pageSize=10)
    if company_name is not None:
        complete.companyName = company_name

    results = complete.execute()
    print(results)

C#

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


public static void JobTitleAutoComplete(String companyName, String query)
{
    CompleteRequest completeRequest = new CompleteRequest(jobServiceClient, parent)
    {
        Query = query,
        LanguageCode = "en-US",
        Type = CompleteRequest.TypeEnum.JOBTITLE,
        PageSize = 10
    };

    if (companyName != null)
    {
        completeRequest.CompanyName = companyName;
    }

    CompleteQueryResponse results = completeRequest.Execute();
    Console.WriteLine("Completion results: " + ToJsonString(results));
}

Go

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


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

	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		return nil, fmt.Errorf("google.DefaultClient: %v", err)
	}
	// Create the jobs service client.
	service, err := talent.New(client)
	if err != nil {
		return nil, fmt.Errorf("talent.New: %v", err)
	}

	parent := "projects/" + projectID
	complete := service.Projects.Complete(parent).Query(query).LanguageCode("en-US").Type("JOB_TITLE").PageSize(10)
	if companyName != "" {
		complete.CompanyName(companyName)
	}
	resp, err := complete.Do()
	if err != nil {
		return nil, fmt.Errorf("failed to auto complete with query %s in company %s: %v", query, companyName, err)
	}

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

	return resp, nil
}

Node.js

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


/**
 * Auto completes job titles within given companyName.
 */
const jobTitleAutoComplete = async (jobServiceClient, query, companyName) => {
  try {
    const request = {
      name: `projects/${PROJECT_ID}`,
      query: query,
      languageCode: 'en-US',
      type: 'JOB_TITLE',
      pageSize: 10,
    };

    if (companyName) {
      request.companyName = companyName;
    }

    const complete = await jobServiceClient.projects.complete(request);

    console.log(JSON.stringify(complete.data));
  } catch (e) {
    console.error(e);
    throw e;
  }
};

Ruby

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

# project_id     = "Project id required"
# company_name   = "The resource name of the company listing the job. The format is "projects/{project_id}/companies/{company_id}""
# query          = "Job title prefix as auto complete query"

require "google/apis/jobs_v3"

jobs = Google::Apis::JobsV3
talent_solution_client = jobs::CloudTalentSolutionService.new
talent_solution_client.authorization = Google::Auth.get_application_default(
  "https://www.googleapis.com/auth/jobs"
)

page_size = 10
type = "JOB_TITLE"
language_code = "en-US"
result = talent_solution_client.complete_project(
  project_id, company_name: company_name, page_size: page_size, query: query,
    language_code: language_code, type: type
) do |result, err|
  if err.nil?
    puts "Job title auto complete result: #{result.to_json}"
  else
    puts "Error when auto completing job title. Error message: #{err.to_json}"
  end
end
result

Set up the jobs analytics framework to tune Cloud Talent Solution with client events

You're now ready to optimize search results to your site (see Improve search results using client events). This is a critical step in improving results for job seekers by optimizing search results.