在 Talent Solution 中创建公司和招聘信息

本教程旨在引导您利用 Cloud Talent Solution 探索和开发应用。它假设您熟悉基本编程;但即使没有太多的编程知识,您也应该能够按照说明操作。完成本教程后,您应该能够借助 Cloud Talent Solution 参考文档创建自己的基本应用。

本教程介绍使用 Java 代码的 Cloud Talent Solution 应用。但我们的目的不是解释 Java 客户端库,而是说明如何调用 Cloud Talent Solution。Python 和 Node.js 版应用基本相似。如有任何疑问,请联系我们

准备工作

您已完成以下操作:

创建一个公司及其职位,并搜索这些职位

本教程将为您介绍基本的 Cloud Talent Solution 应用,并引导您创建一个关联到公司的职位。下一个教程将为您介绍基于职位属性和搜索查询来搜索公司内职位的步骤。search API 会尝试根据职位内的可用字段(公司名称、职务、职位描述、职位类别、工作地点等),返回与求职者查询最相关的职位。

使用您的凭据创建服务

使用您在准备工作中下载的 JSON 凭据文件创建服务:

Java

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


private static final JsonFactory JSON_FACTORY = new GsonFactory();
private static final NetHttpTransport NET_HTTP_TRANSPORT = new NetHttpTransport();
private static final String DEFAULT_PROJECT_ID =
    "projects/" + System.getenv("GOOGLE_CLOUD_PROJECT");

private static CloudTalentSolution talentSolutionClient =
    createTalentSolutionClient(generateCredential());

private static CloudTalentSolution createTalentSolutionClient(GoogleCredentials credential) {
  String url = "https://jobs.googleapis.com";

  HttpRequestInitializer requestInitializer =
      request -> {
        new HttpCredentialsAdapter(credential).initialize(request);
        request.setConnectTimeout(60000); // 1 minute connect timeout
        request.setReadTimeout(60000); // 1 minute read timeout
      };

  return new CloudTalentSolution.Builder(NET_HTTP_TRANSPORT, JSON_FACTORY, requestInitializer)
      .setApplicationName("JobServiceClientSamples")
      .setRootUrl(url)
      .build();
}

private static GoogleCredentials generateCredential() {
  try {
    // Credentials could be downloaded after creating service account
    // set the `GOOGLE_APPLICATION_CREDENTIALS` environment variable, for example:
    // export GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/key.json
    return GoogleCredentials.getApplicationDefault()
        .createScoped(Collections.singleton(CloudTalentSolutionScopes.JOBS));
  } catch (Exception e) {
    System.out.println("Error in generating credential");
    throw new RuntimeException(e);
  }
}

public static CloudTalentSolution getTalentSolutionClient() {
  return talentSolutionClient;
}

public static void main(String... args) throws Exception {
  try {
    ListCompaniesResponse listCompaniesResponse =
        talentSolutionClient.projects().companies().list(DEFAULT_PROJECT_ID).execute();
    System.out.println("Request Id is " + listCompaniesResponse.getMetadata().getRequestId());
    if (listCompaniesResponse.getCompanies() != null) {
      for (Company company : listCompaniesResponse.getCompanies()) {
        System.out.println(company.getName());
      }
    }
  } catch (IOException e) {
    System.out.println("Got exception while listing companies");
    throw e;
  }
}

Python

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

import os

from googleapiclient.discovery import build
from googleapiclient.errors import Error

client_service = build("jobs", "v3")

def run_sample():
    try:
        project_id = "projects/" + os.environ["GOOGLE_CLOUD_PROJECT"]
        response = (
            client_service.projects().companies().list(parent=project_id).execute()
        )
        print("Request Id: %s" % response.get("metadata").get("requestId"))
        print("Companies:")
        if response.get("companies") is not None:
            for company in response.get("companies"):
                print("%s" % company.get("name"))
        print("")

    except Error as e:
        print("Got exception while listing companies")
        raise e

if __name__ == "__main__":
    run_sample()

Go

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


