快速入门:创建公司和职位

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

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

前提条件

您已完成以下操作:

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

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

创建公司

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

Go

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
)

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

	// Initializes a companyService client.
	c, err := talent.NewCompanyClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("talent.NewCompanyClient: %v", err)
	}

	// Construct a createCompany request.
	req := &talentpb.CreateCompanyRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		Company: &talentpb.Company{
			ExternalId:  externalID,
			DisplayName: displayName,
		},
	}

	resp, err := c.CreateCompany(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateCompany: %v", err)
	}

	fmt.Fprintf(w, "Created company: %q\n", resp.GetName())

	return resp, nil
}

Java

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

/*
 * Please include the following imports to run this sample.
 *
 * import com.google.cloud.talent.v4beta1.Company;
 * import com.google.cloud.talent.v4beta1.CompanyServiceClient;
 * import com.google.cloud.talent.v4beta1.CreateCompanyRequest;
 * import com.google.cloud.talent.v4beta1.TenantName;
 * import com.google.cloud.talent.v4beta1.TenantOrProjectName;
 */
public class JobSearchCreateCompany {
  /**
   * Create Company
   *
   * @param projectId Your Google Cloud Project ID
   * @param tenantId Identifier of the Tenant
   */
  public static void sampleCreateCompany(
      String projectId, String tenantId, String displayName, String externalId) {
    try (CompanyServiceClient companyServiceClient = CompanyServiceClient.create()) {
      // String projectId = "Your Google Cloud Project ID";
      // String tenantId = "Your Tenant ID (using tenancy is optional)";
      // String displayName = "My Company Name";
      // String externalId = "Identifier of this company in my system";
      TenantOrProjectName parent = TenantName.of(projectId, tenantId);
      Company company =
          Company.newBuilder().setDisplayName(displayName).setExternalId(externalId).build();
      CreateCompanyRequest request =
          CreateCompanyRequest.newBuilder()
              .setParent(parent.toString())
              .setCompany(company)
              .build();
      Company response = companyServiceClient.createCompany(request);
      System.out.println("Created Company");
      System.out.printf("Name: %s\n", response.getName());
      System.out.printf("Display Name: %s\n", response.getDisplayName());
      System.out.printf("External ID: %s\n", response.getExternalId());
    } catch (Exception exception) {
      System.err.println("Failed to create the client due to: " + exception);
    }
  }

  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("project_id").build());
    options.addOption(Option.builder("").required(false).hasArg(true).longOpt("tenant_id").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("display_name").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("external_id").build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    String projectId = cl.getOptionValue("project_id", "Your Google Cloud Project ID");
    String tenantId = cl.getOptionValue("tenant_id", "Your Tenant ID (using tenancy is optional)");
    String displayName = cl.getOptionValue("display_name", "My Company Name");
    String externalId = cl.getOptionValue("external_id", "Identifier of this company in my system");

    sampleCreateCompany(projectId, tenantId, displayName, externalId);
  }
}
// FIXME: Insert here clean-up code.

Node.js

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

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

/**
 * Create Company
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the Tenant
 */
function sampleCreateCompany(projectId, tenantId, displayName, externalId) {
  const client = new talent.CompanyServiceClient();
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const displayName = 'My Company Name';
  // const externalId = 'Identifier of this company in my system';
  const formattedParent = client.tenantPath(projectId, tenantId);
  const company = {
    displayName: displayName,
    externalId: externalId,
  };
  const request = {
    parent: formattedParent,
    company: company,
  };
  client.createCompany(request)
    .then(responses => {
      const response = responses[0];
      console.log(`Created Company`);
      console.log(`Name: ${response.name}`);
      console.log(`Display Name: ${response.displayName}`);
      console.log(`External ID: ${response.externalId}`);
    })
    .catch(err => {
      console.error(err);
    });
}

PHP

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

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

use Google\Cloud\Talent\V4beta1\CompanyServiceClient;
use Google\Cloud\Talent\V4beta1\Company;

/**
 * Create Company.
 *
 * @param string $projectId Your Google Cloud Project ID
 * @param string $tenantId  Identifier of the Tenant
 */
function sampleCreateCompany($projectId, $tenantId, $displayName, $externalId)
{

    $companyServiceClient = new CompanyServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    // $displayName = 'My Company Name';
    // $externalId = 'Identifier of this company in my system';
    $formattedParent = $companyServiceClient->tenantName($projectId, $tenantId);
    $company = new Company();
    $company->setDisplayName($displayName);
    $company->setExternalId($externalId);

    try {
        $response = $companyServiceClient->createCompany($formattedParent, $company);
        printf('Created Company'.PHP_EOL);
        printf('Name: %s'.PHP_EOL, $response->getName());
        printf('Display Name: %s'.PHP_EOL, $response->getDisplayName());
        printf('External ID: %s'.PHP_EOL, $response->getExternalId());
    } finally {
        $companyServiceClient->close();
    }

}

