快速入门:搜索 (v4beta1)

利用 Cloud Talent Solution,您可以搜索已发布到 Cloud Talent Solution 系统的任何当前有效的职位。如果您能够发出搜索请求,请务必实施招聘信息分析框架并实施客户端事件。这是 Cloud Talent Solution 价值的核心,并直接影响改进的搜索结果。 此外,还有视频教程和交互式 Codelab 可供使用

获取按特定字段统计的招聘信息数直方图

搜索 API 可以返回在 Cloud Talent Solution 中编制索引的、与搜索查询过滤条件匹配的所有相关招聘信息的直方图。现在您已经获得搜索结果,可以按不同属性统计招聘信息计数。 利用直方图 API 获取按特定属性统计的招聘信息计数。

Go

如需了解如何安装和使用适用于 CTS 的客户端库,请参阅 CTS 客户端库。 如需了解详情,请参阅 CTS Go API 参考文档

如需向 CTS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证

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

如需详细了解如何安装和创建 Cloud Talent Solution 客户端,请参阅 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 {
    // 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

如需详细了解如何安装和创建 Cloud Talent Solution 客户端,请参阅 Cloud Talent Solution 客户端库


from google.cloud import talent

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, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(query, bytes):
        query = query.decode("utf-8")
    parent = f"projects/{project_id}/tenants/{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 = []
    request = talent.SearchJobsRequest(
        parent=parent,
        request_metadata=request_metadata,
        histogram_queries=histogram_queries,
    )
    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
        results.append(job)
        print("Job name: {job.name}")
        print("Job title: {job.title}")
    return results

这种情况下,我们将获得系统中指定过滤器中接受的、涵盖各种属性(类别和城市)的所有招聘信息的计数。

使用自动填充 API 获取建议的职务

完整的 API 会根据求职者已经输入的内容,建议他们可能感兴趣的职务或公司名称。使用此选项可在界面的搜索栏中自动填充可能的结果。

Go

如需详细了解如何安装和创建 Cloud Talent Solution 客户端,请参阅 Cloud Talent Solution 客户端库

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"cloud.google.com/go/talent/apiv4beta1/talentpb"
)

// 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: %w", err)
	}
	defer c.Close()

	// 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): %w", 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

如需详细了解如何安装和创建 Cloud Talent Solution 客户端,请参阅 Cloud Talent Solution 客户端库


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

如需详细了解如何安装和创建 Cloud Talent Solution 客户端,请参阅 Cloud Talent Solution 客户端库


from google.cloud import talent_v4beta1

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, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(query, bytes):
        query = query.decode("utf-8")

    parent = f"projects/{project_id}/tenants/{tenant_id}"

    request = talent_v4beta1.CompleteQueryRequest(
        parent=parent,
        query=query,
        page_size=5,  # limit for number of results
        language_codes=["en-US"],  # language code
    )
    response = client.complete_query(request=request)
    for result in response.completion_results:
        print(f"Suggested title: {result.suggestion}")
        # Suggestion type is JOB_TITLE or COMPANY_TITLE
        print(
            f"Suggestion type: {talent_v4beta1.CompleteQueryRequest.CompletionType(result.type_).name}"
        )