Administra trabajos de conciliación de entidades con la API

En esta guía de inicio rápido, se presenta la API de Entity Reconciliation. En esta guía de inicio rápido, usarás la consola Google Cloud para configurar tu proyectoGoogle Cloud y autenticación, crear archivos de asignación de esquemas y, luego, solicitar a Enterprise Knowledge Graph que ejecute un trabajo de conciliación de entidades.

Crea un trabajo de conciliación de entidades

Sigue estos pasos para crear un trabajo de conciliación de entidades:

REST

Para crear un trabajo simple con una tabla fuente (eliminación de duplicados), llama al método projects.locations.entityReconciliationJobs.create.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: Es el ID del proyecto de Google Cloud .
  • LOCATION: Es la ubicación en Knowledge Graph.
    • Opciones: global (extremo global)
  • DATASET_ID: ID del conjunto de datos de BigQuery
  • TABLE_ID: ID de la tabla de BigQuery
  • MAPPING_FILE_URI: Es la ruta de acceso de Cloud Storage a un archivo de asignación en formato YAML.
    • Ejemplo: gs://ekg-test-gcs/mapping.yml
  • ENTITY_TYPE: Es el tipo de entidad para la conciliación.

Método HTTP y URL:

POST https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs

Cuerpo JSON de la solicitud:

{
  "inputConfig": {
    "bigqueryInputConfigs": [
      {
        "bigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID",
        "gcsUri": "MAPPING_FILE_URI"
      }
    ],
    "entityType": "ENTITY_TYPE"
  },
  "outputConfig": {
    "bigqueryDataset": "projects/PROJECT_ID/datasets/DATASET_ID"
  }
}

Para enviar tu solicitud, elige una de estas opciones:

curl

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs"

PowerShell

Guarda el cuerpo de la solicitud en un archivo llamado request.json y ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID",
  "inputConfig": {
    "bigqueryInputConfigs": [
      {
        "bigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID",
        "gcsUri": "MAPPING_FILE_URI"
      }
    ],
    "entityType": "ENTITY_TYPE"
  },
  "outputConfig": {
    "bigqueryDataset": "projects/PROJECT_ID/datasets/DATASET_ID"
  },
  "state": "JOB_STATE_RUNNING",
  "createTime": "2021-07-31T14:39:14.145568Z",
  "updateTime": "2021-07-31T14:39:14.145568Z"
}
Para crear un trabajo con opciones avanzadas y varias tablas de BigQuery, usa un cuerpo de solicitud similar a este ejemplo:

{
  "inputConfig": {
    "bigqueryInputConfigs": [
      {
        "bigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID",
        "gcsUri": "MAPPING_FILE_URI"
      },
      {
        "bigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID",
        "gcsUri": "MAPPING_FILE_URI"
      }
    ],
    "entityType": "ENTITY_TYPE",
    "previousResultBigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/clusters_13689265293502324307"
  },
  "outputConfig": {
    "bigqueryDataset": "projects/PROJECT_ID/datasets/DATASET_ID"
  },
  "reconConfig": {
    "affinityClusteringConfig": {
      "compressionRoundCount": "2"
    },
    "options": {
      "enableGeocodingSeparation": true
    }
  }
}

Python

Si quieres obtener más información, consulta la documentación de referencia de la API de Enterprise Knowledge Graph para Python.

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


from google.cloud import enterpriseknowledgegraph as ekg

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_GRAPH_LOCATION'          # Values: 'global'
# input_dataset = 'YOUR_INPUT_DATASET'      # BigQuery Dataset Name
# input_table = 'YOUR_INPUT_TABLE'          # BigQuery Table Name
# mapping_file_uri = 'YOUR_MAPPING_FILE     # GCS Path. Example: gs://ekg-test-gcs/mapping.yml
# output_dataset = 'YOUR_OUTPUT_DATASET'    # BigQuery Dataset Name

# Refer to https://cloud.google.com/enterprise-knowledge-graph/docs/schema
# entity_type = ekg.InputConfig.EntityType.Person