Python

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

from google.cloud import talent_v4beta1
import six

def sample_create_company(project_id, tenant_id, display_name, external_id):
    """Create Company"""

    client = talent_v4beta1.CompanyServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # display_name = 'My Company Name'
    # external_id = 'Identifier of this company in my system'

    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(display_name, six.binary_type):
        display_name = display_name.decode('utf-8')
    if isinstance(external_id, six.binary_type):
        external_id = external_id.decode('utf-8')
    parent = client.tenant_path(project_id, tenant_id)
    company = {'display_name': display_name, 'external_id': external_id}

    response = client.create_company(parent, company)
    print('Created Company')
    print('Name: {}'.format(response.name))
    print('Display Name: {}'.format(response.display_name))
    print('External ID: {}'.format(response.external_id))

Ruby

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

 # Create Company
 #
 # @param project_id {String} Your Google Cloud Project ID
 # @param tenant_id {String} Identifier of the Tenant
def sample_create_company(project_id, tenant_id, display_name, external_id)
  # Instantiate a client
  company_client = Google::Cloud::Talent::CompanyService.new version: :v4beta1

  # project_id = "Your Google Cloud Project ID"
  # tenant_id = "Your Tenant ID (using tenancy is optional)"
  # display_name = "My Company Name"
  # external_id = "Identifier of this company in my system"
  formatted_parent = company_client.class.tenant_path(project_id, tenant_id)
  company = { display_name: display_name, external_id: external_id }

  response = company_client.create_company(formatted_parent, company)
  puts "Created Company"
  puts "Name: #{response.name}"
  puts "Display Name: #{response.display_name}"
  puts "External ID: #{response.external_id}"

end

创建职位

要发布新的职位资源,您必须提供有关此职位的所有必需字段以及要与此职位关联的公司的 companyName。在创建公司资源时,您已指定了 companyName

使用 POST 请求将填充了职位数据的数据对象发送到 Cloud Talent Solution 端点。name 字段不应在初始请求中设置,因为它是 createJob API 的“仅供输出”字段:当服务器创建新的职位实体时,它是该 API 响应的一部分。用于与职位资源交互的 API 端点在 Cloud Talent Solution 客户端库文档中指定。

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

当您尝试创建新的职位时,如果系统中已存在另一个具有相同 companyNamerequisitionIdlanguageCode 的职位,则服务器将返回错误。

通过 Cloud Talent Solution,您还可以创建针对特定地点的职位。如需了解详情,请参阅 locations

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

您可以使用以下代码示例创建职位。如需了解详情,请参阅快速入门:创建公司和职位

Go

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

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
)

// createJob create a job as given.
func createJob(w io.Writer, projectID, companyID, requisitionID, title, URI, description, address1, address2, languageCode string) (*talentpb.Job, error) {
	ctx := context.Background()

	// Initialize a jobService client.
	c, err := talent.NewJobClient(ctx)
	if err != nil {
		fmt.Printf("talent.NewJobClient: %v\n", err)
		return nil, err
	}

	jobToCreate := &talentpb.Job{
		CompanyName:   fmt.Sprintf("projects/%s/companies/%s", projectID, companyID),
		RequisitionId: requisitionID,
		Title:         title,
		ApplicationInfo: &talentpb.Job_ApplicationInfo{
			Uris: []string{URI},
		},
		Description:  description,
		Addresses:    []string{address1, address2},
		LanguageCode: languageCode,
	}

	// Construct a createJob request.
	req := &talentpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		Job:    jobToCreate,
	}

	resp, err := c.CreateJob(ctx, req)
	if err != nil {
		fmt.Printf("Failed to create job: %v\n", err)
		return nil, err
	}

	fmt.Printf("Created job: %q\n", resp.GetName())

	return resp, nil
}

Java

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

/*
 * Please include the following imports to run this sample.
 *
 * import com.google.cloud.talent.v4beta1.CreateJobRequest;
 * import com.google.cloud.talent.v4beta1.Job;
 * import com.google.cloud.talent.v4beta1.Job.ApplicationInfo;
 * import com.google.cloud.talent.v4beta1.JobServiceClient;
 * import com.google.cloud.talent.v4beta1.TenantName;
 * import com.google.cloud.talent.v4beta1.TenantOrProjectName;
 * import java.util.Arrays;
 * import java.util.List;
 */
