יצירת מזהה מילון גדול בהתאמה אישית

במאמר הזה מוסבר איך ליצור מילונים גדולים בהתאמה אישית ולבנות אותם מחדש. הוא גם כולל מידע על תרחישי שגיאה שונים.

מתי כדאי לבחור מילון מותאם אישית גדול במקום מילון מותאם אישית רגיל

מזהים רגילים של מילונים מותאמים אישית מספיקים אם יש לכם עשרות אלפי מילים או ביטויים רגישים שאתם רוצים לסרוק בתוכן שלכם. אם יש לכם יותר מ-10,000 מונחים או אם רשימת המונחים משתנה לעיתים קרובות, כדאי ליצור מילון מותאם אישית גדול, שיכול לתמוך בעשרות מיליוני מונחים.

מה ההבדל בין מילונים מותאמים אישית גדולים לבין סוגי מידע מותאמים אישית אחרים

מילונים גדולים בהתאמה אישית שונים מסוגי מידע אחרים בהתאמה אישית בכך שלכל מילון גדול בהתאמה אישית יש שני רכיבים:

  • רשימה של ביטויים שאתם יוצרים ומגדירים. הרשימה מאוחסנת כקובץ טקסט ב-Cloud Storage או כעמוד בטבלה ב-BigQuery.
  • קובצי המילון, שנוצרים על ידי Sensitive Data Protection ומאוחסנים ב-Cloud Storage. קבצי מילון מורכבים מעותק של רשימת המונחים שלכם בתוספת מסנני בלום, שמסייעים בחיפוש ובהתאמה.

יצירת מילון גדול בהתאמה אישית

בקטע הזה מוסבר איך ליצור, לערוך ולבנות מחדש מילון גדול בהתאמה אישית.

יצירת רשימת מונחים

יוצרים רשימה שמכילה את כל המילים והביטויים שרוצים שמנגנון זיהוי סוג המידע החדש יחפש. מבצעים אחת מהפעולות הבאות:

  • ממקמים קובץ טקסט עם כל מילה או ביטוי בשורה נפרדת בקטגוריה של Cloud Storage.
  • מגדירים עמודה אחת בטבלה ב-BigQuery כמאגר למילים ולביטויים. כל רשומה צריכה להיות בשורה נפרדת בעמודה. אפשר להשתמש בטבלה ב-BigQuery קיימת, בתנאי שכל המילים והביטויים במילון נמצאים בעמודה אחת.

יכול להיות שתצליחו ליצור רשימת מונחים גדולה מדי לעיבוד על ידי הכלי Sensitive Data Protection. אם מופיעה הודעת שגיאה, אפשר לעיין בקטע פתרון בעיות שגיאה בהמשך המאמר.

יצירה של infoType מאוחסן

אחרי שיוצרים את רשימת המונחים, משתמשים ב-Sensitive Data Protection כדי ליצור מילון:

המסוף

  1. בקטגוריה של Cloud Storage, יוצרים תיקייה חדשה שבה Sensitive Data Protection ישמור את המילון שנוצר.

    הכלי Sensitive Data Protection יוצר תיקיות שמכילות את קובצי המילון במיקום שאתם מציינים.

  2. נכנסים לדף Create infoType במסוף Google Cloud .

    כניסה לדף Create infoType

  3. בקטע סוג, בוחרים באפשרות מילון גדול בהתאמה אישית.

  4. בשדה InfoType ID (מזהה InfoType), מזינים מזהה של InfoType מאוחסן.

    תשתמשו במזהה הזה כשמגדירים את עבודות הבדיקה והסרת הפרטים המזהים. אפשר להשתמש באותיות, במספרים, במקפים ובקווים תחתונים בשם.

  5. בשדה שם התצוגה של סוג המידע, מזינים שם לסוג המידע המאוחסן.

    אפשר להשתמש ברווחים ובסימני פיסוק בשם.

  6. בשדה תיאור, מזינים תיאור של מה שסוג המידע המאוחסן מגלה.

  7. בשדה סוג אחסון, בוחרים את המיקום של רשימת המונחים:

    • BigQuery: מזינים את מזהה הפרויקט, מזהה מערך הנתונים ומזהה הטבלה. בשדה Field name, מזינים את מזהה העמודה. אפשר להגדיר לכל היותר עמודה אחת מהטבלה.
    • Google Cloud Storage: מזינים את הנתיב לקובץ.
  8. בשדה Output bucket or folder (תיקייה או קטגוריה של פלט), מזינים את המיקום ב-Cloud Storage של התיקייה שיצרתם בשלב 1.

    Sensitive Data Protection נשמרות.

  9. לוחצים על יצירה.

מוצג סיכום של סוג המידע המאוחסן. כשמילון נוצר וסוג המידע החדש שמאוחסן מוכן לשימוש, הסטטוס של סוג המידע הוא Ready (מוכן).

C#

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class CreateStoredInfoTypes
{
    public static StoredInfoType Create(
        string projectId,
        string outputPath,
        string storedInfoTypeId)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Construct the stored infotype config by specifying the public table and 
        // cloud storage output path.
        var storedInfoTypeConfig = new StoredInfoTypeConfig
        {
            DisplayName = "Github Usernames",
            Description = "Dictionary of Github usernames used in commits.",
            LargeCustomDictionary = new LargeCustomDictionaryConfig
            {
                BigQueryField = new BigQueryField
                {
                    Table = new BigQueryTable
                    {
                        DatasetId = "samples",
                        ProjectId = "bigquery-public-data",
                        TableId = "github_nested"
                    },
                    Field = new FieldId
                    {
                        Name = "actor"
                    }
                },
                OutputPath = new CloudStoragePath
                {
                    Path = outputPath
                }
            },
        };

        // Construct the request.
        var request = new CreateStoredInfoTypeRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            Config = storedInfoTypeConfig,
            StoredInfoTypeId = storedInfoTypeId
        };

        // Call the API.
        StoredInfoType response = dlp.CreateStoredInfoType(request);

        // Inspect the response.
        Console.WriteLine($"Created the stored infotype at path: {response.Name}");

        return response;
    }
}

Go

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// createStoredInfoType creates a custom stored info type based on your input data.
func createStoredInfoType(w io.Writer, projectID, outputPath string) error {
	// projectId := "my-project-id"
	// outputPath := "gs://" + "your-bucket-name" + "path/to/directory"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the name you want to give the dictionary.
	displayName := "Github Usernames"

	// Specify a description of the dictionary.
	description := "Dictionary of GitHub usernames used in commits"

	// Specify the path to the location in a Cloud Storage
	// bucket to store the created dictionary.
	cloudStoragePath := &dlppb.CloudStoragePath{
		Path: outputPath,
	}

	// Specify your term list is stored in BigQuery.
	bigQueryField := &dlppb.BigQueryField{
		Table: &dlppb.BigQueryTable{
			ProjectId: "bigquery-public-data",
			DatasetId: "samples",
			TableId:   "github_nested",
		},
		Field: &dlppb.FieldId{
			Name: "actor",
		},
	}

	// Specify the configuration of the large custom dictionary.
	largeCustomDictionaryConfig := &dlppb.LargeCustomDictionaryConfig{
		OutputPath: cloudStoragePath,
		Source: &dlppb.LargeCustomDictionaryConfig_BigQueryField{
			BigQueryField: bigQueryField,
		},
	}

	// Specify the configuration for stored infoType.
	storedInfoTypeConfig := &dlppb.StoredInfoTypeConfig{
		DisplayName: displayName,
		Description: description,
		Type: &dlppb.StoredInfoTypeConfig_LargeCustomDictionary{
			LargeCustomDictionary: largeCustomDictionaryConfig,
		},
	}

	// Combine configurations into a request for the service.
	req := &dlppb.CreateStoredInfoTypeRequest{
		Parent:           fmt.Sprintf("projects/%s/locations/global", projectID),
		Config:           storedInfoTypeConfig,
		StoredInfoTypeId: "github-usernames",
	}

	// Send the request and receive response from the service.
	resp, err := client.CreateStoredInfoType(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "output: %v", resp.Name)
	return nil

}

