Conceptos básicos de los trabajos (v4beta1)

Un recurso Job representa una publicación de trabajo única (también llamada "lista de trabajos" o "requerimiento de trabajo"). Un trabajo pertenece a un recurso Company que representa a la entidad que contrata y es responsable del trabajo.

Puedes acceder a un trabajo con los métodos LIST y GET, y manipularlo con los métodos CREATE, UPDATE y DELETE. Es posible que el índice de Cloud Talent Solution tarde varios minutos en reflejar los cambios.

Los trabajos se almacenan en el alcance de una cuenta de servicio. Solo se pueden usar solicitudes de búsqueda autenticadas con las credenciales de una cuenta de servicio determinada para acceder al contenido de estos trabajos.

Para facilitar la solución de problemas y la clasificación, sincroniza el índice de trabajos de Cloud Talent Solution con el tuyo y mantén una relación entre el name que genera Cloud Talent Solution y el identificador único de los trabajos de tu sistema. A medida que los trabajos cambian o se introducen en tu sistema, se debe enviar la llamada CRUD adecuada al CTS en tiempo real para garantizar que estos cambios se reflejen de inmediato. El índice de CTS se debe agregar a la canalización de transferencia de trabajos existente.

Crear un trabajo

Puedes crear un trabajo con la siguiente muestra de código. Consulta Guía de inicio rápido: Crea empresas y trabajos para obtener más detalles. Los videos instructivos y los codelabs interactivos también están disponibles.

Go

Para aprender a instalar y usar la biblioteca cliente de CTS, consulta Bibliotecas cliente de CTS. Para obtener más información, consulta la documentación de referencia de la API de Go de CTS.

Para autenticarte en CTS, configura las credenciales predeterminadas de la aplicación. Si deseas obtener más información, consulta Configura la autenticación para un entorno de desarrollo local.

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

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


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 java.io.IOException;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

public class JobSearchCreateJob {

  public static void createJob() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String tenantId = "your-tenant-id";
    String companyId = "your-company-id";
    String requisitionId = "your-unique-req-id";
    String jobApplicationUrl = "your-job-url";
    createJob(projectId, tenantId, companyId, requisitionId, jobApplicationUrl);
  }

  // Create a job.
  public static void createJob(
      String projectId,
      String tenantId,
      String companyId,
      String requisitionId,
      String jobApplicationUrl)
      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);
      Job.ApplicationInfo applicationInfo =
          Job.ApplicationInfo.newBuilder().addUris(jobApplicationUrl).build();

      List<String> addresses =
          Arrays.asList(
              "1600 Amphitheatre Parkway, Mountain View, CA 94043",
              "111 8th Avenue, New York, NY 10011");

      // By default, job will expire in 30 days.
      // https://cloud.google.com/talent-solution/job-search/docs/jobs
      Job job =
          Job.newBuilder()
              .setCompany(companyId)
              .setRequisitionId(requisitionId)
              .setTitle("Software Developer")
              .setDescription("Develop, maintain the software solutions.")
              .setApplicationInfo(applicationInfo)
              .addAllAddresses(addresses)
              .setLanguageCode("en-US")
              .build();

      CreateJobRequest request =
          CreateJobRequest.newBuilder().setParent(parent.toString()).setJob(job).build();

      Job response = jobServiceClient.createJob(request);
      System.out.format("Created job: %s%n", response.getName());
    }
  }
}

Python

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


from google.cloud import talent

def create_job(
    project_id,
    tenant_id,
    company_id,
    requisition_id,
    job_application_url,
):
    """Create Job"""

    client = talent.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # company_id = '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, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(company_id, bytes):
        company_id = company_id.decode("utf-8")
    if isinstance(requisition_id, bytes):
        requisition_id = requisition_id.decode("utf-8")
    if isinstance(job_application_url, bytes):
        job_application_url = job_application_url.decode("utf-8")
    parent = f"projects/{project_id}/tenants/{tenant_id}"
    uris = [job_application_url]
    application_info = {"uris": uris}
    addresses = [
        "1600 Amphitheatre Parkway, Mountain View, CA 94043",
        "111 8th Avenue, New York, NY 10011",
    ]
    job = {
        "company": company_id,
        "requisition_id": requisition_id,
        "title": "Software Developer",
        "description": "Develop, maintain the software solutions.",
        "application_info": application_info,
        "addresses": addresses,
        "language_code": "en-US",
    }

    response = client.create_job(parent=parent, job=job)
    print(f"Created job: {response.name}")
    return response.name