public class JobSearchCreateJob {
  /**
   * Create Job
   *
   * @param projectId Your Google Cloud Project ID
   * @param tenantId Identifier of the Tenant
   */
  public static void sampleCreateJob(
      String projectId,
      String tenantId,
      String companyName,
      String requisitionId,
      String title,
      String description,
      String jobApplicationUrl,
      String addressOne,
      String addressTwo,
      String languageCode) {
    try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
      // String projectId = "Your Google Cloud Project ID";
      // String tenantId = "Your Tenant ID (using tenancy is optional)";
      // String companyName = "Company name, e.g. projects/your-project/companies/company-id";
      // String requisitionId = "Job requisition ID, aka Posting ID. Unique per job.";
      // String title = "Software Engineer";
      // String description = "This is a description of this <i>wonderful</i> job!";
      // String jobApplicationUrl = "https://www.example.org/job-posting/123";
      // String addressOne = "1600 Amphitheatre Parkway, Mountain View, CA 94043";
      // String addressTwo = "111 8th Avenue, New York, NY 10011";
      // String languageCode = "en-US";
      TenantOrProjectName parent = TenantName.of(projectId, tenantId);
      List<String> uris = Arrays.asList(jobApplicationUrl);
      Job.ApplicationInfo applicationInfo =
          Job.ApplicationInfo.newBuilder().addAllUris(uris).build();
      List<String> addresses = Arrays.asList(addressOne, addressTwo);
      Job job =
          Job.newBuilder()
              .setCompany(companyName)
              .setRequisitionId(requisitionId)
              .setTitle(title)
              .setDescription(description)
              .setApplicationInfo(applicationInfo)
              .addAllAddresses(addresses)
              .setLanguageCode(languageCode)
              .build();
      CreateJobRequest request =
          CreateJobRequest.newBuilder().setParent(parent.toString()).setJob(job).build();
      Job response = jobServiceClient.createJob(request);
      System.out.printf("Created job: %s\n", response.getName());
    } catch (Exception exception) {
      System.err.println("Failed to create the client due to: " + exception);
    }
  }

  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("project_id").build());
    options.addOption(Option.builder("").required(false).hasArg(true).longOpt("tenant_id").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("company_name").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("requisition_id").build());
    options.addOption(Option.builder("").required(false).hasArg(true).longOpt("title").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("description").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("job_application_url").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("address_one").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("address_two").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("language_code").build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    String projectId = cl.getOptionValue("project_id", "Your Google Cloud Project ID");
    String tenantId = cl.getOptionValue("tenant_id", "Your Tenant ID (using tenancy is optional)");
    String companyName =
        cl.getOptionValue(
            "company_name", "Company name, e.g. projects/your-project/companies/company-id");
    String requisitionId =
        cl.getOptionValue("requisition_id", "Job requisition ID, aka Posting ID. Unique per job.");
    String title = cl.getOptionValue("title", "Software Engineer");
    String description =
        cl.getOptionValue("description", "This is a description of this <i>wonderful</i> job!");
    String jobApplicationUrl =
        cl.getOptionValue("job_application_url", "https://www.example.org/job-posting/123");
    String addressOne =
        cl.getOptionValue("address_one", "1600 Amphitheatre Parkway, Mountain View, CA 94043");
    String addressTwo = cl.getOptionValue("address_two", "111 8th Avenue, New York, NY 10011");
    String languageCode = cl.getOptionValue("language_code", "en-US");

    sampleCreateJob(
        projectId,
        tenantId,
        companyName,
        requisitionId,
        title,
        description,
        jobApplicationUrl,
        addressOne,
        addressTwo,
        languageCode);
  }
}
// FIXME: Insert here clean-up code.

Node.js

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

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

/**
 * Create Job
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the Tenant
 */