Java

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.BigQueryField;
import com.google.privacy.dlp.v2.BigQueryTable;
import com.google.privacy.dlp.v2.CloudStoragePath;
import com.google.privacy.dlp.v2.CreateStoredInfoTypeRequest;
import com.google.privacy.dlp.v2.FieldId;
import com.google.privacy.dlp.v2.LargeCustomDictionaryConfig;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.StoredInfoType;
import com.google.privacy.dlp.v2.StoredInfoTypeConfig;
import java.io.IOException;

public class CreateStoredInfoType {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.

    //The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The path to the location in a GCS bucket to store the created dictionary.
    String outputPath = "gs://" + "your-bucket-name" + "path/to/directory";
    createStoredInfoType(projectId, outputPath);
  }

  // Creates a custom stored info type that contains GitHub usernames used in commits.
  public static void createStoredInfoType(String projectId, String outputPath)
      throws IOException {
    try (DlpServiceClient dlp = DlpServiceClient.create()) {

      // Optionally set a display name and a description.
      String displayName = "GitHub usernames";
      String description = "Dictionary of GitHub usernames used in commits";

      // The output path where the custom dictionary containing the GitHub usernames will be stored.
      CloudStoragePath cloudStoragePath =
          CloudStoragePath.newBuilder()
              .setPath(outputPath)
              .build();

      // The reference to the table containing the GitHub usernames.
      BigQueryTable table = BigQueryTable.newBuilder()
              .setProjectId("bigquery-public-data")
              .setDatasetId("samples")
              .setTableId("github_nested")
              .build();

      // The reference to the BigQuery field that contains the GitHub usernames.
      BigQueryField bigQueryField = BigQueryField.newBuilder()
              .setTable(table)
              .setField(FieldId.newBuilder().setName("actor").build())
              .build();

      LargeCustomDictionaryConfig largeCustomDictionaryConfig =
          LargeCustomDictionaryConfig.newBuilder()
              .setOutputPath(cloudStoragePath)
              .setBigQueryField(bigQueryField)
              .build();

      StoredInfoTypeConfig storedInfoTypeConfig = StoredInfoTypeConfig.newBuilder()
              .setDisplayName(displayName)
              .setDescription(description)
              .setLargeCustomDictionary(largeCustomDictionaryConfig)
              .build();

      // Combine configurations into a request for the service.
      CreateStoredInfoTypeRequest createStoredInfoType = CreateStoredInfoTypeRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setConfig(storedInfoTypeConfig)
              .setStoredInfoTypeId("github-usernames")
              .build();

      // Send the request and receive response from the service.
      StoredInfoType response = dlp.createStoredInfoType(createStoredInfoType);

      // Print the results.
      System.out.println("Created Stored InfoType: " + response.getName());
    }
  }
}

Node.js

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Import the required libraries
const dlp = require('@google-cloud/dlp');

// Create a DLP client
const dlpClient = new dlp.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = "your-project-id";

// The identifier for the stored infoType
// const infoTypeId = 'github-usernames';

// The path to the location in a Cloud Storage bucket to store the created dictionary
// const outputPath = 'cloud-bucket-path';

// The project ID the table is stored under
// This may or (for public datasets) may not equal the calling project ID
// const dataProjectId = 'my-project';

// The ID of the dataset to inspect, e.g. 'my_dataset'
// const datasetId = 'my_dataset';

// The ID of the table to inspect, e.g. 'my_table'
// const tableId = 'my_table';

// Field ID to be used for constructing dictionary
// const fieldName = 'field_name';

async function createStoredInfoType() {
  // The name you want to give the dictionary.
  const displayName = 'GitHub usernames';
  // A description of the dictionary.
  const description = 'Dictionary of GitHub usernames used in commits';

  // Specify configuration for the large custom dictionary
  const largeCustomDictionaryConfig = {
    outputPath: {
      path: outputPath,
    },
    bigQueryField: {
      table: {
        datasetId: datasetId,
        projectId: dataProjectId,
        tableId: tableId,
      },
      field: {
        name: fieldName,
      },
    },
  };

  // Stored infoType configuration that uses large custom dictionary.
  const storedInfoTypeConfig = {
    displayName: displayName,
    description: description,
    largeCustomDictionary: largeCustomDictionaryConfig,
  };

  // Construct the job creation request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    config: storedInfoTypeConfig,
    storedInfoTypeId: infoTypeId,
  };

  // Send the job creation request and process the response.
  const [response] = await dlpClient.createStoredInfoType(request);

  // Print results
  console.log(`InfoType stored successfully: ${response.name}`);
}
await createStoredInfoType();

PHP

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


use Google\Cloud\Dlp\V2\BigQueryField;
use Google\Cloud\Dlp\V2\BigQueryTable;
use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStoragePath;
use Google\Cloud\Dlp\V2\CreateStoredInfoTypeRequest;
use Google\Cloud\Dlp\V2\FieldId;
use Google\Cloud\Dlp\V2\LargeCustomDictionaryConfig;
use Google\Cloud\Dlp\V2\StoredInfoTypeConfig;

/**
 * Create a stored infoType.
 *
 * @param string $callingProjectId  The Google Cloud Project ID to run the API call under.
 * @param string $outputgcsPath     The path to the location in a Cloud Storage bucket to store the created dictionary.
 * @param string $storedInfoTypeId  The name of the custom stored info type.
 * @param string $displayName       The human-readable name to give the stored infoType.
 * @param string $description       A description for the stored infoType to be created.
 */
function create_stored_infotype(
    string $callingProjectId,
    string $outputgcsPath,
    string $storedInfoTypeId,
    string $displayName,
    string $description
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // The reference to the table containing the GitHub usernames.
    // The reference to the BigQuery field that contains the GitHub usernames.
    // Note: we have used public data
    $bigQueryField = (new BigQueryField())
        ->setTable((new BigQueryTable())
            ->setDatasetId('samples')
            ->setProjectId('bigquery-public-data')
            ->setTableId('github_nested'))
        ->setField((new FieldId())
            ->setName('actor'));

    $largeCustomDictionaryConfig = (new LargeCustomDictionaryConfig())
        // The output path where the custom dictionary containing the GitHub usernames will be stored.
        ->setOutputPath((new CloudStoragePath())
            ->setPath($outputgcsPath))
        ->setBigQueryField($bigQueryField);

    // Configure the StoredInfoType we want the service to perform.
    $storedInfoTypeConfig = (new StoredInfoTypeConfig())
        ->setDisplayName($displayName)
        ->setDescription($description)
        ->setLargeCustomDictionary($largeCustomDictionaryConfig);

    // Send the stored infoType creation request and process the response.
    $parent = "projects/$callingProjectId/locations/global";
    $createStoredInfoTypeRequest = (new CreateStoredInfoTypeRequest())
        ->setParent($parent)
        ->setConfig($storedInfoTypeConfig)
        ->setStoredInfoTypeId($storedInfoTypeId);
    $response = $dlp->createStoredInfoType($createStoredInfoTypeRequest);

    // Print results.
    printf('Successfully created Stored InfoType : %s', $response->getName());
}

