מחיקת משאבים

אתם יכולים למחוק משאבים של תמונות רפרנס, מוצרים או קבוצות מוצרים שנוצרו על ידי ה-API.

מחיקת משאב בודד

מחיקת תמונת רפרנס

אתם יכולים למחוק תמונת רפרנס שמשויכת למוצר.

אחרי בקשת הפעולה, התמונות מסומנות למחיקה, אבל הן יישארו במוצר עד לפעם הבאה שהוא יתווסף לאינדקס.

הפעולה הזו לא מוחקת את קובצי התמונות עצמם ב-Cloud Storage. רק ההפניה לתמונה תוסר מהמוצר.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION_ID: מזהה מיקום תקין. מזהי המיקום התקינים הם: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • ‫PRODUCT_ID: המזהה של המוצר שמשויך לתמונת רפרנס. המזהה הזה מוגדר באופן אקראי או מצוין על ידי המשתמש בזמן יצירת המוצר.
  • ‫IMAGE_ID: המזהה של משאב התמונה לטירגוט.

ה-method של ה-HTTP וכתובת ה-URL:

DELETE https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}

Go

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Go API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// deleteReferenceImage deletes a reference image from a product.
func deleteReferenceImage(w io.Writer, projectID string, location string, productID string, referenceImageID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.DeleteReferenceImageRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/products/%s/referenceImages/%s", projectID, location, productID, referenceImageID),
	}

	if err = c.DeleteReferenceImage(ctx, req); err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}

	fmt.Fprintf(w, "Reference image deleted from product.\n")

	return nil
}

Java

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Java API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Delete a reference image.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param referenceImageId - Id of the image.
 * @throws IOException - on I/O errors.
 */
public static void deleteReferenceImage(
    String projectId, String computeRegion, String productId, String referenceImageId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the reference image.
    String formattedName =
        ImageName.format(projectId, computeRegion, productId, referenceImageId);
    // Delete the reference image.
    client.deleteReferenceImage(formattedName);
    System.out.println("Reference image deleted from product.");
  }
}

Node.js

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Node.js API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

const vision = require('@google-cloud/vision');

const client = new vision.ProductSearchClient();

async function deleteReferenceImage() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';
  // const referenceImageId = 'Id of the reference image';

  const formattedName = client.referenceImagePath(
    projectId,
    location,
    productId,
    referenceImageId
  );

  const request = {
    name: formattedName,
  };

  await client.deleteReferenceImage(request);
  console.log('Reference image deleted from product.');
}
deleteReferenceImage();

Python

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Python API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision

def delete_reference_image(project_id, location, product_id, reference_image_id):
    """Delete a reference image.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        reference_image_id: Id of the reference image.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the reference image.
    reference_image_path = client.reference_image_path(
        project=project_id,
        location=location,
        product=product_id,
        reference_image=reference_image_id,
    )

    # Delete the reference image.
    client.delete_reference_image(name=reference_image_path)
    print("Reference image deleted from product.")

שפות נוספות

‫C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו במאמרי העזרה של Vision API Product Search ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-Ruby.

מחיקת מוצר

אתם יכולים למחוק מוצר שמשויך לפרויקט ספציפי.

מחיקת מוצר גורמת למחיקת התמונות המשויכות אליו.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION_ID: מזהה מיקום תקין. מזהי המיקום התקינים הם: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • ‫PRODUCT_ID: המזהה של המוצר שמשויך לתמונת רפרנס. המזהה הזה מוגדר באופן אקראי או מצוין על ידי המשתמש בזמן יצירת המוצר.

ה-method של ה-HTTP וכתובת ה-URL:

DELETE https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}

Go

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Go API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// deleteProduct deletes a product.
func deleteProduct(w io.Writer, projectID string, location string, productID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.DeleteProductRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

	if err = c.DeleteProduct(ctx, req); err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}

	fmt.Fprintf(w, "Product deleted.\n")

	return nil
}

Java

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Java API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Delete the product and all its reference images.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @throws IOException - on I/O errors.
 */
public static void deleteProduct(String projectId, String computeRegion, String productId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product.
    String formattedName = ProductName.format(projectId, computeRegion, productId);

    // Delete a product.
    client.deleteProduct(formattedName);
    System.out.println("Product deleted.");
  }
}

Node.js

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Node.js API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function deleteProduct() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productId = 'Id of the product';

  // Resource path that represents full path to the product.
  const productPath = client.productPath(projectId, location, productId);

  await client.deleteProduct({name: productPath});
  console.log('Product deleted.');
}
deleteProduct();

Python

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Python API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

def delete_product(project_id, location, product_id):
    """Delete the product and all its reference images.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product.
    product_path = client.product_path(
        project=project_id, location=location, product=product_id
    )

    # Delete a product.
    client.delete_product(name=product_path)
    print("Product deleted.")