// Command quickstart is an example of using the Google Cloud Talent Solution API.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"golang.org/x/oauth2/google"
	talent "google.golang.org/api/jobs/v3"
)

func main() {
	projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
	parent := fmt.Sprintf("projects/%s", projectID)

	// Authorize the client using Application Default Credentials.
	// See https://g.co/dv/identity/protocols/application-default-credentials
	ctx := context.Background()
	client, err := google.DefaultClient(ctx, talent.CloudPlatformScope)
	if err != nil {
		log.Fatal(err)
	}

	// Create the jobs service client.
	ctsService, err := talent.New(client)
	if err != nil {
		log.Fatal(err)
	}

	// Make the RPC call.
	response, err := ctsService.Projects.Companies.List(parent).Do()
	if err != nil {
		log.Fatalf("Failed to list Companies: %v", err)
	}

	// Print the request id.
	fmt.Printf("Request ID: %q\n", response.Metadata.RequestId)

	// Print the returned companies.
	for _, company := range response.Companies {
		fmt.Printf("Company: %q\n", company.Name)
	}
}

此代码使用您应用的凭据信息配置客户端服务。进行 API 调用时,系统会发送 OAuth 2.0 请求。上述过程中生成的身份验证令牌的有效期通常为 1 小时;如果您在超出该时间后尝试使用它,系统会报错。 GoogleCredential 库负责自动“刷新”令牌,即获得新的访问令牌。

创建公司

公司是与一组职位列表关联的实体。您必须先创建公司,才能在 Cloud Talent Solution 上为该公司发布职位。 创建公司时,您可以将任何自由格式的字符串作为 externalId 发送。这意味着您在创建和引用公司时,可以使用现有数据库(如果有)中的主键。

Java

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


/** Create a company. */
public static Company createCompany(Company companyToBeCreated) throws IOException {
  try {
    CreateCompanyRequest createCompanyRequest =
        new CreateCompanyRequest().setCompany(companyToBeCreated);
    Company companyCreated =
        talentSolutionClient
            .projects()
            .companies()
            .create(DEFAULT_PROJECT_ID, createCompanyRequest)
            .execute();
    System.out.println("Company created: " + companyCreated);
    return companyCreated;
  } catch (IOException e) {
    System.out.println("Got exception while creating company");
    throw e;
  }
}

Python

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

def create_company(client_service, company_to_be_created):
    try:
        request = {"company": company_to_be_created}
        company_created = (
            client_service.projects()
            .companies()
            .create(parent=parent, body=request)
            .execute()
        )
        print("Company created: %s" % company_created)
        return company_created
    except Error as e:
        print("Got exception while creating company")
        raise e

Go

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


// createCompany creates a company as given.
func createCompany(w io.Writer, projectID string, companyToCreate *talent.Company) (*talent.Company, error) {
	ctx := context.Background()

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

	parent := "projects/" + projectID
	req := &talent.CreateCompanyRequest{
		Company: companyToCreate,
	}
	company, err := service.Projects.Companies.Create(parent, req).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to create company %q: %w", companyToCreate.DisplayName, err)
	}

	return company, nil
}

获取公司

您可以发送 GET 请求以及我们后端分配的公司 name,以读取公司当前的状态。

Java

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


/** Get a company. */
public static Company getCompany(String companyName) throws IOException {
  try {
    Company companyExisted =
        talentSolutionClient.projects().companies().get(companyName).execute();
    System.out.println("Company existed: " + companyExisted);
    return companyExisted;
  } catch (IOException e) {
    System.out.println("Got exception while getting company");
    throw e;
  }
}

Python

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

def get_company(client_service, company_name):
    try:
        company_existed = (
            client_service.projects().companies().get(name=company_name).execute()
        )
        print("Company existed: %s" % company_existed)
        return company_existed
    except Error as e:
        print("Got exception while getting company")
        raise e

Go

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