Python

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def create_stored_infotype(
    project: str,
    stored_info_type_id: str,
    output_bucket_name: str,
) -> None:
    """Uses the Data Loss Prevention API to create stored infoType.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        stored_info_type_id: The identifier for large custom dictionary.
        output_bucket_name: The name of the bucket in Google Cloud Storage
            that would store the created dictionary.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Construct the stored infoType Configuration dictionary. This example creates
    # a stored infoType from a term list stored in a publicly available BigQuery
    # database (bigquery-public-data.samples.github_nested).
    # The database contains all GitHub usernames used in commits.
    stored_info_type_config = {
        "display_name": "GitHub usernames",
        "description": "Dictionary of GitHub usernames used in commits",
        "large_custom_dictionary": {
            "output_path": {"path": f"gs://{output_bucket_name}"},
            # We can either use bigquery field or gcs file as a term list input option.
            "big_query_field": {
                "table": {
                    "project_id": "bigquery-public-data",
                    "dataset_id": "samples",
                    "table_id": "github_nested",
                },
                "field": {"name": "actor"},
            },
        },
    }

    # Convert the project id into a full resource id.
    parent = f"projects/{project}/locations/global"

    # Call the API.
    response = dlp.create_stored_info_type(
        request={
            "parent": parent,
            "config": stored_info_type_config,
            "stored_info_type_id": stored_info_type_id,
        }
    )

    # Print the result
    print(f"Created Stored InfoType: {response.name}")

REST

  1. יוצרים תיקייה חדשה למילון בקטגוריה של Cloud Storage. הכלי Sensitive Data Protection יוצר תיקיות שמכילות את קובצי המילון במיקום שאתם מציינים.
  2. יישמרו.
  3. יוצרים את המילון באמצעות ה-method‏ storedInfoTypes.create. השיטה create מקבלת את הפרמטרים הבאים:
    • אובייקט StoredInfoTypeConfig שמכיל את ההגדרה של סוג המידע המאוחסן. היא כוללת:
      • description: תיאור המילון.
      • displayName: השם שרוצים לתת למילון.
      • LargeCustomDictionaryConfig: מכיל את ההגדרה של מילון מותאם אישית גדול. היא כוללת:
        • BigQueryField: הפרמטר הזה מצוין אם רשימת המונחים מאוחסנת ב-BigQuery. כולל הפניה לטבלה שבה הרשימה מאוחסנת, וגם לשדה שמכיל כל ביטוי במילון.
        • CloudStorageFileSet: הערך הזה מצוין אם רשימת המונחים מאוחסנת ב-Cloud Storage. כולל את כתובת ה-URL של מיקום המקור ב-Cloud Storage, בפורמט הבא: "gs://[PATH_TO_GS]". יש תמיכה בתווים כלליים לחיפוש.
        • outputPath: הנתיב למיקום בקטגוריה של Cloud Storage שבו יאוחסן המילון שנוצר.
    • storedInfoTypeId: המזהה של סוג המידע המאוחסן. משתמשים במזהה הזה כדי להתייחס לסוג המידע המאוחסן כשבונים אותו מחדש, מוחקים אותו או משתמשים בו בעבודת בדיקה או בעבודת הסרת פרטים מזהים. אם לא ממלאים את השדה הזה, המערכת יוצרת מזהה בשבילכם.

זוהי דוגמה ל-JSON שכששולחים אותו לשיטת storedInfoTypes.create, הוא יוצר סוג מידע מאוחסן חדש – ספציפית, גלאי מילון מותאם אישית גדול. בדוגמה הזו נוצר סוג מידע מאוחסן מרשימת מונחים שמאוחסנת במסד נתונים ב-BigQuery שזמין לציבור (bigquery-public-data.samples.github_nested). מסד הנתונים מכיל את כל שמות המשתמשים ב-GitHub שנעשה בהם שימוש בהתחייבויות. נתיב הפלט של המילון שנוצר מוגדר לקטגוריה של Cloud Storage בשם dlptesting, וסוג המידע המאוחסן נקרא github-usernames.

קלט JSON

POST https://dlp.googleapis.com/v2/projects/PROJECT_ID/storedInfoTypes

{
  "config":{
    "displayName":"GitHub usernames",
    "description":"Dictionary of GitHub usernames used in commits",
    "largeCustomDictionary":{
      "outputPath":{
        "path":"gs://[PATH_TO_GS]"
      },
      "bigQueryField":{
        "table":{
          "datasetId":"samples",
          "projectId":"bigquery-public-data",
          "tableId":"github_nested"
        }
      }
    }
  },
  "storedInfoTypeId":"github-usernames"
}

בנייה מחדש של המילון

כדי לעדכן את המילון, קודם מעדכנים את רשימת מונחי המקור, ואז מנחים את Sensitive Data Protection לבנות מחדש את ה-infoType המאוחסן.

  1. מעדכנים את רשימת מונחי המקור הקיימת ב-Cloud Storage או ב-BigQuery.

    מוסיפים, מסירים או משנים את המונחים או הצירופים לפי הצורך.

  2. כדי ליצור גרסה חדשה של סוג המידע המאוחסן, צריך 'לבנות אותו מחדש' באמצעות מסוף Google Cloud או באמצעות השיטה storedInfoTypes.patch.

    בנייה מחדש יוצרת גרסה חדשה של המילון, שמחליפה את המילון הישן.

כשבונים מחדש סוג מידע מאוחסן לגרסה חדשה, הגרסה הישנה נמחקת. בזמן ש-Sensitive Data Protection מעדכן את ה-infoType המאוחסן, הסטטוס שלו הוא pending. במהלך הזמן הזה, הגרסה הישנה של סוג המידע המאוחסן עדיין קיימת. כל הסריקות שתריצו בזמן שסוג המידע המאוחסן נמצא במצב 'בהמתנה' יפעלו באמצעות הגרסה הישנה של סוג המידע המאוחסן.

כדי לבנות מחדש את סוג המידע שמאוחסן:

המסוף

  1. מעדכנים ושומרים את רשימת המונחים ב-Cloud Storage או ב-BigQuery.
  2. במסוף Google Cloud , עוברים לרשימת סוגי המידע (infoType) שנשמרו.

    מעבר אל stored infoTypes

  3. לוחצים על המזהה של סוג המידע המאוחסן שרוצים לעדכן.

  4. בדף פרטים של סוג המידע, לוחצים על בנייה מחדש של הנתונים.

Sensitive Data Protection בונה מחדש את ה-infoType המאוחסן עם השינויים שביצעתם ברשימת מונחי המקור. אחרי שהסטטוס של infoType המאוחסן הוא Ready (מוכן), אפשר להשתמש בו. כל התבניות או הטריגרים של העבודות שמשתמשים ב-infoType המאוחסן ישתמשו אוטומטית בגרסה שנבנתה מחדש.

C#

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Cloud.Dlp.V2;
using Google.Protobuf.WellKnownTypes;

public class UpdateStoredInfoTypes
{
    public static StoredInfoType Update(
        string gcsFileUri,
        string storedInfoTypePath,
        string outputPath)
    {
        // Instantiate the client.
        var dlp = DlpServiceClient.Create();

        // Construct the stored infotype config. Here, we will change the source from bigquery table to GCS file.
        var storedConfig = new StoredInfoTypeConfig
        {
            LargeCustomDictionary = new LargeCustomDictionaryConfig
            {
                CloudStorageFileSet = new CloudStorageFileSet
                {
                    Url = gcsFileUri
                },
                OutputPath = new CloudStoragePath
                {
                    Path = outputPath
                }
            }
        };

        // Construct the request using the stored config by specifying the update mask object
        // which represent the path of field to be updated.
        var request = new UpdateStoredInfoTypeRequest
        {
            Config = storedConfig,
            Name = storedInfoTypePath,
            UpdateMask = new FieldMask
            {
                Paths =
                {
                    "large_custom_dictionary.cloud_storage_file_set.url"
                }
            }
        };

        // Call the API.
        StoredInfoType response = dlp.UpdateStoredInfoType(request);

        // Inspect the result.
        Console.WriteLine(response);
        return response;
    }
}

Go

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
	"google.golang.org/protobuf/types/known/fieldmaskpb"
)

// updateStoredInfoType uses the Data Loss Prevention API to update stored infoType
// detector by changing the source term list from one stored in Bigquery
// to one stored in Cloud Storage.
func updateStoredInfoType(w io.Writer, projectID, gcsUri, fileSetUrl, infoTypeId string) error {
	// projectId := "your-project-id"
	// gcsUri := "gs://" + "your-bucket-name" + "/path/to/your/file.txt"
	// fileSetUrl := "your-cloud-storage-file-set"
	// infoTypeId := "your-stored-info-type-id"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Set path in Cloud Storage.
	cloudStoragePath := &dlppb.CloudStoragePath{
		Path: gcsUri,
	}
	cloudStorageFileSet := &dlppb.CloudStorageFileSet{
		Url: fileSetUrl,
	}

	// Configuration for a custom dictionary created from a data source of any size
	largeCustomDictionaryConfig := &dlppb.LargeCustomDictionaryConfig{
		OutputPath: cloudStoragePath,
		Source: &dlppb.LargeCustomDictionaryConfig_CloudStorageFileSet{
			CloudStorageFileSet: cloudStorageFileSet,
		},
	}

	// Set configuration for stored infoTypes.
	storedInfoTypeConfig := &dlppb.StoredInfoTypeConfig{
		Type: &dlppb.StoredInfoTypeConfig_LargeCustomDictionary{
			LargeCustomDictionary: largeCustomDictionaryConfig,
		},
	}

	// Set mask to control which fields get updated.
	fieldMask := &fieldmaskpb.FieldMask{
		Paths: []string{"large_custom_dictionary.cloud_storage_file_set.url"},
	}
	// Construct the job creation request to be sent by the client.
	req := &dlppb.UpdateStoredInfoTypeRequest{
		Name:       fmt.Sprint("projects/" + projectID + "/storedInfoTypes/" + infoTypeId),
		Config:     storedInfoTypeConfig,
		UpdateMask: fieldMask,
	}

	// Use the client to send the API request.
	resp, err := client.UpdateStoredInfoType(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "output: %v", resp.Name)
	return nil
}

Java

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CloudStorageFileSet;
import com.google.privacy.dlp.v2.CloudStoragePath;
import com.google.privacy.dlp.v2.LargeCustomDictionaryConfig;
import com.google.privacy.dlp.v2.StoredInfoType;
import com.google.privacy.dlp.v2.StoredInfoTypeConfig;
import com.google.privacy.dlp.v2.StoredInfoTypeName;
import com.google.privacy.dlp.v2.UpdateStoredInfoTypeRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;

public class UpdateStoredInfoType {
  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The path to file in GCS bucket that holds a collection of words and phrases to be searched by
    // the new infoType detector.
    String filePath = "gs://" + "your-bucket-name" + "/path/to/your/file.txt";
    // The path to the location in a GCS bucket to store the created dictionary.
    String outputPath = "your-cloud-storage-file-set";
    // The name of the stored InfoType which is to be updated.
    String infoTypeId = "your-stored-info-type-id";
    updateStoredInfoType(projectId, filePath, outputPath, infoTypeId);
  }

  // Update the stored info type rebuilding the Custom dictionary.
  public static void updateStoredInfoType(
      String projectId, String filePath, String outputPath, String infoTypeId) 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 (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Set path in Cloud Storage.
      CloudStoragePath cloudStoragePath = CloudStoragePath.newBuilder().setPath(outputPath).build();
      CloudStorageFileSet cloudStorageFileSet =
          CloudStorageFileSet.newBuilder().setUrl(filePath).build();

      // Configuration for a custom dictionary created from a data source of any size
      LargeCustomDictionaryConfig largeCustomDictionaryConfig =
          LargeCustomDictionaryConfig.newBuilder()
              .setOutputPath(cloudStoragePath)
              .setCloudStorageFileSet(cloudStorageFileSet)
              .build();

      // Set configuration for stored infoTypes.
      StoredInfoTypeConfig storedInfoTypeConfig =
          StoredInfoTypeConfig.newBuilder()
              .setLargeCustomDictionary(largeCustomDictionaryConfig)
              .build();

      // Set mask to control which fields get updated.
      // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
      FieldMask fieldMask =
          FieldMask.newBuilder()
              .addPaths("large_custom_dictionary.cloud_storage_file_set.url")
              .build();

      // Construct the job creation request to be sent by the client.
      UpdateStoredInfoTypeRequest updateStoredInfoTypeRequest =
          UpdateStoredInfoTypeRequest.newBuilder()
              .setName(
                  StoredInfoTypeName.ofProjectStoredInfoTypeName(projectId, infoTypeId).toString())
              .setConfig(storedInfoTypeConfig)
              .setUpdateMask(fieldMask)
              .build();

      // Send the job creation request and process the response.
      StoredInfoType response = dlp.updateStoredInfoType(updateStoredInfoTypeRequest);

      // Print the results.
      System.out.println("Updated stored InfoType successfully: " + response.getName());
    }
  }
}

Node.js

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Import the required libraries
const dlp = require('@google-cloud/dlp');

// Create a DLP client
const dlpClient = new dlp.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = "your-project-id";

// The identifier for the stored infoType
// const infoTypeId = 'github-usernames';

// The path to the location in a Cloud Storage bucket to store the created dictionary
// const outputPath = 'cloud-bucket-path';

// Path of file containing term list
// const cloudStorageFileSet = 'gs://[PATH_TO_GS]';

async function updateStoredInfoType() {
  // Specify configuration of the large custom dictionary including cloudStorageFileSet and outputPath
  const largeCustomDictionaryConfig = {
    outputPath: {
      path: outputPath,
    },
    cloudStorageFileSet: {
      url: fileSetUrl,
    },
  };

  // Construct the job creation request to be sent by the client.
  const updateStoredInfoTypeRequest = {
    name: `projects/${projectId}/storedInfoTypes/${infoTypeId}`,
    config: {
      largeCustomDictionary: largeCustomDictionaryConfig,
    },
    updateMask: {
      paths: ['large_custom_dictionary.cloud_storage_file_set.url'],
    },
  };

  // Send the job creation request and process the response.
  const [response] = await dlpClient.updateStoredInfoType(
    updateStoredInfoTypeRequest
  );

  // Print the results.
  console.log(`InfoType updated successfully: ${JSON.stringify(response)}`);
}
await updateStoredInfoType();

PHP

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\CloudStorageFileSet;
use Google\Cloud\Dlp\V2\CloudStoragePath;
use Google\Cloud\Dlp\V2\LargeCustomDictionaryConfig;
use Google\Cloud\Dlp\V2\StoredInfoTypeConfig;
use Google\Cloud\Dlp\V2\UpdateStoredInfoTypeRequest;
use Google\Protobuf\FieldMask;

/**
 * Rebuild/Update the stored infoType.
 *
 * @param string $callingProjectId  The Google Cloud Project ID to run the API call under.
 * @param string $gcsPath           The path to file in GCS bucket that holds a collection of words and phrases to be searched by the new infoType detector.
 * @param string $outputgcsPath     The path to the location in a Cloud Storage bucket to store the created dictionary.
 * @param string $storedInfoTypeId  The name of the stored InfoType which is to be updated.
 *
 */
function update_stored_infotype(
    string $callingProjectId,
    string $gcsPath,
    string $outputgcsPath,
    string $storedInfoTypeId
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Set path in Cloud Storage.
    $cloudStorageFileSet = (new CloudStorageFileSet())
        ->setUrl($gcsPath);

    // Configuration for a custom dictionary created from a data source of any size
    $largeCustomDictionaryConfig = (new LargeCustomDictionaryConfig())
        ->setOutputPath((new CloudStoragePath())
            ->setPath($outputgcsPath))
        ->setCloudStorageFileSet($cloudStorageFileSet);

    // Set configuration for stored infoTypes.
    $storedInfoTypeConfig = (new StoredInfoTypeConfig())
        ->setLargeCustomDictionary($largeCustomDictionaryConfig);

    // Send the stored infoType creation request and process the response.

    $name = "projects/$callingProjectId/locations/global/storedInfoTypes/" . $storedInfoTypeId;
    // Set mask to control which fields get updated.
    // Refer https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask for constructing the field mask paths.
    $fieldMask = (new FieldMask())
        ->setPaths([
            'large_custom_dictionary.cloud_storage_file_set.url'
        ]);

    // Run request
    $updateStoredInfoTypeRequest = (new UpdateStoredInfoTypeRequest())
        ->setName($name)
        ->setConfig($storedInfoTypeConfig)
        ->setUpdateMask($fieldMask);
    $response = $dlp->updateStoredInfoType($updateStoredInfoTypeRequest);

    // Print results
    printf('Successfully update Stored InforType : %s' . PHP_EOL, $response->getName());
}

Python

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def update_stored_infotype(
    project: str,
    stored_info_type_id: str,
    gcs_input_file_path: str,
    output_bucket_name: str,
) -> None:
    """Uses the Data Loss Prevention API to update stored infoType
    detector by changing the source term list from one stored in Bigquery
    to one stored in Cloud Storage.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        stored_info_type_id: The identifier of stored infoType which is to
            be updated.
        gcs_input_file_path: The url in the format <bucket>/<path_to_file>
            for the location of the source term list.
        output_bucket_name: The name of the bucket in Google Cloud Storage
            where large dictionary is stored.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Construct the stored infoType configuration dictionary.
    stored_info_type_config = {
        "large_custom_dictionary": {
            "output_path": {"path": f"gs://{output_bucket_name}"},
            "cloud_storage_file_set": {"url": f"gs://{gcs_input_file_path}"},
        }
    }

    # Set mask to control which fields get updated. For more details, refer
    # https://protobuf.dev/reference/protobuf/google.protobuf/#field-mask
    # for constructing the field mask paths.
    field_mask = {"paths": ["large_custom_dictionary.cloud_storage_file_set.url"]}

    # Convert the stored infoType id into a full resource id.
    stored_info_type_name = (
        f"projects/{project}/locations/global/storedInfoTypes/{stored_info_type_id}"
    )

    # Call the API.
    response = dlp.update_stored_info_type(
        request={
            "name": stored_info_type_name,
            "config": stored_info_type_config,
            "update_mask": field_mask,
        }
    )

    # Print the result
    print(f"Updated stored infoType successfully: {response.name}")