def create_entity_reconciliation_job_sample(
    project_id: str,
    location: str,
    input_dataset: str,
    input_table: str,
    mapping_file_uri: str,
    entity_type: int,
    output_dataset: str,
) -> None:
    # Create a client
    client = ekg.EnterpriseKnowledgeGraphServiceClient()

    # The full resource name of the location
    # e.g. projects/{project_id}/locations/{location}
    parent = client.common_location_path(project=project_id, location=location)

    # Input Parameters
    input_config = ekg.InputConfig(
        bigquery_input_configs=[
            ekg.BigQueryInputConfig(
                bigquery_table=client.table_path(
                    project=project_id, dataset=input_dataset, table=input_table
                ),
                gcs_uri=mapping_file_uri,
            )
        ],
        entity_type=entity_type,
    )

    # Output Parameters
    output_config = ekg.OutputConfig(
        bigquery_dataset=client.dataset_path(project=project_id, dataset=output_dataset)
    )

    entity_reconciliation_job = ekg.EntityReconciliationJob(
        input_config=input_config, output_config=output_config
    )

    # Initialize request argument(s)
    request = ekg.CreateEntityReconciliationJobRequest(
        parent=parent, entity_reconciliation_job=entity_reconciliation_job
    )

    # Make the request
    response = client.create_entity_reconciliation_job(request=request)

    print(f"Job: {response.name}")
    print(
        f"Input Table: {response.input_config.bigquery_input_configs[0].bigquery_table}"
    )
    print(f"Output Dataset: {response.output_config.bigquery_dataset}")
    print(f"State: {response.state.name}")

Obtén un trabajo de conciliación de entidades

REST

Para recuperar el estado del trabajo de la API, llama al método projects.locations.entityReconciliationJobs.get.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: Es el ID del proyecto de Google Cloud .
  • LOCATION: Es la ubicación en Knowledge Graph.
    • Opciones: global (extremo global)
  • JOB_ID: Es el ID del trabajo de conciliación de entidades.
    • Ejemplo: 2628838070002699773

Método HTTP y URL:

GET https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "name": "projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID",
  "inputConfig": {
    "bigqueryInputConfigs": [
      {
        "bigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID",
        "gcsUri": "MAPPING_FILE_URI"
      }
    ],
    "entityType": "ENTITY_TYPE"
  },
  "outputConfig": {
    "bigqueryDataset": "projects/PROJECT_ID/datasets/DATASET_ID"
  },
  "state": "JOB_STATE_SUCCEEDED",
  "createTime": "2021-07-31T14:39:14.145568Z",
  "updateTime": "2021-07-31T14:39:14.145568Z"
}

Python

Si quieres obtener más información, consulta la documentación de referencia de la API de Enterprise Knowledge Graph para Python.

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


from google.cloud import enterpriseknowledgegraph as ekg

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_GRAPH_LOCATION'  # Values: 'global'
# job_id = 'YOUR_JOB_ID'            # Entity Reconciliation Job ID


def get_entity_reconciliation_job_sample(
    project_id: str, location: str, job_id: str
) -> None:
    # Create a client
    client = ekg.EnterpriseKnowledgeGraphServiceClient()

    # The full resource name of the job
    # e.g. projects/{project_id}/locations/{location}/entityReconciliationJobs/{entity_reconciliation_job}
    name = client.entity_reconciliation_job_path(
        project=project_id, location=location, entity_reconciliation_job=job_id
    )

    # Initialize request argument(s)
    request = ekg.GetEntityReconciliationJobRequest(name=name)

    # Make the request
    response = client.get_entity_reconciliation_job(request=request)

    print(f"Job: {response.name}")
    print(
        f"Input Table: {response.input_config.bigquery_input_configs[0].bigquery_table}"
    )
    print(f"Output Dataset: {response.output_config.bigquery_dataset}")
    print(f"State: {response.state.name}")

Enumera los trabajos de conciliación de entidades

REST

Para recuperar todos los trabajos de la API, llama al método projects.locations.entityReconciliationJobs.list.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: Es el ID del proyecto de Google Cloud .
  • LOCATION: Es la ubicación en Knowledge Graph.
    • Opciones: global (extremo global)

Método HTTP y URL:

GET https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs" | Select-Object -Expand Content

Deberías recibir una respuesta JSON similar a la que se muestra a continuación:

{
  "entityReconciliationJobs": [
    {
      "name": "projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID",
      "inputConfig": {
        "bigqueryInputConfigs": [
          {
            "bigqueryTable": "projects/PROJECT_ID/datasets/DATASET_ID/tables/TABLE_ID",
            "gcsUri": "MAPPING_FILE_URI"
          }
        ],
        "entityType": "ENTITY_TYPE"
      },
      "outputConfig": {
        "bigqueryDataset": "projects/PROJECT_ID/datasets/DATASET_ID"
      },
      "state": "JOB_STATE_SUCCEEDED",
      "createTime": "2021-07-31T14:39:14.145568Z",
      "updateTime": "2021-07-31T14:39:14.145568Z"
    }
  ],
  "nextPageToken": ""
}

Python

Si quieres obtener más información, consulta la documentación de referencia de la API de Enterprise Knowledge Graph para Python.

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


from google.cloud import enterpriseknowledgegraph as ekg

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_GRAPH_LOCATION'  # Values: 'global'