Campos obligatorios

Se deben completar los siguientes campos durante la creación y la actualización de los trabajos:

  • companyName: Es el nombre de recurso de la empresa a la que pertenece el trabajo, como companyName=\"projects/{ProjectId}/companies/{CompanyId}\".

  • requisitionId: El ID de requerimiento, también conocido como ID de publicación, es un valor que asignas para identificar un trabajo. Puedes usar este campo para la identificación del cliente y el seguimiento de solicitudes. La cantidad máxima de caracteres permitida es 255.

    Para determinar que una publicación de trabajo sea única, se usa una combinación de requisitionID, companyName y ubicación. Si se crea un trabajo con una clave específica de estos atributos, la clave se almacena en el índice de Cloud Talent Solution y no se pueden crear más trabajos con esos mismos campos hasta que se borre el primero.

  • title: es el título del trabajo, por ejemplo, "Ingeniero de software". La cantidad máxima de caracteres permitida es 500.

    Para corregir el problema de los resultados de la búsqueda faltantes a causa de títulos de trabajos no estándar, Cloud Talent Solution aprovecha todos los campos del trabajo a fin de comprender su contexto y almacenar de manera interna un título “limpio”. Cuando se envía una solicitud de búsqueda al servicio, la consulta de la búsqueda también se limpia y se usan estas ontologías para asignarla a trabajos limpios relevantes.

  • description: La descripción del trabajo, que, por lo general, incluye una descripción de varios párrafos sobre la empresa y la información relacionada. El objeto del trabajo cuenta con campos independientes para las responsabilidades, las cualificaciones y otras de sus características. Se recomienda el uso de estos campos del trabajo independientes.

    Este campo acepta la entrada HTML y la limpia, además de aceptar las etiquetas de lenguaje de marcado de negrita, cursiva, lista ordenada y lista sin ordenar. La cantidad máxima de caracteres permitida es 100,000.

Uno de los siguientes:

  • applicationInfo.uris: Son las URL de las páginas de postulación.

  • applicationInfo.emails: Direcciones de correo electrónico a las que se deben enviar los currículums o las aplicaciones.

  • applicationInfo.instruction: Son las instrucciones de postulación, como "Envía tu solicitud a…". Este campo acepta y depura la entrada HTML, y acepta las etiquetas de lenguaje de lista sin ordenar, lista ordenada, negrita y cursiva. La cantidad máxima de caracteres permitida es 3,000.

Campos de uso común

  • postingExpireTime: Indica el momento, en función de la marca de tiempo, en el que vence la publicación de trabajos. Cuando pasa ese momento, el trabajo se marca como vencido y no aparecerá en los resultados de la búsqueda. La fecha debe ser como máximo el 31 de diciembre de 2100 en la zona horaria UTC. Se ignoran las fechas no válidas (como las fechas pasadas). La fecha de vencimiento predeterminada es 30 días después de la creación del trabajo en la zona horaria UTC.

    El contenido de los trabajos vencidos permanece disponible y se puede recuperar hasta 60 días después de la fecha de vencimiento mediante el operador GET. Después de este plazo, el trabajo dejará de mostrarse mediante la operación GET.

  • addresses: Son los lugares de trabajo. Se recomienda proporcionar las direcciones completas de la entidad contratante para habilitar mejores resultados en la búsqueda de empleo, incluidas las búsquedas según el tiempo de viaje diario. La cantidad máxima de caracteres permitida es 500. Puedes encontrar más información sobre addresses en la sección Prácticas recomendadas a continuación.

  • promotionValue: Si el valor es superior a 0, se define a este trabajo como un “trabajo destacado”, que se muestra solo en búsquedas del tipo FEATURED_JOBS. Los valores más altos se muestran más arriba en los resultados destacados de la búsqueda. Consulta Trabajos destacados para obtener más información.

Usa campos de trabajo personalizados