REST

עדכון רשימת המונחים

אם אתם מעדכנים רק את רשימת המונחים במילון הגדול המותאם אישית, הבקשה שלכם storedInfoTypes.patch צריכה לכלול רק את השדה name. מזינים את השם המלא של המשאב של סוג המידע המאוחסן שרוצים לבנות מחדש.

הדפוסים הבאים מייצגים ערכים תקינים בשדה name:

  • organizations/ORGANIZATION_ID/storedInfoTypes/STORED_INFOTYPE_ID
  • projects/PROJECT_ID/storedInfoTypes/STORED_INFOTYPE_ID

מחליפים את STORED_INFOTYPE_ID במזהה של סוג המידע המאוחסן שרוצים לבנות מחדש.

אם אתם לא יודעים מה המזהה של סוג המידע המאוחסן, אתם יכולים להפעיל את השיטה storedInfoTypes.list כדי לראות רשימה של כל סוגי המידע המאוחסנים הנוכחיים.

דוגמה

PATCH https://dlp.googleapis.com/v2/projects/PROJECT_ID/storedInfoTypes/STORED_INFOTYPE_ID

במקרה כזה, אין צורך בגוף הבקשה.

החלפת רשימת מונחי המקור

אפשר לשנות את רשימת מונחי המקור של סוג מידע מאוחסן, מאחסון ב-BigQuery לאחסון ב-Cloud Storage. משתמשים בשיטה storedInfoTypes.patch, אבל כוללים אובייקט CloudStorageFileSet ב-LargeCustomDictionaryConfig במקום אובייקט BigQueryField שבו השתמשתם קודם. לאחר מכן מגדירים את הפרמטר updateMask לפרמטר infoType שאוחסן ושבניתם מחדש, בפורמט FieldMask. לדוגמה, ב-JSON הבא מצוין בפרמטר updateMask שכתובת ה-URL של הנתיב ב-Cloud Storage עודכנה (large_custom_dictionary.cloud_storage_file_set.url):