function sampleCreateJob(projectId, tenantId, companyName, requisitionId, title, description, jobApplicationUrl, addressOne, addressTwo, languageCode) {
  const client = new talent.JobServiceClient();
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const companyName = 'Company name, e.g. projects/your-project/companies/company-id';
  // const requisitionId = 'Job requisition ID, aka Posting ID. Unique per job.';
  // const title = 'Software Engineer';
  // const description = 'This is a description of this <i>wonderful</i> job!';
  // const jobApplicationUrl = 'https://www.example.org/job-posting/123';
  // const addressOne = '1600 Amphitheatre Parkway, Mountain View, CA 94043';
  // const addressTwo = '111 8th Avenue, New York, NY 10011';
  // const languageCode = 'en-US';
  const formattedParent = client.tenantPath(projectId, tenantId);
  const uris = [jobApplicationUrl];
  const applicationInfo = {
    uris: uris,
  };
  const addresses = [addressOne, addressTwo];
  const job = {
    company: companyName,
    requisitionId: requisitionId,
    title: title,
    description: description,
    applicationInfo: applicationInfo,
    addresses: addresses,
    languageCode: languageCode,
  };
  const request = {
    parent: formattedParent,
    job: job,
  };
  client.createJob(request)
    .then(responses => {
      const response = responses[0];
      console.log(`Created job: ${response.name}`);
    })
    .catch(err => {
      console.error(err);
    });
}

PHP

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

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

use Google\Cloud\Talent\V4beta1\JobServiceClient;
use Google\Cloud\Talent\V4beta1\Job;
use Google\Cloud\Talent\V4beta1\Job_ApplicationInfo;

/**
 * Create Job.
 *
 * @param string $projectId Your Google Cloud Project ID
 * @param string $tenantId  Identifier of the Tenant
 */
function sampleCreateJob($projectId, $tenantId, $companyName, $requisitionId, $title, $description, $jobApplicationUrl, $addressOne, $addressTwo, $languageCode)
{

    $jobServiceClient = new JobServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    // $companyName = 'Company name, e.g. projects/your-project/companies/company-id';
    // $requisitionId = 'Job requisition ID, aka Posting ID. Unique per job.';
    // $title = 'Software Engineer';
    // $description = 'This is a description of this <i>wonderful</i> job!';
    // $jobApplicationUrl = 'https://www.example.org/job-posting/123';
    // $addressOne = '1600 Amphitheatre Parkway, Mountain View, CA 94043';
    // $addressTwo = '111 8th Avenue, New York, NY 10011';
    // $languageCode = 'en-US';
    $formattedParent = $jobServiceClient->tenantName($projectId, $tenantId);
    $uris = [$jobApplicationUrl];
    $applicationInfo = new Job_ApplicationInfo();
    $applicationInfo->setUris($uris);
    $addresses = [$addressOne, $addressTwo];
    $job = new Job();
    $job->setCompany($companyName);
    $job->setRequisitionId($requisitionId);
    $job->setTitle($title);
    $job->setDescription($description);
    $job->setApplicationInfo($applicationInfo);
    $job->setAddresses($addresses);
    $job->setLanguageCode($languageCode);

    try {
        $response = $jobServiceClient->createJob($formattedParent, $job);
        printf('Created job: %s'.PHP_EOL, $response->getName());
    } finally {
        $jobServiceClient->close();
    }

}

Python

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

from google.cloud import talent_v4beta1
import six

def sample_create_job(project_id, tenant_id, company_name, requisition_id,
                      title, description, job_application_url, address_one,
                      address_two, language_code):
    """Create Job"""

    client = talent_v4beta1.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # company_name = 'Company name, e.g. projects/your-project/companies/company-id'
    # requisition_id = 'Job requisition ID, aka Posting ID. Unique per job.'
    # title = 'Software Engineer'
    # description = 'This is a description of this <i>wonderful</i> job!'
    # job_application_url = 'https://www.example.org/job-posting/123'
    # address_one = '1600 Amphitheatre Parkway, Mountain View, CA 94043'
    # address_two = '111 8th Avenue, New York, NY 10011'
    # 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(company_name, six.binary_type):
        company_name = company_name.decode('utf-8')
    if isinstance(requisition_id, six.binary_type):
        requisition_id = requisition_id.decode('utf-8')
    if isinstance(title, six.binary_type):
        title = title.decode('utf-8')
    if isinstance(description, six.binary_type):
        description = description.decode('utf-8')
    if isinstance(job_application_url, six.binary_type):
        job_application_url = job_application_url.decode('utf-8')
    if isinstance(address_one, six.binary_type):
        address_one = address_one.decode('utf-8')
    if isinstance(address_two, six.binary_type):
        address_two = address_two.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)
    uris = [job_application_url]
    application_info = {'uris': uris}
    addresses = [address_one, address_two]
    job = {
        'company': company_name,
        'requisition_id': requisition_id,
        'title': title,
        'description': description,
        'application_info': application_info,
        'addresses': addresses,
        'language_code': language_code
    }

    response = client.create_job(parent, job)
    print('Created job: {}'.format(response.name))

Ruby

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

 # Create Job
 #
 # @param project_id {String} Your Google Cloud Project ID
 # @param tenant_id {String} Identifier of the Tenant