שפות נוספות

‫C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו במאמרי העזרה של Vision API Product Search ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-Ruby.

מחיקה של קבוצת מוצרים

אפשר גם למחוק קבוצת מוצרים.

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

הפעולה הזו לא מוחקת את קובצי התמונות עצמם ב-Cloud Storage. משאבי ReferenceImage שנוצרו על ידי ה-API לא יוסרו.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION_ID: מזהה מיקום תקין. מזהי המיקום התקינים הם: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • ‫PRODUCT_SET_ID: המזהה של קבוצת המוצרים שרוצים להפעיל עליה את הפעולה.

ה-method של ה-HTTP וכתובת ה-URL:

DELETE https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X DELETE \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method DELETE `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id" | Select-Object -Expand Content

אתם אמורים לקבל תגובת JSON שדומה לזו:

{}

Go

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Go API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// deleteProductSet deletes a product set.
func deleteProductSet(w io.Writer, projectID string, location string, productSetID string) error {
	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.DeleteProductSetRequest{
		Name: fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
	}

	if err = c.DeleteProductSet(ctx, req); err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}

	fmt.Fprintln(w, "Product set deleted.")

	return nil
}

Java

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Java API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

/**
 * Delete a product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productSetId - Id of the product set.
 * @throws IOException - on I/O errors.
 */
public static void deleteProductSet(String projectId, String computeRegion, String productSetId)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // Get the full path of the product set.
    String formattedName = ProductSetName.format(projectId, computeRegion, productSetId);
    // Delete the product set.
    client.deleteProductSet(formattedName);
    System.out.println(String.format("Product set deleted"));
  }
}

Node.js

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Node.js API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function deleteProductSet() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productSetId = 'Id of the product set';

  // Resource path that represents full path to the product set.
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  await client.deleteProductSet({name: productSetPath});
  console.log('Product set deleted.');
}
deleteProductSet();

Python

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Python API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision

def delete_product_set(project_id, location, product_set_id):
    """Delete a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
    """
    client = vision.ProductSearchClient()

    # Get the full path of the product set.
    product_set_path = client.product_set_path(
        project=project_id, location=location, product_set=product_set_id
    )

    # Delete the product set.
    client.delete_product_set(name=product_set_path)
    print("Product set deleted.")

שפות נוספות

‫C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו במאמרי העזרה של Vision API Product Search ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-Ruby.

מחיקת משאבים באצווה

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

  • כל המוצרים בקבוצת מוצרים ספציפית
  • כל המוצרים שלא שייכים לאף קבוצת מוצרים

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

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

מחיקת מוצרים מקבוצת מוצרים

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

כל המוצרים בקבוצת המוצרים יימחקו גם אם הם שייכים לקבוצות מוצרים אחרות.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION_ID: מזהה מיקום תקין. מזהי המיקום התקינים הם: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • ‫PRODUCT_SET_ID: המזהה של קבוצת המוצרים שרוצים להפעיל עליה את הפעולה.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products:purge

גוף בקשת JSON:

{
  "force": "true",
  "productSetPurgeConfig": {
    "productSetId": "product-set-id"
  }
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products:purge"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products:purge" | Select-Object -Expand Content

הבקשה הזו מתחילה פעולה ממושכת. תגובת ה-JSON מכילה מידע על הפעולה הממושכת הזו:

{
"name": "projects/project-id/locations/location-id/operations/bc4e1d412863e626"
}

במקרה הזה, operation-id הוא bc4e1d412863e626.

אפשר לעקוב אחרי ההתקדמות של הפעולה הזו באמצעות operation-id. לדוגמה, כדי לקבל את סטטוס הפעולה, ראו קבלת סטטוס הפעולה.

Go

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Go API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// purgeProductsInProductSet deletes all products in a product set.
func purgeProductsInProductSet(w io.Writer, projectID string, location string, productSetID string) error {
	// projectID := "your-gcp-project-id"
	// location := "us-west1"
	// productSetID := "sampleProductSetID"

	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.PurgeProductsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Target: &visionpb.PurgeProductsRequest_ProductSetPurgeConfig{
			ProductSetPurgeConfig: &visionpb.ProductSetPurgeConfig{
				ProductSetId: productSetID,
			},
		},
		Force: true,
	}

	// The purge operation is async.
	op, err := c.PurgeProducts(ctx, req)
	if err != nil {
		return fmt.Errorf("PurgeProducts: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Deleted products in product set.\n")

	return nil
}

Java

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Java API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.BatchOperationMetadata;
import com.google.cloud.vision.v1.LocationName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.ProductSetPurgeConfig;
import com.google.cloud.vision.v1.PurgeProductsRequest;
import com.google.protobuf.Empty;
import java.util.concurrent.TimeUnit;

public class PurgeProductsInProductSet {

  // Delete all products in a product set.
  public static void purgeProductsInProductSet(
      String projectId, String location, String productSetId) throws Exception {

    // String projectId = "YOUR_PROJECT_ID";
    // String location = "us-central1";
    // String productSetId = "YOUR_PRODUCT_SET_ID";
    // boolean force = true;

    try (ProductSearchClient client = ProductSearchClient.create()) {

      String parent = LocationName.format(projectId, location);
      ProductSetPurgeConfig productSetPurgeConfig =
          ProductSetPurgeConfig.newBuilder().setProductSetId(productSetId).build();

      PurgeProductsRequest request =
          PurgeProductsRequest.newBuilder()
              .setParent(parent)
              .setProductSetPurgeConfig(productSetPurgeConfig)
              // The operation is irreversible and removes multiple products.
              // The user is required to pass in force=True to actually perform the
              // purge.
              // If force is not set to True, the service raises an exception.
              .setForce(true)
              .build();

      OperationFuture<Empty, BatchOperationMetadata> response = client.purgeProductsAsync(request);
      response.getPollingFuture().get(180, TimeUnit.SECONDS);

      System.out.println("Products removed from product set.");
    }
  }
}

Node.js

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Node.js API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function purgeProductsInProductSet() {
  // Deletes all products in a product set.

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';
  // const productSetId = 'Id of the product set';

  const formattedParent = client.locationPath(projectId, location);
  const purgeConfig = {productSetId: productSetId};

  // The operation is irreversible and removes multiple products.
  // The user is required to pass in force=true to actually perform the purge.
  // If force is not set to True, the service raises an error.
  const force = true;

  try {
    const [operation] = await client.purgeProducts({
      parent: formattedParent,
      productSetPurgeConfig: purgeConfig,
      force: force,
    });
    await operation.promise();
    console.log('Products removed from product set.');
  } catch (err) {
    console.log(err);
  }
}
purgeProductsInProductSet();

Python

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Python API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision

def purge_products_in_product_set(project_id, location, product_set_id, force):
    """Delete all products in a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
        force: Perform the purge only when force is set to True.
    """
    client = vision.ProductSearchClient()

    parent = f"projects/{project_id}/locations/{location}"

    product_set_purge_config = vision.ProductSetPurgeConfig(
        product_set_id=product_set_id
    )

    # The purge operation is async.
    operation = client.purge_products(
        request={
            "parent": parent,
            "product_set_purge_config": product_set_purge_config,
            # The operation is irreversible and removes multiple products.
            # The user is required to pass in force=True to actually perform the
            # purge.
            # If force is not set to True, the service raises an exception.
            "force": force,
        }
    )

    operation.result(timeout=500)

    print("Deleted products in product set.")

שפות נוספות

‫C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו במאמרי העזרה של Vision API Product Search ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-Ruby.

מחיקת מוצרים מיותמים

כדי למחוק את כל המוצרים שלא נמצאים בקבוצת מוצרים, צריך לציין את האפשרות הזו בבקשה.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION_ID: מזהה מיקום תקין. מזהי המיקום התקינים הם: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.

ה-method של ה-HTTP וכתובת ה-URL:

POST https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products:purge

גוף בקשת JSON:

{
  "force": "true",
  "deleteOrphanProducts": "true"
}

כדי לשלוח את הבקשה עליכם לבחור אחת מהאפשרויות הבאות:

curl

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products:purge"

PowerShell

שומרים את גוף הבקשה בקובץ בשם request.json ומריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products:purge" | Select-Object -Expand Content

הבקשה הזו מתחילה פעולה ממושכת. תגובת ה-JSON מכילה מידע על הפעולה הממושכת הזו:

{
"name": "projects/project-id/locations/location-id/operations/bc4e1d412863e626"
}

במקרה הזה, operation-id הוא bc4e1d412863e626.

אפשר לעקוב אחרי ההתקדמות של הפעולה הזו באמצעות operation-id. לדוגמה, כדי לקבל את סטטוס הפעולה, ראו קבלת סטטוס הפעולה.

Go

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Go API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	"cloud.google.com/go/vision/v2/apiv1/visionpb"
)

// purgeOrphanProducts deletes all products not in any product sets.
func purgeOrphanProducts(w io.Writer, projectID string, location string) error {
	// projectID := "your-gcp-project-id"
	// location := "us-west1"

	ctx := context.Background()
	c, err := vision.NewProductSearchClient(ctx)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	defer c.Close()

	req := &visionpb.PurgeProductsRequest{
		Parent: fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		Target: &visionpb.PurgeProductsRequest_DeleteOrphanProducts{
			DeleteOrphanProducts: true,
		},
		Force: true,
	}

	// The purge operation is async.
	op, err := c.PurgeProducts(ctx, req)
	if err != nil {
		return fmt.Errorf("NewProductSearchClient: %w", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

	if err := op.Wait(ctx); err != nil {
		return fmt.Errorf("Wait: %w", err)
	}

	fmt.Fprintf(w, "Orphan products deleted.\n")

	return nil
}

Java

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Java API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.BatchOperationMetadata;
import com.google.cloud.vision.v1.LocationName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.PurgeProductsRequest;
import com.google.protobuf.Empty;
import java.util.concurrent.TimeUnit;

public class PurgeProducts {

  // Delete the product and all its reference images.
  public static void purgeOrphanProducts(String projectId, String computeRegion) throws Exception {

    // String projectId = "YOUR_PROJECT_ID";
    // String computeRegion = "us-central1";
    // boolean force = true;

    try (ProductSearchClient client = ProductSearchClient.create()) {
      String parent = LocationName.format(projectId, computeRegion);

      // The purge operation is async.
      PurgeProductsRequest request =
          PurgeProductsRequest.newBuilder()
              .setDeleteOrphanProducts(true)
              // The operation is irreversible and removes multiple products.
              // The user is required to pass in force=True to actually perform the
              // purge.
              // If force is not set to True, the service raises an exception.
              .setForce(true)
              .setParent(parent)
              .build();

      OperationFuture<Empty, BatchOperationMetadata> response = client.purgeProductsAsync(request);
      response.getPollingFuture().get(180, TimeUnit.SECONDS);

      System.out.println("Orphan products deleted.");
    }
  }
}

Node.js

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Node.js API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

// Imports the Google Cloud client library
const vision = require('@google-cloud/vision');

// Creates a client
const client = new vision.ProductSearchClient();

async function purgeOrphanProducts() {
  // Deletes all products not in any product sets.

  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  // const projectId = 'Your Google Cloud project Id';
  // const location = 'A compute region name';

  const formattedParent = client.locationPath(projectId, location);

  // The operation is irreversible and removes multiple products.
  // The user is required to pass in force=true to actually perform the purge.
  // If force is not set to True, the service raises an error.
  const force = true;

  try {
    const [operation] = await client.purgeProducts({
      parent: formattedParent,
      deleteOrphanProducts: true,
      force: force,
    });
    await operation.promise();
    console.log('Orphan products deleted.');
  } catch (err) {
    console.log(err);
  }
}
purgeOrphanProducts();

Python

במאמר ספריות הלקוח של Vision API Product Search מוסבר איך להתקין את ספריית הלקוח ולהשתמש בה ב-Vision API Product Search. מידע נוסף מופיע במאמרי העזרה של Vision API Product Search Python API.

כדי לבצע אימות ב-Vision API Product Search, צריך להגדיר את Application Default Credentials. למידע נוסף, ראו הגדרת אימות לסביבת פיתוח מקומית.

from google.cloud import vision
from google.protobuf import field_mask_pb2 as field_mask

def purge_orphan_products(project_id, location, force):
    """Delete all products not in any product sets.
    Args:
        project_id: Id of the project.
        location: A compute region name.
    """
    client = vision.ProductSearchClient()

    parent = f"projects/{project_id}/locations/{location}"

    # The purge operation is async.
    operation = client.purge_products(
        request={
            "parent": parent,
            "delete_orphan_products": True,
            # The operation is irreversible and removes multiple products.
            # The user is required to pass in force=True to actually perform the
            # purge.
            # If force is not set to True, the service raises an exception.
            "force": force,
        }
    )

    operation.result(timeout=500)

    print("Orphan products deleted.")

שפות נוספות

‫C#‎: פעלו לפי הוראות ההגדרה של C# ‎ בדף ספריות הלקוח, ואז עיינו במאמרי העזרה של Vision API Product Search ל-‎ .NET.

‫PHP: פועלים לפי הוראות ההגדרה של PHP בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-PHP.

‫Ruby: פועלים לפי הוראות ההגדרה של Ruby בדף ספריות הלקוח, ואז עוברים אל מאמרי העזרה של Vision API Product Search ל-Ruby.

קבלת הסטטוס של פעולה

אתם יכולים להשתמש ב-operation-id של פעולה ממושכת (כמו מחיקת קבוצת מוצרים או מחיקת מוצרים מיותרים) כדי לקבל את הסטטוס שלה.

REST

לפני שמשתמשים בנתוני הבקשה, צריך להחליף את הנתונים הבאים:

  • ‫PROJECT_ID: מזהה הפרויקט ב- Google Cloud .
  • ‫LOCATION_ID: מזהה מיקום תקין. מזהי המיקום התקינים הם: us-west1,‏ us-east1,‏ europe-west1 ו-asia-east1.
  • ‫OPERATION_ID: מזהה הפעולה. המזהה הוא הרכיב האחרון בשם הפעולה. לדוגמה:
    • שם הפעולה: projects/PROJECT_ID/locations/LOCATION_ID/operations/bc4e1d412863e626
    • מזהה הפעולה: bc4e1d412863e626

ה-method של ה-HTTP וכתובת ה-URL:

GET https://vision.googleapis.com/v1/locations/location-id/operations/operation-id

כדי לשלוח את הבקשה אתם צריכים לבחור אחת מהאפשרויות הבאות:

curl

מריצים את הפקודה הבאה:

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "x-goog-user-project: project-id" \
"https://vision.googleapis.com/v1/locations/location-id/operations/operation-id"

PowerShell

מריצים את הפקודה הבאה:

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred"; "x-goog-user-project" = "project-id" }

Invoke-WebRequest `
-Method GET `
-Headers $headers `
-Uri "https://vision.googleapis.com/v1/locations/location-id/operations/operation-id" | Select-Object -Expand Content
הפלט אמור להיראות כך עבור פעולת טיהור של קבוצת מוצרים שהושלמה:
{
  "name": "locations/location-id/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "submitTime": "2019-09-04T15:58:39.131591882Z",
    "endTime": "2019-09-04T15:58:43.099020580Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.PurgeProductsRequest",
    "parent": "projects/project-id/locations/location-id",
    "productSetPurgeConfig": {
      "productSetId": "project-set-id"
    },
    "force": true
  }
}

הפלט אמור להיראות כך אחרי שהפעולה לניקוי מוצרים מיותמים הושלמה:

{
  "name": "locations/location-id/operations/operation-id",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "submitTime": "2019-09-04T16:08:38.278197397Z",
    "endTime": "2019-09-04T16:08:45.075778639Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.PurgeProductsRequest",
    "parent": "projects/project-id/locations/location-id",
    "deleteOrphanProducts": true,
    "force": true
  }
}