דוגמה

PATCH https://dlp.googleapis.com/v2/projects/PROJECT_ID/storedInfoTypes/github-usernames

{
  "config":{
    "largeCustomDictionary":{
      "cloudStorageFileSet":{
        "url":"gs://[BUCKET_NAME]/[PATH_TO_FILE]"
      }
    }
  },
  "updateMask":"large_custom_dictionary.cloud_storage_file_set.url"
}

באופן דומה, אפשר להחליף את רשימת המונחים מרשימה שמאוחסנת בטבלה ב-BigQuery לרשימה שמאוחסנת בקטגוריה של Cloud Storage.

סריקת תוכן באמצעות מזהה מותאם אישית של מילון גדול

סריקת תוכן באמצעות מזהה מילון מותאם אישית גדול דומה לסריקת תוכן באמצעות כל מזהה אחר של סוג מידע מותאם אישית.

ההליך הזה מניח שיש לכם סוג מידע מאוחסן קיים. מידע נוסף זמין במאמר בנושא יצירת סוג מידע מאוחסן בדף הזה.

המסוף

אפשר להחיל מזהה מילון גדול בהתאמה אישית כשמבצעים את הפעולות הבאות:

בקטע Configure detection בדף, בקטע המשנה InfoTypes, אפשר לציין את סוג המידע של המילון הגדול בהתאמה אישית.

  1. לוחצים על ניהול סוגי מידע.
  2. בחלונית InfoTypes, לוחצים על הכרטיסייה Custom.
  3. לוחצים על הוספת סוג מידע בהתאמה אישית.
  4. בחלונית Add custom infoType (הוספת סוג מידע מותאם אישית):

    1. בשדה Type, בוחרים באפשרות Stored infoType.
    2. בשדה InfoType, מזינים שם לסוג המידע המותאם אישית. אפשר להשתמש באותיות, במספרים ובקווים תחתונים.
    3. בקטע סבירות, בוחרים את רמת הסבירות שרוצים להקצות כברירת מחדל לכל הממצאים שתואמים לסוג המידע המותאם אישית הזה. אפשר לכוונן עוד יותר את רמת הסבירות של ממצאים ספציפיים באמצעות כללים של מילות הפעלה.

      אם לא מציינים ערך ברירת מחדל, רמת הסבירות שמוגדרת כברירת מחדל היא VERY_LIKELY. מידע נוסף זמין במאמר בנושא הסתברות להתאמה.

    4. בקטע רגישות, בוחרים את רמת הרגישות שרוצים להקצות לכל הממצאים שתואמים לסוג המידע המותאם אישית הזה. אם לא מציינים ערך, רמות הרגישות של הממצאים האלה מוגדרות כHIGH.

      ציוני הרגישות משמשים בפרופילים של נתונים. כשמבצעים פרופיל לנתונים, Sensitive Data Protection משתמש בציוני הרגישות של ה-infoTypes כדי לחשב את רמת הרגישות.

    5. בשדה Stored infoType name, בוחרים את סוג המידע המאוחסן שרוצים לבסס עליו את סוג המידע החדש בהתאמה אישית.

    6. לוחצים על סיום כדי לסגור את החלונית הוספת סוג מידע בהתאמה אישית.

  5. אופציונלי: בכרטיסייה Built-in (מוכלל), עורכים את הבחירה של סוגי המידע המוכללים.

  6. לוחצים על סיום כדי לסגור את החלונית סוגי מידע.

    ה-infoType המותאם אישית יתווסף לרשימת ה-infoTypes ש-Sensitive Data Protection סורק. עם זאת, הבחירה הזו לא סופית עד שתשמרו את העבודה, את טריגר העבודה, את התבנית או את הגדרות הסריקה.

  7. כשמסיימים ליצור או לערוך את ההגדרה, לוחצים על שמירה.