def sample_create_job(project_id, tenant_id, company_name, requisition_id, title, description, job_application_url, address_one, address_two, language_code)
  # 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)"
  # company_name = "Company name, e.g. projects/your-project/companies/company-id"
  # requisition_id = "Job requisition ID, aka Posting ID. Unique per job."
  # title = "Software Engineer"
  # description = "This is a description of this <i>wonderful</i> job!"
  # job_application_url = "https://www.example.org/job-posting/123"
  # address_one = "1600 Amphitheatre Parkway, Mountain View, CA 94043"
  # address_two = "111 8th Avenue, New York, NY 10011"
  # language_code = "en-US"
  formatted_parent = job_client.class.tenant_path(project_id, tenant_id)
  uris = [job_application_url]
  application_info = { uris: uris }
  addresses = [address_one, address_two]
  job = {
    company: company_name,
    requisition_id: requisition_id,
    title: title,
    description: description,
    application_info: application_info,
    addresses: addresses,
    language_code: language_code
  }

  response = job_client.create_job(formatted_parent, job)
  puts "Created job: #{response.name}"

end

使用自定义字段创建职位

Cloud Talent Solution 包含很多内置于 API 架构中的职位字段。但是,您仍然可能需要一些开箱即用选项中不存在的其他字段。虽然我们建议您尽可能使用开箱即用的字段,但 Cloud Talent Solution 还是为职位提供了一些 customAttributes。这些属性可能可以过滤,也可能不可过滤。如需了解详情,请参阅 customAttributes 文档。

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

Go

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

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"github.com/gofrs/uuid"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
	money "google.golang.org/genproto/googleapis/type/money"
)

// createJobWithCustomAttributes creates a job with custom attributes.
func createJobWithCustomAttributes(w io.Writer, projectID, companyID, jobTitle string) (*talentpb.Job, error) {
	ctx := context.Background()

	// Initialize a job service client.
	c, err := talent.NewJobClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("talent.NewJobClient: %v", err)
	}

	// requisitionID shoud be the unique ID in your system
	requisitionID := fmt.Sprintf("job-with-custom-attribute-%s", uuid.Must(uuid.NewV4()).String())
	jobToCreate := &talentpb.Job{
		Company:       fmt.Sprintf("projects/%s/companies/%s", projectID, companyID),
		RequisitionId: requisitionID,
		Title:         jobTitle,
		ApplicationInfo: &talentpb.Job_ApplicationInfo{
			Uris: []string{"https://googlesample.com/career"},
		},
		Description:     "Design, devolop, test, deploy, maintain and improve software.",
		LanguageCode:    "en-US",
		PromotionValue:  2,
		EmploymentTypes: []talentpb.EmploymentType{talentpb.EmploymentType_FULL_TIME},
		Addresses:       []string{"Mountain View, CA"},
		CustomAttributes: map[string]*talentpb.CustomAttribute{
			"someFieldString": {
				Filterable:   true,
				StringValues: []string{"someStrVal"},
			},
			"someFieldLong": {
				Filterable: true,
				LongValues: []int64{900},
			},
		},
		CompensationInfo: &talentpb.CompensationInfo{
			Entries: []*talentpb.CompensationInfo_CompensationEntry{
				{
					Type: talentpb.CompensationInfo_BASE,
					Unit: talentpb.CompensationInfo_HOURLY,
					CompensationAmount: &talentpb.CompensationInfo_CompensationEntry_Amount{
						Amount: &money.Money{
							CurrencyCode: "USD",
							Units:        1,
						},
					},
				},
			},
		},
	}

	// Construct a createJob request.
	req := &talentpb.CreateJobRequest{
		Parent: fmt.Sprintf("projects/%s", projectID),
		Job:    jobToCreate,
	}

	resp, err := c.CreateJob(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("CreateJob: %v", err)
	}

	fmt.Fprintf(w, "Created job with custom attributres: %q\n", resp.GetName())
	fmt.Fprintf(w, "Custom long field has value: %v\n", resp.GetCustomAttributes()["someFieldLong"].GetLongValues())

	return resp, nil
}

Java

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

/*
 * Please include the following imports to run this sample.
 *
 * import com.google.cloud.talent.v4beta1.CreateJobRequest;
 * import com.google.cloud.talent.v4beta1.Job;
 * import com.google.cloud.talent.v4beta1.JobServiceClient;
 * import com.google.cloud.talent.v4beta1.TenantName;
 * import com.google.cloud.talent.v4beta1.TenantOrProjectName;
 */
