刪除資源

您可以刪除 API 建立的參考圖片、產品或產品組合資源。

刪除個別資源

刪除參考圖片

你可以刪除與產品相關聯的參考圖片。

作業要求完成後,系統會將圖片標示為待刪除,但圖片仍會保留在產品中,直到下次建立索引為止。

這項作業不會刪除 Cloud Storage 中的實際圖片檔案。系統只會移除產品的圖片參照。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • PRODUCT_ID:與參考圖片相關聯的產品 ID。這個 ID 是隨機設定,或由使用者在建立產品時指定。
  • IMAGE_ID:目標圖片資源的 ID。

HTTP 方法和網址:

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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# 設定說明操作, 然後前往 .NET 適用的 Vision API Product Search 參考說明文件

PHP: 請按照用戶端程式庫頁面上的 PHP 設定說明 操作,然後前往 PHP 適用的 Vision API 產品搜尋參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明操作, 然後前往 Ruby 適用的 Vision API Product Search 參考說明文件

刪除產品

你可以刪除與特定專案相關聯的產品。

刪除產品會導致系統一併刪除子項圖片。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • PRODUCT_ID:與參考圖片相關聯的產品 ID。這個 ID 是隨機設定,或由使用者在建立產品時指定。

HTTP 方法和網址:

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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# 設定說明操作, 然後前往 .NET 適用的 Vision API Product Search 參考說明文件

PHP: 請按照用戶端程式庫頁面上的 PHP 設定說明 操作,然後前往 PHP 適用的 Vision API 產品搜尋參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明操作, 然後前往 Ruby 適用的 Vision API Product Search 參考說明文件

刪除產品集

你也可以刪除產品組合。

刪除產品組合後,系統會立即從結果中移除該組合。 不過,刪除產品組合「不會」移除組合中的個別產品,因為產品可能屬於多個不同組合。您不必等待下一個索引,變更就會生效。

這項作業不會刪除 Cloud Storage 中的實際圖片檔案。系統不會移除透過 API 建立的 ReferenceImage 資源。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • PRODUCT_SET_ID:要對其執行作業的產品組合 ID。

HTTP 方法和網址:

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。


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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

/**
 * 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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# 設定說明操作, 然後前往 .NET 適用的 Vision API Product Search 參考說明文件

PHP: 請按照用戶端程式庫頁面上的 PHP 設定說明 操作,然後前往 PHP 適用的 Vision API 產品搜尋參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明操作, 然後前往 Ruby 適用的 Vision API Product Search 參考說明文件

批次刪除資源

你現在可以批次刪除產品。下列產品類型可進行產品批次刪除:

  • 特定產品集中的所有產品
  • 不屬於任何產品組合的所有產品

為避免發生並行作業錯誤,請等待這批產品刪除作業完成後,再刪除產品組合。如果重複使用已清空的產品組合,請等待批次刪除作業完成,再匯入新產品。

個別產品也適用類似的考量事項;您應避免對批次刪除作業中的任何個別產品採取行動。舉例來說,請勿將這些產品新增至其他產品組合,因為系統最終會刪除這些產品。

刪除產品集中的產品

只要在要求中指定產品集 ID,即可刪除特定產品集中的所有產品。

系統會刪除產品組合中的所有產品,無論這些產品是否屬於其他產品組合

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • PRODUCT_SET_ID:要對其執行作業的產品組合 ID。

HTTP 方法和網址:

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-idbc4e1d412863e626

您可以使用 operation-id 追蹤這項作業的進度。如要查看取得作業狀態的範例,請參閱「取得作業狀態」。

Go

如要瞭解如何安裝及使用 Vision API Product Search 的用戶端程式庫,請參閱 Vision API Product Search 用戶端程式庫。 詳情請參閱 Vision API Product Search Go API 參考說明文件

如要向 Vision API Product Search 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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# 設定說明操作, 然後前往 .NET 適用的 Vision API Product Search 參考說明文件

PHP: 請按照用戶端程式庫頁面上的 PHP 設定說明 操作,然後前往 PHP 適用的 Vision API 產品搜尋參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明操作, 然後前往 Ruby 適用的 Vision API Product Search 參考說明文件

刪除孤立產品

如要在要求中指定這個選項,可以刪除產品組合中屬於該組合的所有產品。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1

HTTP 方法和網址:

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-idbc4e1d412863e626

您可以使用 operation-id 追蹤這項作業的進度。如要查看取得作業狀態的範例,請參閱「取得作業狀態」。

Go

如要瞭解如何安裝及使用 Vision API Product Search 的用戶端程式庫,請參閱 Vision API Product Search 用戶端程式庫。 詳情請參閱 Vision API Product Search Go API 參考說明文件

如要向 Vision API Product Search 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

// 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 進行驗證,請設定應用程式預設憑證。 詳情請參閱「為本機開發環境設定驗證」。

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# 設定說明操作, 然後前往 .NET 適用的 Vision API Product Search 參考說明文件

PHP: 請按照用戶端程式庫頁面上的 PHP 設定說明 操作,然後前往 PHP 適用的 Vision API 產品搜尋參考文件

Ruby: 請按照用戶端程式庫頁面的 Ruby 設定說明操作, 然後前往 Ruby 適用的 Vision API Product Search 參考說明文件

取得作業狀態

您可以透過長時間執行的作業 (例如清除產品組合或清除孤立產品) 的 operation-id 取得作業狀態。

REST

使用任何要求資料之前,請先替換以下項目:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • OPERATION_ID:作業 ID。ID 是作業名稱的最後一個元素。舉例來說:
    • 作業名稱:projects/PROJECT_ID/locations/LOCATION_ID/operations/bc4e1d412863e626
    • 作業 ID:bc4e1d412863e626

HTTP 方法和網址:

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
  }
}