C#

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


using System;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class InspectDataWithStoredInfotypes
{
    public static InspectContentResponse Inspect(
        string projectId,
        string storedInfotypePath,
        string text,
        InfoType infoType = null)
    {
        // Instantiate the dlp client.
        var dlp = DlpServiceClient.Create();

        // Construct the infotype if null.
        var infotype = infoType ?? new InfoType { Name = "GITHUB_LOGINS" };

        // Construct the inspect config using stored infotype.
        var inspectConfig = new InspectConfig
        {
            CustomInfoTypes =
            {
                new CustomInfoType
                {
                    InfoType = infotype,
                    StoredType = new StoredType { Name = storedInfotypePath }
                }
            },
            IncludeQuote = true
        };

        // Construct the request using inspect config.
        var request = new InspectContentRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            InspectConfig = inspectConfig,
            Item = new ContentItem { Value = text }
        };

        // Call the API.
        InspectContentResponse response = dlp.InspectContent(request);

        // Inspect the results.
        var findings = response.Result.Findings;
        Console.WriteLine($"Findings: {findings.Count}");
        foreach (var f in findings)
        {
            Console.WriteLine("\tQuote: " + f.Quote);
            Console.WriteLine("\tInfo type: " + f.InfoType.Name);
            Console.WriteLine("\tLikelihood: " + f.Likelihood);
        }

        return response;
    }
}

Go

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// inspectWithStoredInfotype inspects the given text using the specified stored infoType detector.
func inspectWithStoredInfotype(w io.Writer, projectID, infoTypeId, textToDeidentify string) error {
	// projectId := "your-project-id"
	// infoTypeId := "your-info-type-id"
	// textToDeidentify := "This commit was made by kewin2010"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return err
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the content to be inspected.
	contentItem := &dlppb.ContentItem{
		DataItem: &dlppb.ContentItem_Value{
			Value: textToDeidentify,
		},
	}

	// Specify the info type the inspection will look for.
	infoType := &dlppb.InfoType{
		Name: "GITHUB_LOGINS",
	}

	// Specify the stored info type the inspection will look for.
	storedType := &dlppb.StoredType{
		Name: infoTypeId,
	}

	customInfoType := &dlppb.CustomInfoType{
		InfoType: infoType,
		Type: &dlppb.CustomInfoType_StoredType{
			StoredType: storedType,
		},
	}

	// Specify how the content should be inspected.
	inspectConfig := &dlppb.InspectConfig{
		CustomInfoTypes: []*dlppb.CustomInfoType{
			customInfoType,
		},
		IncludeQuote: true,
	}

	// Construct the Inspect request to be sent by the client.
	req := &dlppb.InspectContentRequest{
		Parent:        fmt.Sprintf("projects/%s/locations/global", projectID),
		InspectConfig: inspectConfig,
		Item:          contentItem,
	}

	// Use the client to send the API request.
	resp, err := client.InspectContent(ctx, req)
	if err != nil {
		return err
	}

	// Process the results.
	fmt.Fprintf(w, "Findings: %d\n", len(resp.Result.Findings))
	for _, f := range resp.Result.Findings {
		fmt.Fprintf(w, "\tQuote: %s\n", f.Quote)
		fmt.Fprintf(w, "\tInfo type: %s\n", f.InfoType.Name)
		fmt.Fprintf(w, "\tLikelihood: %s\n", f.Likelihood)
	}
	return nil
}

Java

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.CustomInfoType;
import com.google.privacy.dlp.v2.Finding;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.InspectContentRequest;
import com.google.privacy.dlp.v2.InspectContentResponse;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.ProjectStoredInfoTypeName;
import com.google.privacy.dlp.v2.StoredType;
import java.io.IOException;

public class InspectWithStoredInfotype {

  public static void main(String[] args) throws IOException {
    // TODO(developer): Replace these variables before running the sample.
    // The Google Cloud project id to use as a parent resource.
    String projectId = "your-project-id";
    // The sample assumes that you have an existing stored infoType.
    // To create a stored InfoType refer:
    // https://cloud.google.com/dlp/docs/creating-stored-infotypes#create-storedinfotye 
    String storedInfoTypeId = "your-info-type-id";
    // The string to de-identify.
    String textToInspect =
        "My phone number is (223) 456-7890 and my email address is gary@example.com.";
    inspectWithStoredInfotype(projectId, storedInfoTypeId, textToInspect);
  }