public class JobSearchCreateJobCustomAttributes {
  /**
   * Create Job with Custom Attributes
   *
   * @param projectId Your Google Cloud Project ID
   * @param tenantId Identifier of the Tenantd
   */
  public static void sampleCreateJob(
      String projectId,
      String tenantId,
      String companyName,
      String requisitionId,
      String languageCode) {
    try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
      // String projectId = "Your Google Cloud Project ID";
      // String tenantId = "Your Tenant ID (using tenancy is optional)";
      // String companyName = "Company name, e.g. projects/your-project/companies/company-id";
      // String requisitionId = "Job requisition ID, aka Posting ID. Unique per job.";
      // String languageCode = "en-US";
      TenantOrProjectName parent = TenantName.of(projectId, tenantId);
      Job job =
          Job.newBuilder()
              .setCompany(companyName)
              .setRequisitionId(requisitionId)
              .setLanguageCode(languageCode)
              .build();
      CreateJobRequest request =
          CreateJobRequest.newBuilder().setParent(parent.toString()).setJob(job).build();
      Job response = jobServiceClient.createJob(request);
      System.out.printf("Created job: %s\n", response.getName());
    } catch (Exception exception) {
      System.err.println("Failed to create the client due to: " + exception);
    }
  }

  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("project_id").build());
    options.addOption(Option.builder("").required(false).hasArg(true).longOpt("tenant_id").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("company_name").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("requisition_id").build());
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("language_code").build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    String projectId = cl.getOptionValue("project_id", "Your Google Cloud Project ID");
    String tenantId = cl.getOptionValue("tenant_id", "Your Tenant ID (using tenancy is optional)");
    String companyName =
        cl.getOptionValue(
            "company_name", "Company name, e.g. projects/your-project/companies/company-id");
    String requisitionId =
        cl.getOptionValue("requisition_id", "Job requisition ID, aka Posting ID. Unique per job.");
    String languageCode = cl.getOptionValue("language_code", "en-US");

    sampleCreateJob(projectId, tenantId, companyName, requisitionId, languageCode);
  }
}
// FIXME: Insert here clean-up code.

Node.js

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

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

/**
 * Create Job with Custom Attributes
 *
 * @param projectId {string} Your Google Cloud Project ID
 * @param tenantId {string} Identifier of the Tenantd
 */
function sampleCreateJob(projectId, tenantId, companyName, requisitionId, languageCode) {
  const client = new talent.JobServiceClient();
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const companyName = 'Company name, e.g. projects/your-project/companies/company-id';
  // const requisitionId = 'Job requisition ID, aka Posting ID. Unique per job.';
  // const languageCode = 'en-US';
  const formattedParent = client.tenantPath(projectId, tenantId);
  const job = {
    company: companyName,
    requisitionId: requisitionId,
    languageCode: languageCode,
  };
  const request = {
    parent: formattedParent,
    job: job,
  };
  client.createJob(request)
    .then(responses => {
      const response = responses[0];
      console.log(`Created job: ${response.name}`);
    })
    .catch(err => {
      console.error(err);
    });
}

PHP

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

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

use Google\Cloud\Talent\V4beta1\JobServiceClient;
use Google\Cloud\Talent\V4beta1\Job;

/**
 * Create Job with Custom Attributes.
 *
 * @param string $projectId Your Google Cloud Project ID
 * @param string $tenantId  Identifier of the Tenantd
 */
function sampleCreateJob($projectId, $tenantId, $companyName, $requisitionId, $languageCode)
{

    $jobServiceClient = new JobServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    // $companyName = 'Company name, e.g. projects/your-project/companies/company-id';
    // $requisitionId = 'Job requisition ID, aka Posting ID. Unique per job.';
    // $languageCode = 'en-US';
    $formattedParent = $jobServiceClient->tenantName($projectId, $tenantId);
    $job = new Job();
    $job->setCompany($companyName);
    $job->setRequisitionId($requisitionId);
    $job->setLanguageCode($languageCode);

    try {
        $response = $jobServiceClient->createJob($formattedParent, $job);
        printf('Created job: %s'.PHP_EOL, $response->getName());
    } finally {
        $jobServiceClient->close();
    }

}

Python

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

from google.cloud import talent_v4beta1
import six

def sample_create_job(project_id, tenant_id, company_name, requisition_id,
                      language_code):
    """Create Job with Custom Attributes"""

    client = talent_v4beta1.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # company_name = 'Company name, e.g. projects/your-project/companies/company-id'
    # requisition_id = 'Job requisition ID, aka Posting ID. Unique per job.'
    # 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(company_name, six.binary_type):
        company_name = company_name.decode('utf-8')
    if isinstance(requisition_id, six.binary_type):
        requisition_id = requisition_id.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)
    job = {
        'company': company_name,
        'requisition_id': requisition_id,
        'language_code': language_code
    }

    response = client.create_job(parent, job)
    print('Created job: {}'.format(response.name))