// getCompany gets an existing company by name.
func getCompany(w io.Writer, name string) (*talent.Company, error) {
	ctx := context.Background()

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

	company, err := service.Projects.Companies.Get(name).Do()
	if err != nil {
		return nil, fmt.Errorf("failed to get company %q: %w", name, err)
	}

	fmt.Fprintf(w, "Company: %q\n", company.Name)

	return company, nil
}

创建作业

要发布新职位,您必须填写与新职位相关的所有必填字段,以及您要将此职位关联到的公司的 companyName(您在创建公司资源时指定)。

填妥职位数据的数据对象通过 POST 请求发送到 Cloud Talent Solution 端点。请注意,不应在初始请求中设置 name 字段,因为它是 createJob API 的“仅限输出”字段,并且在服务器创建新的职位实体时,它是 API 响应的一部分。与职位资源交互的 API 端点在 Cloud Talent Solution 客户端库文档中指定。

对请求的响应是新职位信息帖的对象;它应该包含唯一代表该信息帖的职位 name。需要更新或删除信息帖时会用到职位 name。最佳做法是,保存此 name 并将其与您自己对该职位的唯一 ID 对应。

如果系统上已存在同一公司的 companyNamerequisitionIdlanguageCode 相同的其他职位,则当您尝试插入职位时,服务器会返回错误。

以下代码仅使用必需字段为 companyName 字段中指定的公司创建职位。

Java

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


/** Create a job. */
public static Job createJob(Job jobToBeCreated) throws IOException {
  try {
    CreateJobRequest createJobRequest = new CreateJobRequest().setJob(jobToBeCreated);

    Job jobCreated =
        talentSolutionClient
            .projects()
            .jobs()
            .create(DEFAULT_PROJECT_ID, createJobRequest)
            .execute();
    System.out.println("Job created: " + jobCreated);
    return jobCreated;
  } catch (IOException e) {
    System.out.println("Got exception while creating job");
    throw e;
  }
}

Python

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

def create_job(client_service, job_to_be_created):
    try:
        request = {"job": job_to_be_created}
        job_created = (
            client_service.projects()
            .jobs()
            .create(parent=parent, body=request)
            .execute()
        )
        print("Job created: %s" % job_created)
        return job_created
    except Error as e:
        print("Got exception while creating job")
        raise e

Go

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


// createJob create a job as given.
func createJob(w io.Writer, projectID string, jobToCreate *talent.Job) (*talent.Job, error) {
	ctx := context.Background()

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

	parent := "projects/" + projectID
	req := &talent.CreateJobRequest{
		Job: jobToCreate,
	}
	job, err := service.Projects.Jobs.Create(parent, req).Do()
	if err != nil {
		return nil, fmt.Errorf("Failed to create job %q, Err: %w", jobToCreate.RequisitionId, err)
	}
	return job, err
}

通过 Cloud Talent Solution,您还可以创建特定于某个位置的职位。如需了解详情,请参阅 locations

Cloud Talent Solution 有几个与职位相关的字段内置于 API 架构中。但是,您仍然可能碰到一些不是开箱即用的字段。虽然建议 Cloud Talent Solution 的所有客户始终尽可能使用开箱即用的字段,但 Cloud Talent Solution 还是为职位提供了一些 customAttributes。这些属性可能可以过滤,也可能不可过滤。如需了解详情,请参阅 customAttributes

以下代码示例显示了如何使用 customAttribute 创建职位:

Java

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


/** Generate a job with a custom attribute. */
@SuppressWarnings("checkstyle:AbbreviationAsWordInName")
public static Job generateJobWithACustomAttribute(String companyName) {
  // requisition id should be a unique Id in your system.
  String requisitionId = "jobWithACustomAttribute:" + String.valueOf(new Random().nextLong());
  ApplicationInfo applicationInfo =
      new ApplicationInfo().setUris(Arrays.asList("http://careers.google.com"));

  // Constructs custom attributes map
  Map<String, CustomAttribute> customAttributes = new HashMap<>();
  customAttributes.put(
      "someFieldName1",
      new CustomAttribute().setStringValues(Arrays.asList("value1")).setFilterable(Boolean.TRUE));
  customAttributes.put(
      "someFieldName2",
      new CustomAttribute().setLongValues(Arrays.asList(256L)).setFilterable(true));

  // Creates job with custom attributes
  Job job =
      new Job()
          .setCompanyName(companyName)
          .setRequisitionId(requisitionId)
          .setTitle("Software Engineer")
          .setApplicationInfo(applicationInfo)
          .setDescription("Design, develop, test, deploy, maintain and improve software.")
          .setCustomAttributes(customAttributes);
  System.out.println("Job generated: " + job);
  return job;
}