  //  Inspects the given text using the specified stored infoType detector.
  public static void inspectWithStoredInfotype(
      String projectId, String storedInfoTypeId, String textToInspect) 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 (DlpServiceClient dlp = DlpServiceClient.create()) {

      // Specify the content to be inspected.
      ContentItem contentItem = ContentItem.newBuilder().setValue(textToInspect).build();

      InfoType infoType = InfoType.newBuilder().setName("STORED_TYPE").build();

      // Reference to the existing StoredInfoType to inspect the data.
      StoredType storedType = StoredType.newBuilder()
              .setName(ProjectStoredInfoTypeName.of(projectId, storedInfoTypeId).toString())
              .build();

      CustomInfoType customInfoType =
          CustomInfoType.newBuilder().setInfoType(infoType).setStoredType(storedType).build();

      // Construct the configuration for the Inspect request.
      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addCustomInfoTypes(customInfoType)
              .setIncludeQuote(true)
              .build();

      // Construct the Inspect request to be sent by the client.
      InspectContentRequest inspectContentRequest =
          InspectContentRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setInspectConfig(inspectConfig)
              .setItem(contentItem)
              .build();

      // Use the client to send the API request.
      InspectContentResponse response = dlp.inspectContent(inspectContentRequest);

      // Parse the response and process results.
      System.out.println("Findings: " + "" + response.getResult().getFindingsCount());
      for (Finding f : response.getResult().getFindingsList()) {
        System.out.println("\tQuote: " + f.getQuote());
        System.out.println("\tInfoType: " + f.getInfoType().getName());
        System.out.println("\tLikelihood: " + f.getLikelihood() + "\n");
      }
    }
  }
}

Node.js

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// The project ID to run the API call under.
// const projectId = 'your-project-id';

// The custom info-type id created and stored in the bucket.
// const infoTypeId = 'your-info-type-id';

// The string to inspect.
// const string = 'My phone number is (223) 456-7890 and my email address is gary@example.com.';

async function inspectWithStoredInfotype() {
  // Reference to the existing StoredInfoType to inspect the data.
  const customInfoType = {
    infoType: {
      name: 'GITHUB_LOGINS',
    },
    storedType: {
      name: infoTypeId,
    },
  };

  // Construct the configuration for the Inspect request.
  const inspectConfig = {
    customInfoTypes: [customInfoType],
    includeQuote: true,
  };

  // Construct the Inspect request to be sent by the client.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    inspectConfig: inspectConfig,
    item: {
      value: string,
    },
  };
  // Run request
  const [response] = await dlp.inspectContent(request);

  // Print Findings
  const findings = response.result.findings;
  if (findings.length > 0) {
    console.log(`Findings: ${findings.length}\n`);
    findings.forEach(finding => {
      console.log(`InfoType: ${finding.infoType.name}`);
      console.log(`\tQuote: ${finding.quote}`);
      console.log(`\tLikelihood: ${finding.likelihood} \n`);
    });
  } else {
    console.log('No findings.');
  }
}
await inspectWithStoredInfotype();

PHP

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\CustomInfoType;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\InspectContentRequest;
use Google\Cloud\Dlp\V2\Likelihood;
use Google\Cloud\Dlp\V2\StoredType;

/**
 * Inspect with stored infoType.
 * Scan content using a large custom dictionary detector.
 *
 * @param string $projectId             The Google Cloud Project ID to run the API call under.
 * @param string $storedInfoTypeName    The name of the stored infotype whose This value must be in the format
 * projects/projectName/(locations/locationId)/storedInfoTypes/storedInfoTypeName.
 * @param string $textToInspect         The string to inspect.
 */
function inspect_with_stored_infotype(
    string $projectId,
    string $storedInfoTypeName,
    string $textToInspect
): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    $parent = "projects/$projectId/locations/global";

    // Specify the content to be inspected.
    $item = (new ContentItem())
        ->setValue($textToInspect);

    // Reference to the existing StoredInfoType to inspect the data.
    $customInfoType = (new CustomInfoType())
        ->setInfoType((new InfoType())
            ->setName('STORED_TYPE'))
        ->setStoredType((new StoredType())
            ->setName($storedInfoTypeName));

    // Construct the configuration for the Inspect request.
    $inspectConfig = (new InspectConfig())
        ->setCustomInfoTypes([$customInfoType])
        ->setIncludeQuote(true);

    // Run request.
    $inspectContentRequest = (new InspectContentRequest())
        ->setParent($parent)
        ->setInspectConfig($inspectConfig)
        ->setItem($item);
    $response = $dlp->inspectContent($inspectContentRequest);

    // Print the results.
    $findings = $response->getResult()->getFindings();
    if (count($findings) == 0) {
        printf('No findings.' . PHP_EOL);
    } else {
        printf('Findings:' . PHP_EOL);
        foreach ($findings as $finding) {
            printf('  Quote: %s' . PHP_EOL, $finding->getQuote());
            printf('  Info type: %s' . PHP_EOL, $finding->getInfoType()->getName());
            printf('  Likelihood: %s' . PHP_EOL, Likelihood::name($finding->getLikelihood()));
        }
    }
}

Python

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

כדי לבצע אימות ב-Sensitive Data Protection, צריך להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לסביבת פיתוח מקומית.

import google.cloud.dlp


def inspect_with_stored_infotype(
    project: str,
    stored_info_type_id: str,
    content_string: str,
) -> None:
    """Uses the Data Loss Prevention API to inspect/scan content using stored
    infoType.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        content_string: The string to inspect.
        stored_info_type_id: The identifier of stored infoType used to inspect.
    """

    # Instantiate a client.
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert stored infoType id into full resource id
    stored_type_name = f"projects/{project}/storedInfoTypes/{stored_info_type_id}"

    # Construct a custom info type dictionary using stored infoType.
    custom_info_types = [
        {
            "info_type": {"name": "STORED_TYPE"},
            "stored_type": {
                "name": stored_type_name,
            },
        }
    ]

    # Construct the inspection configuration dictionary.
    inspect_config = {
        "custom_info_types": custom_info_types,
        "include_quote": True,
    }

    # Construct the `item` to be inspected using stored infoType.
    item = {"value": content_string}

    # Convert the project id into a full resource id.
    parent = f"projects/{project}/locations/global"

    # Call the API.
    response = dlp.inspect_content(
        request={
            "parent": parent,
            "inspect_config": inspect_config,
            "item": item,
        }
    )

    # Print out the results.
    if response.result.findings:
        for finding in response.result.findings:
            print(f"Quote: {finding.quote}")
            print(f"Info type: {finding.info_type.name}")
            print(f"Likelihood: {finding.likelihood}")
    else:
        print("No findings.")

REST

בדוגמה הבאה, הטקסט שצוין נסרק באמצעות גלאי מסוג infoType מאוחסן שצוין, כששולחים אותו לשיטה content.inspect. הפרמטר infoType נדרש כי לכל סוגי המידע המותאמים אישית צריך להיות שם שלא מתנגש עם סוגי מידע מובנים או עם סוגי מידע מותאמים אישית אחרים. הפרמטר storedType מכיל את הנתיב המלא של המשאב של סוג המידע המאוחסן.

קלט JSON

POST https://dlp.googleapis.com/v2/projects/PROJECT_ID/content:inspect