Ruby

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

 # Create Job with Custom Attributes
 #
 # @param project_id {String} Your Google Cloud Project ID
 # @param tenant_id {String} Identifier of the Tenantd
def sample_create_job(project_id, tenant_id, company_name, requisition_id, language_code)
  # 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)"
  # company_name = "Company name, e.g. projects/your-project/companies/company-id"
  # requisition_id = "Job requisition ID, aka Posting ID. Unique per job."
  # language_code = "en-US"
  formatted_parent = job_client.class.tenant_path(project_id, tenant_id)
  job = {
    company: company_name,
    requisition_id: requisition_id,
    language_code: language_code
  }

  response = job_client.create_job(formatted_parent, job)
  puts "Created job: #{response.name}"

end

检索职位

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

您可以向 Cloud Talent Solution API 发送 GET 请求,以检索之前插入的职位的详细信息。URI 应包含原始 CREATE 请求返回的之前插入的职位 name 作为网址参数。

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

Go

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

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	talentpb "google.golang.org/genproto/googleapis/cloud/talent/v4beta1"
)

// getJob gets an existing job by its resource name.
func getJob(w io.Writer, projectID, jobID string) (*talentpb.Job, error) {
	ctx := context.Background()

	// Initialize a jobService client.
	c, err := talent.NewJobClient(ctx)
	if err != nil {
		fmt.Printf("talent.NewJobClient: %v\n", err)
		return nil, err
	}

	// Construct a getJob request.
	jobName := fmt.Sprintf("projects/%s/jobs/%s", projectID, jobID)
	req := &talentpb.GetJobRequest{
		// The resource name of the job to retrieve.
		// The format is "projects/{project_id}/jobs/{job_id}".
		Name: jobName,
	}

	resp, err := c.GetJob(ctx, req)
	if err != nil {
		fmt.Printf("Failed to get job %s: %v\n", jobName, err)
		return nil, err
	}

	fmt.Fprintf(w, "Job: %q\n", resp.GetName())
	fmt.Fprintf(w, "Job title: %v\n", resp.GetTitle())

	return resp, err
}

Java

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

/*
 * Please include the following imports to run this sample.
 *
 * import com.google.cloud.talent.v4beta1.GetJobRequest;
 * import com.google.cloud.talent.v4beta1.Job;
 * import com.google.cloud.talent.v4beta1.JobName;
 * import com.google.cloud.talent.v4beta1.JobServiceClient;
 * import com.google.cloud.talent.v4beta1.JobWithTenantName;
 */
public class JobSearchGetJob {
  /** Get Job */
  public static void sampleGetJob(String projectId, String tenantId, String jobId) {
    try (JobServiceClient jobServiceClient = JobServiceClient.create()) {
      // String projectId = "Your Google Cloud Project ID";
      // String tenantId = "Your Tenant ID (using tenancy is optional)";
      // String jobId = "Job ID";
      JobName name = JobWithTenantName.of(projectId, tenantId, jobId);
      GetJobRequest request = GetJobRequest.newBuilder().setName(name.toString()).build();
      Job response = jobServiceClient.getJob(request);
      System.out.printf("Job name: %s\n", response.getName());
      System.out.printf("Requisition ID: %s\n", response.getRequisitionId());
      System.out.printf("Title: %s\n", response.getTitle());
      System.out.printf("Description: %s\n", response.getDescription());
      System.out.printf("Posting language: %s\n", response.getLanguageCode());
      for (String address : response.getAddressesList()) {
        System.out.printf("Address: %s\n", address);
      }
      for (String email : response.getApplicationInfo().getEmailsList()) {
        System.out.printf("Email: %s\n", email);
      }
      for (String websiteUri : response.getApplicationInfo().getUrisList()) {
        System.out.printf("Website: %s\n", websiteUri);
      }
    } catch (Exception exception) {
      System.err.println("Failed to create the client due to: " + exception);
    }
  }