Python

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

def generate_job_with_custom_attributes(company_name):
    # Requisition id should be a unique Id in your system.
    requisition_id = "job_with_custom_attributes:" + "".join(
        random.choice(string.ascii_uppercase + string.digits) for _ in range(16)
    )

    job_title = "Software Engineer"
    application_urls = ["http://careers.google.com"]
    description = "Design, develop, test, deploy, maintain and improve " "software."

    custom_attributes = {
        "someFieldName1": {"string_values": ["value1"], "filterable": True},
        "someFieldName2": {"long_values": [256], "filterable": True},
    }

    job = {
        "company_name": company_name,
        "requisition_id": requisition_id,
        "title": job_title,
        "application_info": {"uris": application_urls},
        "description": description,
        "custom_attributes": custom_attributes,
    }
    print("Job generated: %s" % job)
    return job

Go

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


// constructJobWithCustomAttributes constructs a job with custom attributes.
func constructJobWithCustomAttributes(companyName string, jobTitle string) *talent.Job {
	// requisitionID shoud be the unique ID in your system
	requisitionID := fmt.Sprintf("job-with-custom-attribute-%d", time.Now().UnixNano())

	job := &talent.Job{
		RequisitionId: requisitionID,
		Title:         jobTitle,
		CompanyName:   companyName,
		ApplicationInfo: &talent.ApplicationInfo{
			Uris: []string{"https://googlesample.com/career"},
		},
		Description: "Design, devolop, test, deploy, maintain and improve software.",
		CustomAttributes: map[string]talent.CustomAttribute{
			"someFieldString": {
				Filterable:   true,
				StringValues: []string{"someStrVal"},
			},
			"someFieldLong": {
				Filterable: true,
				LongValues: []int64{900},
			},
		},
	}
	return job
}

检索职位

您可以通过 GET 操作获取职位的详细信息,以确认职位是否已创建。请注意,根据 Cloud Talent Solution 中当前创建的职位数量,职位可能需要数分钟才能变为可用。

您可以向 Cloud Talent Solution 发送 GET 请求,以检索先前插入的职位的详细信息。URI 应包括先前插入的、原始创建请求以网址参数形式返回的职位 name

以下示例通过 GET 操作检索具有给定 name 的职位的详细信息:

Java

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


/** Get a job. */
public static Job getJob(String jobName) throws IOException {
  try {
    Job jobExisted = talentSolutionClient.projects().jobs().get(jobName).execute();
    System.out.println("Job existed: " + jobExisted);
    return jobExisted;
  } catch (IOException e) {
    System.out.println("Got exception while getting job");
    throw e;
  }
}

Python

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

def get_job(client_service, job_name):
    try:
        job_existed = client_service.projects().jobs().get(name=job_name).execute()
        print("Job existed: %s" % job_existed)
        return job_existed
    except Error as e:
        print("Got exception while getting job")
        raise e

Go

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


// getJob gets a job by name.
func getJob(w io.Writer, jobName string) (*talent.Job, error) {
	ctx := context.Background()

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

	job, err := service.Projects.Jobs.Get(jobName).Do()
	if err != nil {
		return nil, fmt.Errorf("Failed to get job %s: %w", jobName, err)
	}

	fmt.Fprintf(w, "Job: %q", job.Name)

	return job, err
}

搜索职位

您已经使用 Cloud Talent Solution 创建了第一家公司和第一个职位!现在,您可以搜索这些职位。

后续步骤