Cloud Talent Solution incluye varios campos de trabajos integrados en los esquemas de sus API. Sin embargo, es posible que necesites campos adicionales que no estén presentes en las opciones predefinidas. Si bien recomendamos que uses los campos listos para usar siempre que sea posible, Cloud Talent Solution también proporciona algunos campos customAttributes para un trabajo. Algunos de ellos se pueden usar en los filtros. Consulta la documentación sobre customAttributes para obtener más información.

  • customAttributes: Este campo almacena hasta 100 atributos personalizados que se usan para almacenar datos personalizados sobre el trabajo. Estos campos se pueden filtrar mediante una solicitud de búsqueda que especifique el campo jobQuery. Además, cualquiera de estos campos se puede configurar en el atributo keywordSearchableJobCustomAttributes de company, por lo que un término de búsqueda que tiene una coincidencia exacta en cualquiera de los campos de keywordSearchableJobCustomAttributes muestra cualquier trabajo que incluya la coincidencia.

En el siguiente ejemplo de código, se muestra cómo crear un trabajo con un customAttribute:

Go

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.

import (
	"context"
	"fmt"
	"io"

	talent "cloud.google.com/go/talent/apiv4beta1"
	"cloud.google.com/go/talent/apiv4beta1/talentpb"
	"github.com/gofrs/uuid"
	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: %w", err)
	}
	defer c.Close()

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

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


import com.google.cloud.talent.v4beta1.CreateJobRequest;
import com.google.cloud.talent.v4beta1.CustomAttribute;
import com.google.cloud.talent.v4beta1.Job;
import com.google.cloud.talent.v4beta1.JobServiceClient;
import com.google.cloud.talent.v4beta1.TenantName;
import java.io.IOException;

public class JobSearchCreateJobCustomAttributes {

  public static void createJob() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String tenantId = "your-tenant-id";
    String companyId = "your-company-id";
    String requisitionId = "your-unique-req-id";
    createJob(projectId, tenantId, companyId, requisitionId);
  }

  // Create Job with Custom Attributes.
  public static void createJob(
          String projectId,
          String tenantId,
          String companyId,
          String requisitionId)
          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);

      // Custom attribute can be string or numeric value, and can be filtered in search queries.
      // https://cloud.google.com/talent-solution/job-search/docs/custom-attributes
      CustomAttribute customAttribute = CustomAttribute.newBuilder()
              .addStringValues("Internship")
              .addStringValues("Apprenticeship")
              .setFilterable(true)
              .build();

      Job job =
              Job.newBuilder()
                      .setCompany(companyId)
                      .setTitle("Software Developer I")
                      .setDescription("This is a description of this <i>wonderful</i> job!")
                      .putCustomAttributes("FOR_STUDENTS", customAttribute)
                      .setRequisitionId(requisitionId)
                      .setLanguageCode("en-US")
                      .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());
    }
  }
}

Python

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


from google.cloud import talent

def create_job(project_id, tenant_id, company_id, requisition_id):
    """Create Job with Custom Attributes"""

    client = talent.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # company_id = '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, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(company_id, bytes):
        company_id = company_id.decode("utf-8")

    # Custom attribute can be string or numeric value,
    # and can be filtered in search queries.
    # https://cloud.google.com/talent-solution/job-search/docs/custom-attributes
    custom_attribute = talent.CustomAttribute()
    custom_attribute.filterable = True
    custom_attribute.string_values.append("Intern")
    custom_attribute.string_values.append("Apprenticeship")

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

    job = talent.Job(
        company=company_id,
        title="Software Engineer",
        requisition_id=requisition_id,
        description="This is a description of this job",
        language_code="en-us",
        custom_attributes={"FOR_STUDENTS": custom_attribute},
    )

    response = client.create_job(parent=parent, job=job)
    print(f"Created job: {response.name}")
    return response.name

Recupera un trabajo

Go

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de 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

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


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 java.io.IOException;

public class JobSearchGetJob {

  public static void getJob() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String tenantId = "your-tenant-id";
    String jobId = "your-job-id";
    getJob(projectId, tenantId, jobId);
  }

  // Get Job.
  public static void getJob(String projectId, String tenantId, String jobId) 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()) {
      JobName name = JobName.ofProjectTenantJobName(projectId, tenantId, jobId);

      GetJobRequest request = GetJobRequest.newBuilder().setName(name.toString()).build();

      Job response = jobServiceClient.getJob(request);
      System.out.format("Job name: %s%n", response.getName());
      System.out.format("Requisition ID: %s%n", response.getRequisitionId());
      System.out.format("Title: %s%n", response.getTitle());
      System.out.format("Description: %s%n", response.getDescription());
      System.out.format("Posting language: %s%n", response.getLanguageCode());
      for (String address : response.getAddressesList()) {
        System.out.format("Address: %s%n", address);
      }
      for (String email : response.getApplicationInfo().getEmailsList()) {
        System.out.format("Email: %s%n", email);
      }
      for (String websiteUri : response.getApplicationInfo().getUrisList()) {
        System.out.format("Website: %s%n", websiteUri);
      }
    }
  }
}

