建立公司和職缺

本教學課程旨在協助您使用 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 回應。Cloud Talent Solution 用戶端程式庫說明文件中指定了與職缺資源互動的 API 端點。

要求的回應是新職缺公告的物件,應包含代表該公告的唯一職缺 name。更新或刪除公告時,需使用職缺 name。最佳做法是儲存此 name,並將其對應至您自己的職缺唯一識別碼。

如果您嘗試插入職缺,但系統中同一家公司已有另一個職缺使用相同的 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 還是會為職缺提供幾個 customAttribute,您不一定可以篩選這些屬性。詳情請參閱 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 中目前正在建立的職缺量而定。

您可以傳送 GET 要求到 Cloud Talent Solution,以擷取先前插入之職缺的詳細資料。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 建立第一個公司和職缺!您現在可以開始使用搜尋功能來搜尋這些職缺。

後續步驟