  public static void main(String[] args) throws Exception {
    Options options = new Options();
    options.addOption(
        Option.builder("").required(false).hasArg(true).longOpt("project_id").build());
    options.addOption(Option.builder("").required(false).hasArg(true).longOpt("tenant_id").build());
    options.addOption(Option.builder("").required(false).hasArg(true).longOpt("job_id").build());

    CommandLine cl = (new DefaultParser()).parse(options, args);
    String projectId = cl.getOptionValue("project_id", "Your Google Cloud Project ID");
    String tenantId = cl.getOptionValue("tenant_id", "Your Tenant ID (using tenancy is optional)");
    String jobId = cl.getOptionValue("job_id", "Job ID");

    sampleGetJob(projectId, tenantId, jobId);
  }
}
// FIXME: Insert here clean-up code.

Node.js

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

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

/** Get Job */
function sampleGetJob(projectId, tenantId, jobId) {
  const client = new talent.JobServiceClient();
  // const projectId = 'Your Google Cloud Project ID';
  // const tenantId = 'Your Tenant ID (using tenancy is optional)';
  // const jobId = 'Job ID';
  const formattedName = client.jobPath(projectId, tenantId, jobId);
  client.getJob({name: formattedName})
    .then(responses => {
      const response = responses[0];
      console.log(`Job name: ${response.name}`);
      console.log(`Requisition ID: ${response.requisitionId}`);
      console.log(`Title: ${response.title}`);
      console.log(`Description: ${response.description}`);
      console.log(`Posting language: ${response.languageCode}`);
      for (const address of response.addresses) {
        console.log(`Address: ${address}`);
      }
      for (const email of response.applicationInfo.emails) {
        console.log(`Email: ${email}`);
      }
      for (const websiteUri of response.applicationInfo.uris) {
        console.log(`Website: ${websiteUri}`);
      }
    })
    .catch(err => {
      console.error(err);
    });
}

PHP

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

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

use Google\Cloud\Talent\V4beta1\JobServiceClient;

/** Get Job */
function sampleGetJob($projectId, $tenantId, $jobId)
{

    $jobServiceClient = new JobServiceClient();

    // $projectId = 'Your Google Cloud Project ID';
    // $tenantId = 'Your Tenant ID (using tenancy is optional)';
    // $jobId = 'Job ID';
    $formattedName = $jobServiceClient->jobName($projectId, $tenantId, $jobId);

    try {
        $response = $jobServiceClient->getJob($formattedName);
        printf('Job name: %s'.PHP_EOL, $response->getName());
        printf('Requisition ID: %s'.PHP_EOL, $response->getRequisitionId());
        printf('Title: %s'.PHP_EOL, $response->getTitle());
        printf('Description: %s'.PHP_EOL, $response->getDescription());
        printf('Posting language: %s'.PHP_EOL, $response->getLanguageCode());
        foreach ($response->getAddresses() as $address) {
            printf('Address: %s'.PHP_EOL, $address);
        }
        foreach ($response->getApplicationInfo()->getEmails() as $email) {
            printf('Email: %s'.PHP_EOL, $email);
        }
        foreach ($response->getApplicationInfo()->getUris() as $websiteUri) {
            printf('Website: %s'.PHP_EOL, $websiteUri);
        }
    } finally {
        $jobServiceClient->close();
    }

}

Python

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

from google.cloud import talent_v4beta1
import six

def sample_get_job(project_id, tenant_id, job_id):
    """Get Job"""

    client = talent_v4beta1.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # job_id = 'Job ID'

    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(job_id, six.binary_type):
        job_id = job_id.decode('utf-8')
    name = client.job_path(project_id, tenant_id, job_id)

    response = client.get_job(name)
    print('Job name: {}'.format(response.name))
    print('Requisition ID: {}'.format(response.requisition_id))
    print('Title: {}'.format(response.title))
    print('Description: {}'.format(response.description))
    print('Posting language: {}'.format(response.language_code))
    for address in response.addresses:
        print('Address: {}'.format(address))
    for email in response.application_info.emails:
        print('Email: {}'.format(email))
    for website_uri in response.application_info.uris:
        print('Website: {}'.format(website_uri))

Ruby

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

# Get Job
def sample_get_job(project_id, tenant_id, job_id)
  # 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)"
  # job_id = "Job ID"
  formatted_name = job_client.class.job_path(project_id, tenant_id, job_id)

  response = job_client.get_job(formatted_name)
  puts "Job name: #{response.name}"
  puts "Requisition ID: #{response.requisition_id}"
  puts "Title: #{response.title}"
  puts "Description: #{response.description}"
  puts "Posting language: #{response.language_code}"
  response.addresses.each do |address|
    puts "Address: #{address}"
  end
  response.application_info.emails.each do |email|
    puts "Email: #{email}"
  end
  response.application_info.uris.each do |website_uri|
    puts "Website: #{website_uri}"
  end

end

搜索职位

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