Python

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


from google.cloud import talent

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

    client = talent.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, bytes):
        project_id = project_id.decode("utf-8")
    if isinstance(tenant_id, bytes):
        tenant_id = tenant_id.decode("utf-8")
    if isinstance(job_id, bytes):
        job_id = job_id.decode("utf-8")
    name = client.job_path(project_id, tenant_id, job_id)

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

Mostrar trabajos

Go

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.

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"
)

// listJobs lists jobs with a filter, for example
// `companyName="projects/my-project/companies/123"`.
func listJobs(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 listJobs request.
	companyName := fmt.Sprintf("projects/%s/companies/%s", projectID, companyID)
	req := &talentpb.ListJobsRequest{
		Parent: "projects/" + projectID,
		Filter: fmt.Sprintf("companyName=%q", companyName),
	}

	it := c.ListJobs(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, "Listing job: %v\n", resp.GetName())
		fmt.Fprintf(w, "Job title: %v\n", resp.GetTitle())
	}
}

Java

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


import com.google.cloud.talent.v4beta1.Job;
import com.google.cloud.talent.v4beta1.JobServiceClient;
import com.google.cloud.talent.v4beta1.ListJobsRequest;
import com.google.cloud.talent.v4beta1.TenantName;
import java.io.IOException;

public class JobSearchListJobs {

  public static void listJobs() 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)])";
    listJobs(projectId, tenantId, query);
  }

  // Search Jobs with histogram queries.
  public static void listJobs(String projectId, String tenantId, String filter) 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);
      ListJobsRequest request =
          ListJobsRequest.newBuilder().setParent(parent.toString()).setFilter(filter).build();
      for (Job responseItem : jobServiceClient.listJobs(request).iterateAll()) {
        System.out.format("Job name: %s%n", responseItem.getName());
        System.out.format("Job requisition ID: %s%n", responseItem.getRequisitionId());
        System.out.format("Job title: %s%n", responseItem.getTitle());
        System.out.format("Job description: %s%n", responseItem.getDescription());
      }
    }
  }
}

Python

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


from google.cloud import talent

def list_jobs(project_id, tenant_id, filter_):
    """List Jobs"""

    client = talent.JobServiceClient()

    # project_id = 'Your Google Cloud Project ID'
    # tenant_id = 'Your Tenant ID (using tenancy is optional)'
    # filter_ = 'companyName=projects/my-project/companies/company-id'

    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(filter_, bytes):
        filter_ = filter_.decode("utf-8")
    parent = f"projects/{project_id}/tenants/{tenant_id}"

    # Iterate over all results
    results = []
    for job in client.list_jobs(parent=parent, filter=filter_):
        results.append(job.name)
        print("Job name: {job.name}")
        print("Job requisition ID: {job.requisition_id}")
        print("Job title: {job.title}")
        print("Job description: {job.description}")
    return results

Borra un trabajo

Go

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.

import (
	"context"
	"fmt"
	"io"

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

// deleteJob deletes an existing job by its resource name.
func deleteJob(w io.Writer, projectID, jobID 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 deleteJob request.
	jobName := fmt.Sprintf("projects/%s/jobs/%s", projectID, jobID)
	req := &talentpb.DeleteJobRequest{
		// The resource name of the job to be deleted.
		// The format is "projects/{project_id}/jobs/{job_id}".
		Name: jobName,
	}

	if err := c.DeleteJob(ctx, req); err != nil {
		fmt.Printf("Delete(%s): %v\n", jobName, err)
		return err
	}

	fmt.Printf("Deleted job: %q\n", jobName)

	return err
}

Java

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


import com.google.cloud.talent.v4beta1.DeleteJobRequest;
import com.google.cloud.talent.v4beta1.JobName;
import com.google.cloud.talent.v4beta1.JobServiceClient;
import java.io.IOException;

public class JobSearchDeleteJob {

  public static void deleteJob() throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String tenantId = "your-tenant-id";
    String jobId = "your-job-id";
    deleteJob(projectId, tenantId, jobId);
  }

  // Delete Job.
  public static void deleteJob(String projectId, String tenantId, String jobId) 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()) {
      JobName name = JobName.ofProjectTenantJobName(projectId, tenantId, jobId);

      DeleteJobRequest request = DeleteJobRequest.newBuilder().setName(name.toString()).build();

      jobServiceClient.deleteJob(request);
      System.out.println("Deleted job.");
    }
  }
}