def list_entity_reconciliation_jobs_sample(project_id: str, location: str) -> None:
    # Create a client
    client = ekg.EnterpriseKnowledgeGraphServiceClient()

    # The full resource name of the location
    # e.g. projects/{project_id}/locations/{location}
    parent = client.common_location_path(project=project_id, location=location)

    # Initialize request argument(s)
    request = ekg.ListEntityReconciliationJobsRequest(parent=parent)

    # Make the request
    pager = client.list_entity_reconciliation_jobs(request=request)

    for response in pager:
        print(f"Job: {response.name}")
        print(
            f"Input Table: {response.input_config.bigquery_input_configs[0].bigquery_table}"
        )
        print(f"Output Dataset: {response.output_config.bigquery_dataset}")
        print(f"State: {response.state.name}\n")

Cancela un trabajo de conciliación de entidades

REST

Para detener un trabajo en ejecución desde la API, llama al método projects.locations.entityReconciliationJobs.cancel.

Enterprise Knowledge Graph detiene el trabajo lo antes posible. Ten en cuenta que la cancelación de un trabajo se basa en el mejor esfuerzo. No se garantiza el éxito del comando cancel.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: Es el ID del proyecto de Google Cloud .
  • LOCATION: Es la ubicación en Knowledge Graph.
    • Opciones: global (extremo global)
  • JOB_ID: Es el ID del trabajo de conciliación de entidades.
    • Ejemplo: 2628838070002699773

Método HTTP y URL:

POST https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID:cancel

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d "" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID:cancel"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID:cancel" | Select-Object -Expand Content

Deberías recibir un código de estado exitoso (2xx) y una respuesta vacía.

Python

Si quieres obtener más información, consulta la documentación de referencia de la API de Enterprise Knowledge Graph para Python.

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


from google.cloud import enterpriseknowledgegraph as ekg

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_GRAPH_LOCATION'  # Values: 'global'
# job_id = 'YOUR_JOB_ID'            # Entity Reconciliation Job ID


def cancel_entity_reconciliation_job_sample(
    project_id: str, location: str, job_id: str
) -> None:
    # Create a client
    client = ekg.EnterpriseKnowledgeGraphServiceClient()

    # The full resource name of the job
    # e.g. projects/{project_id}/locations/{location}/entityReconciliationJobs/{entity_reconciliation_job}
    name = client.entity_reconciliation_job_path(
        project=project_id, location=location, entity_reconciliation_job=job_id
    )

    # Initialize request argument(s)
    request = ekg.CancelEntityReconciliationJobRequest(name=name)

    # Make the request
    client.cancel_entity_reconciliation_job(request=request)

    print(f"Job: {name} successfully cancelled")

Borra un trabajo de conciliación de entidades

REST

Para quitar un trabajo completado o fallido con la API, llama al método projects.locations.entityReconciliationJobs.delete.

Antes de usar cualquiera de los datos de solicitud a continuación, realiza los siguientes reemplazos:

  • PROJECT_ID: Es el ID del proyecto de Google Cloud .
  • LOCATION: Es la ubicación en Knowledge Graph.
    • Opciones: global (extremo global)
  • JOB_ID: Es el ID del trabajo de conciliación de entidades.
    • Ejemplo: 2628838070002699773

Método HTTP y URL:

DELETE https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID

Para enviar tu solicitud, elige una de estas opciones:

curl

Ejecuta el siguiente comando:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
"https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID"

PowerShell

Ejecuta el siguiente comando:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://enterpriseknowledgegraph.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/entityReconciliationJobs/JOB_ID" | Select-Object -Expand Content

Deberías recibir un código de estado exitoso (2xx) y una respuesta vacía.

Python

Si quieres obtener más información, consulta la documentación de referencia de la API de Enterprise Knowledge Graph para Python.

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


from google.cloud import enterpriseknowledgegraph as ekg

# TODO(developer): Uncomment these variables before running the sample.
# project_id = 'YOUR_PROJECT_ID'
# location = 'YOUR_GRAPH_LOCATION'  # Values: 'global'
# job_id = 'YOUR_JOB_ID'            # Entity Reconciliation Job ID


def delete_entity_reconciliation_job_sample(
    project_id: str, location: str, job_id: str
) -> None:
    # Create a client
    client = ekg.EnterpriseKnowledgeGraphServiceClient()

    # The full resource name of the job
    # e.g. projects/{project_id}/locations/{location}/entityReconciliationJobs/{entity_reconciliation_job}
    name = client.entity_reconciliation_job_path(
        project=project_id, location=location, entity_reconciliation_job=job_id
    )

    # Initialize request argument(s)
    request = ekg.DeleteEntityReconciliationJobRequest(name=name)

    # Make the request
    client.delete_entity_reconciliation_job(request=request)

    print(f"Job: {name} successfully deleted")