{
  "inspectConfig":{
    "customInfoTypes":[
      {
        "infoType":{
          "name":"GITHUB_LOGINS"
        },
        "storedType":{
          "name":"projects/PROJECT_ID/storedInfoTypes/github-logins"
        }
      }
    ]
  },
  "item":{
    "value":"The commit was made by githubuser."
  }
}

פתרון בעיות במקרה של שגיאות

אם מופיעה שגיאה כשמנסים ליצור סוג מידע מאוחסן מרשימת מונחים שמאוחסנת ב-Cloud Storage, יכולות להיות לכך הסיבות הבאות:

  • הגעת למגבלה עליונה על סוגי מידע מאוחסנים. בהתאם לבעיה, יש כמה פתרונות עקיפים:
    • אם נתקלתם במגבלה העליונה של קובץ קלט יחיד ב-Cloud Storage‏ (200MB), נסו לפצל את הקובץ לכמה קבצים. אפשר להשתמש בכמה קבצים כדי להרכיב מילון מותאם אישית אחד, כל עוד הגודל הכולל של כל הקבצים לא עולה על 1GB.
    • ב-BigQuery אין את אותן מגבלות כמו ב-Cloud Storage. אפשר להעביר את התנאים לטבלה ב-BigQuery. הגודל המקסימלי של עמודה של מילון מותאם אישית ב-BigQuery הוא 1GB, ומספר השורות המקסימלי הוא 5,000,000.
    • אם קובץ רשימת המונחים חורג מכל המגבלות הרלוונטיות לרשימות של מונחי מקור, צריך לפצל את קובץ רשימת המונחים לכמה קבצים וליצור מילון לכל קובץ. לאחר מכן, יוצרים עבודת סריקה נפרדת לכל מילון.
  • אחד או יותר מהמונחים שלכם לא מכילים לפחות אות אחת או מספר אחד. הכלי Sensitive Data Protection לא יכול לסרוק מונחים שמורכבים רק מרווחים או מסמלים. צריך להוסיף לפחות אות אחת או מספר אחד. בודקים את רשימת המונחים כדי לראות אם יש בה מונחים כאלה, ואז מתקנים או מוחקים אותם.
  • רשימת המונחים שלך מכילה ביטוי עם יותר מדי 'רכיבים'. רכיב בהקשר הזה הוא רצף רציף שמכיל רק אותיות, רק מספרים או רק תווים שהם לא אותיות ולא ספרות, כמו רווחים או סמלים. צריך לבדוק את רשימת המונחים ולראות אם יש בה מונחים כאלה, ואז לתקן או למחוק אותם.
  • לסוכן השירות של Sensitive Data Protection אין גישה לנתוני המקור של המילון או לקטגוריה של Cloud Storage שבה מאוחסנים קובצי המילון. כדי לפתור את הבעיה הזו, צריך להעניק לסוכן השירות של Sensitive Data Protection את התפקיד Storage Admin ‏ (roles/storage.admin) או את התפקידים BigQuery Data Owner ‏ (roles/bigquery.dataOwner) ו-BigQuery Job User ‏(roles/bigquery.jobUser).

סקירה כללית על ממשקי API

חובה ליצור סוג מידע מאוחסן אם יוצרים מזהה מילון גדול בהתאמה אישית.

ב-Sensitive Data Protection, סוג מידע מאוחסן מיוצג על ידי האובייקט StoredInfoType. הוא מורכב מהאובייקטים הקשורים הבאים:

  • StoredInfoTypeVersion כולל את התאריך והשעה של היצירה ואת חמש הודעות השגיאה האחרונות שהתרחשו כשנוצרה הגרסה הנוכחית.

    • StoredInfoTypeConfig מכיל את ההגדרה של סוג המידע המאוחסן, כולל השם והתיאור שלו. אם המילון המותאם אישית גדול, type צריך להיות LargeCustomDictionaryConfig.

      • LargeCustomDictionaryConfig מציין את שני הדברים הבאים:
        • המיקום ב-Cloud Storage או ב-BigQuery שבו מאוחסנת רשימת הביטויים.
        • המיקום ב-Cloud Storage שבו יישמרו קובצי המילון שנוצרו.
    • StoredInfoTypeState מכיל את המצב של הגרסה העדכנית ביותר ושל גרסאות ממתינות של ה-infoType המאוחסן. פרטי המצב כוללים מידע על סוג המידע המאוחסן, למשל אם הוא נבנה מחדש, מוכן לשימוש או לא תקין.

פרטים ספציפיים לגבי התאמה במילון

בהמשך מוסבר איך התכונה Sensitive Data Protection מתאימה מילים וביטויים במילון. הנקודות האלה רלוונטיות גם למילונים רגילים בהתאמה אישית וגם למילונים גדולים בהתאמה אישית:

  • המילים במילון הן לא תלויות-רישיות. אם המילון שלכם כולל את Abby, הוא יתאים ל-abby, ל-ABBY, ל-Abby וכן הלאה.
  • כל התווים – במילונים או בתוכן שצריך לסרוק – מלבד אותיות, ספרות ותווים אלפביתיים אחרים שנכללים ב-Basic Multilingual Plane של Unicode, נחשבים לרווחים כשסורקים התאמות. אם המילון שלכם סורק את Abby Abernathy, הוא יתאים ל-abby abernathy, ל-Abby, Abernathy, ל-Abby (ABERNATHY) וכן הלאה.
  • התווים שמקיפים התאמה כלשהי צריכים להיות מסוג שונה (אותיות או ספרות) מהתווים הסמוכים בתוך המילה. אם המילון שלכם סורק את Abi, הוא יתאים לשלוש התווים הראשונים של Abi904, אבל לא של Abigail.
  • מילים במילון שמכילות תווים במישור הרב-לשוני המשני של תקן Unicode עשויות להניב ממצאים לא צפויים. דוגמאות לתווים כאלה: סמלי אמוג'י, סמלים מדעיים וכתבים היסטוריים.

ההגדרה של אותיות, ספרות ותווים אלפביתיים אחרים היא כדלקמן:

  • אותיות: תווים עם קטגוריות כלליות Lu,‏ Ll,‏ Lt,‏ Lm או Lo במפרט Unicode
  • ספרות: תווים עם קטגוריה כללית Nd במפרט Unicode
  • תווים אלפביתיים אחרים: תווים עם קטגוריה כללית Nl במפרט Unicode או עם מאפיין תורם Other_Alphabetic כפי שמוגדר בתקן Unicode

כדי ליצור, לערוך או למחוק סוג מידע מאוחסן, משתמשים בשיטות הבאות:

  • storedInfoTypes.create: יוצר סוג מידע מאוחסן חדש בהתאם ל-StoredInfoTypeConfig שאתם מציינים.
  • storedInfoTypes.patch: בנייה מחדש של infoType מאוחסן עם StoredInfoTypeConfig חדש שאתם מציינים. אם לא מצוין אף אחד, השיטה הזו יוצרת גרסה חדשה של סוג המידע המאוחסן עם StoredInfoTypeConfig קיים.
  • storedInfoTypes.get: מאחזר את StoredInfoTypeConfig ואת כל הגרסאות בהמתנה של סוג המידע המאוחסן שצוין.
  • storedInfoTypes.list: מציג רשימה של כל סוגי המידע הנוכחיים שמאוחסנים.
  • storedInfoTypes.delete: מחיקת סוג המידע המאוחסן שצוין.