Python

Consulta Bibliotecas cliente de Cloud Talent Solution para obtener más información sobre cómo instalar y crear un cliente de Cloud Talent Solution.


from google.cloud import talent

def delete_job(project_id, tenant_id, job_id):
    """Delete Job"""

    client = talent.JobServiceClient()

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

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

    client.delete_job(name=name)
    print("Deleted job.")

prácticas recomendadas

Campos de ubicación

Siempre que sea posible, recomendamos proporcionar la dirección completa del trabajo en el campo addresses. Esto facilita la detección y la relevancia de la ubicación. Si la dirección no tiene una calle, ingresa la mayor cantidad de información posible. Las direcciones admiten información hasta el nivel de los países. No se admiten las denominaciones regionales (como “Noroeste del Pacífico”).

Cloud Talent Solution usa los datos del campo addresses para propagar el campo derivedInfo.locations (solo salida). Cuando no se proporciona una dirección completa, el servicio usa otras señales, como el nombre de la empresa, a fin de determinar si se puede deducir una dirección más completa para la publicación de trabajo.

Por ejemplo, si la ubicación de una posición de software se especifica como Mountain View, y la empresa a la que está asociado el trabajo es Google, el servicio busca el objeto company para ver si una mejor dirección se proporciona en el campo headquartersAddress y si esa dirección está en la misma ciudad que la publicación del trabajo. Si es así, el servicio comprende que es "probable" que el trabajo esté ubicado en esa dirección y completa el campo derivedInfo.locations de manera apropiada.

Si los datos de la dirección de la empresa no están disponibles, el servicio usa una combinación de conocimientos propios e información sobre el trabajo o la empresa para completar el campo derivedInfo.locations.

Debido a que el valor de derivedInfo.locations es una estimación, es posible que quieras usar los datos de derivedInfo.locations o el campo addresses cuando se muestre la dirección del trabajo.

Una publicación de trabajo puede tener un máximo de 50 ubicaciones asociadas. Si un trabajo tiene más ubicaciones, puedes dividirlo en varios trabajos, cada uno con un requisitionId único (por ejemplo, “ReqA”, “ReqA-1”, “ReqA-2”, etcétera). No se permite tener varios trabajos con los mismos requisitionId, companyName y languageCode. Si se debe conservar la requisitionId original, se debe usar un CustomAttribute para el almacenamiento. Se recomienda agrupar las ubicaciones cercanas en el mismo trabajo a fin de proporcionar una mejor experiencia de búsqueda.

Direcciones admitidas

Cloud Talent Solution acepta cualquier dirección que reconozca la API de Google Maps Geocoding (en el campo formattedAddress). El servicio muestra un error 400 si intentas crear un trabajo o ejecutar una búsqueda mediante una dirección no reconocida.

Si la dirección de una empresa aparece de manera incorrecta en la API de Google Maps Geocoding, informa un error para que la corrijan. Las correcciones pueden tardar hasta 5 días en aplicarse.

Autocompletado de direcciones

Cloud Talent Solution no proporciona sugerencias de autocompletado de ubicaciones. Usa la API de Google Maps Places o servicios de ubicación similares para propagar sugerencias de autocompletado.

Trabajos estatales, nacionales y desde casa

El campo postingRegion se puede usar para especificar el trabajo como estatal, nacional o remoto.

  • Los trabajos de ADMINISTRATIVE_AREA y NATION se muestran en todas las búsquedas con una ubicación especificada dentro del estado o país de la publicación de trabajo. Por ejemplo, si un trabajo de ADMINISTRATIVE_AREA tiene la ubicación “WA, EE.UU.”, se mostrará en las búsquedas que tengan un LocationFilter que especifique “Seattle”.

  • Los trabajos de TELECOMMUTE se muestran en todas las búsquedas relacionadas con la ubicación, pero su relevancia es menor. Se pueden establecer como objetivo en una búsqueda si configuras la marca telecommutePreference como TELECOMMUTE_ALLOWED en el LocationFilter de la búsqueda.