リソースの削除

API によって作成された参照画像、商品、または商品セットの各リソースを削除できます。

個別のリソースの削除

参照画像を削除する

商品に関連付けられている参照画像を削除できます。

オペレーションがリクエストされると、画像は削除対象としてマーキングされますが、次にインデックスが付与されるまで商品に残ります。

このオペレーションでは Google Cloud Storage 内の実際の画像ファイルは削除されず、画像への参照のみが商品から削除されます。

REST とコマンドライン

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • location-id: 有効なロケーション ID。有効なロケーション識別子は us-west1us-east1europe-west1asia-east1 です。
  • product-id: 参照画像に関連付けられている商品の ID。この ID は、商品の作成時にユーザーによってランダムに設定または指定されます。
  • image-id: 対象の画像リソースの ID。

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 application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id/referenceImages/image-id

PowerShell

次のコマンドを実行します。

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

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 レスポンスが返されます。

{}

C#

private static int DeleteReferenceImage(DeleteReferenceImageOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new DeleteReferenceImageRequest
    {
        // Get the full path of the reference image.
        ReferenceImageName = new ReferenceImageName(opts.ProjectID,
                                                    opts.ComputeRegion,
                                                    opts.ProductID,
                                                    opts.ReferenceImageID)
    };

    client.DeleteReferenceImage(request);
    Console.WriteLine("Reference image deleted from product.");
    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// 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: %v", 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: %v", err)
	}

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

	return nil
}

Java

/**
 * 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

async function deleteReferenceImage() {
  const vision = require('@google-cloud/vision');

  const client = new vision.ProductSearchClient();

  /**
   * 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.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Delete a reference image
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 * @param string $referenceImageId ID of the reference image
 */
function product_image_delete($projectId, $location, $productId, $referenceImageId)
{
    $client = new ProductSearchClient();

    # get the name of the reference image.
    $referenceImagePath = $client->referenceImageName($projectId, $location, $productId, $referenceImageId);

    # delete the reference image
    $client->deleteReferenceImage($referenceImagePath);
    print('Reference image deleted from product.');

    $client->close();
}

Python

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.')

Ruby

require "google/cloud/vision"

def product_search_delete_reference_image project_id = "your-project-id",
                                          location   = "us-west1",
                                          product_id = "your-product-id",
                                          image_id   = "your-image-id"

  client = Google::Cloud::Vision.product_search

  reference_image_path = client.reference_image_path project:         project_id,
                                                     location:        location,
                                                     product:         product_id,
                                                     reference_image: image_id

  client.delete_reference_image name: reference_image_path

  puts "Reference image #{image_id} deleted from product #{product_id}."
end

商品を削除する

特定のプロジェクトに関連付けられている商品を削除できます。

商品を削除すると、その子となっている画像も削除されます。

REST とコマンドライン

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • location-id: 有効なロケーション ID。有効なロケーション識別子は us-west1us-east1europe-west1asia-east1 です。
  • product-id: 参照画像に関連付けられている商品の ID。この ID は、商品の作成時にユーザーによってランダムに設定または指定されます。

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 application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/products/product-id

PowerShell

次のコマンドを実行します。

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

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 レスポンスが返されます。

{}

C#

private static int DeleteProduct(DeleteProductOptions opts)
{
    var client = ProductSearchClient.Create();
    var request = new DeleteProductRequest
    {
        // Get the full path of the product.
        ProductName = new ProductName(opts.ProjectID,
                                     opts.ComputeRegion,
                                     opts.ProductID)
    };

    client.DeleteProduct(request);
    Console.WriteLine("Product deleted.");

    return 0;
}

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// 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: %v", 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: %v", err)
	}

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

	return nil
}

Java

/**
 * 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 =
        ProductSearchClient.formatProductName(projectId, computeRegion, productId);

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

Node.js

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

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

  /**
   * 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.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Delete the product and all its reference images.
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productId ID of the product
 */
function product_delete($projectId, $location, $productId)
{
    $client = new ProductSearchClient();

    # get the name of the product.
    $productPath = $client->productName($projectId, $location, $productId);

    # delete the product
    $client->deleteProduct($productPath);
    print('Product deleted.' . PHP_EOL);

    $client->close();
}

Python

from google.cloud import vision

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.')

Ruby

require "google/cloud/vision"

def product_search_delete_product project_id = "your-project-id",
                                  location   = "us-west1",
                                  product_id = "your-product_id"

  client = Google::Cloud::Vision.product_search

  product_path = client.product_path project:  project_id,
                                     location: location,
                                     product:  product_id

  client.delete_product name: product_path

  puts "Product #{product_id} deleted."
end

商品セットを削除する

商品セットは削除することもできます。

商品セットを削除すると、結果から商品セットがすぐに削除されます。ただし、商品セットを削除してもセット内の個々の商品は削除されません。これは、個々の商品が他のセットに含まれる場合があるためです。次のインデックス作成で変更が反映されるまで待つ必要はありません。

このオペレーションでは Google Cloud Storage 内の実際の画像ファイルは削除されず、API によって作成された ReferenceImage リソースも削除されません。

REST とコマンドライン

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • location-id: 有効なロケーション ID。有効なロケーション識別子は us-west1us-east1europe-west1asia-east1 です。
  • product-set-id: 操作を実行する商品セットの ID。

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 application-default print-access-token) \
https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets/product-set-id

PowerShell

次のコマンドを実行します。

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

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 レスポンスが返されます。

{}

C#

        private static object DeleteProductSet(DeleteProductSetOptions opts)
        {
            var client = ProductSearchClient.Create();
            var request = new DeleteProductSetRequest
            {
                // Get the full path of the product set.
                ProductSetName = new ProductSetName(opts.ProjectID,
                                                    opts.ComputeRegion,
                                                    opts.ProductSetId)
            };

            // Delete the product set.
            client.DeleteProductSet(request);

            Console.WriteLine("Product set deleted.");
            return 0;
        }

Go


import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// 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: %v", 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: %v", err)
	}

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

	return nil
}

Java

/**
 * 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 =
        ProductSearchClient.formatProductSetName(projectId, computeRegion, productSetId);
    // Delete the product set.
    client.deleteProductSet(formattedName);
    System.out.println(String.format("Product set deleted"));
  }
}

Node.js

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

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

  /**
   * 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.');
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Deletes product set
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $productSetId ID of the product
 */
function product_set_delete($projectId, $location, $productSetId)
{
    $client = new ProductSearchClient();

    # get the name of the product set
    $productSetPath = $client->productSetName($projectId, $location, $productSetId);

    # delete the product set
    $client->deleteProductSet($productSetPath);
    print('Product set deleted.' . PHP_EOL);

    $client->close();
}

Python

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.')

Ruby

require "google/cloud/vision"

def product_search_delete_product_set project_id     = "your-project-id",
                                      location       = "us-west1",
                                      product_set_id = "your-product-set-id"

  client = Google::Cloud::Vision.product_search

  product_set_path = client.product_set_path project:     project_id,
                                             location:    location,
                                             product_set: product_set_id

  client.delete_product_set name: product_set_path

  puts "Product set #{product_set_id} deleted."
end

リソースのバッチ削除

これで、商品を一括削除できるようになりました。商品を一括削除できるのは、次の商品の種類です。

  • 特定の商品セット内のすべての商品
  • 商品セットに属さないすべての商品

同時操作エラーを回避するには、この商品一括削除の操作が完了した後で、商品セットを削除します。空になった商品セットを再度使用する場合も、一括削除が完了するまで待ってから新しい商品をインポートしてください。

個々の商品についても同様です。一括削除に関連する個々の商品は操作しないでください。たとえば、これらの商品は最終的に削除されてしまうため、別の商品セットに追加してはいけません。

商品セット内の商品を削除する

リクエスト内で商品セット ID を指定すると、指定された商品セット内のすべての商品を削除できます。

他の商品セットに属しているかどうかに関係なく、商品セット内のすべての商品が削除されます。

REST とコマンドライン

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • location-id: 有効なロケーション ID。有効なロケーション識別子は us-west1us-east1europe-west1asia-east1 です。
  • product-set-id: 操作を実行する商品セットの ID。

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 application-default print-access-token) \
-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 application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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 を使って、このオペレーションの進行状況を追跡できます。オペレーションのステータスの取得例については、オペレーションのステータスの取得をご覧ください。

C#

private static int PurgeProductsInProductSet(PurgeProductsInProductSetOptions opts)
{
    var client = ProductSearchClient.Create();
    var parent = LocationName.Format(opts.ProjectID, opts.ComputeRegion);
    var productSetPurgeConfig = new ProductSetPurgeConfig
    {
        ProductSetId = opts.ProductSetId
    };
    var req = new PurgeProductsRequest
    {
        Parent = parent,
        ProductSetPurgeConfig = productSetPurgeConfig,
        Force = true
    };

    var response = client.PurgeProductsAsync(req);

    // wait until it finishes
    response.Result.PollUntilCompleted();

    Console.WriteLine("Products removed from product set.");
    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// 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: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

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

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

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

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

  /**
   * 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);
  }
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ProductSetPurgeConfig;

/**
 * Delete all products in a product set.
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param string $product_set_id ID of the product
 * @param boolean $force force purge
 */
function purge_products_in_product_set($projectId, $location, $product_set_id, $force)
{
    $client = new ProductSearchClient();

    $parent = $client->locationName($projectId, $location);
    $product_set_purge_config = (new ProductSetPurgeConfig())->setProductSetId($product_set_id);
    printf("Deleting products in product-set: %s" . PHP_EOL, $product_set_id);
    $operationResponse  = $client->purgeProducts($parent, ['productSetPurgeConfig' => $product_set_purge_config,
        'force' => $force]);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        print('Operation succeeded' . PHP_EOL);
    # print_r($operationResponse->getResult());
    } else {
        print('Operation failed' . PHP_EOL);
        print_r($operationResponse->getError());
    }
    $client->close();
}

Python

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 = client.location_path(
        project=project_id, location=location)

    product_set_purge_config = vision.types.ProductSetPurgeConfig(
        product_set_id=product_set_id)

    # The purge operation is async.
    operation = client.purge_products(
        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=300)

    print('Deleted products in product set.')

Ruby

require "google/cloud/vision"

# Delete all products in a product set.
def product_search_purge_products_in_product_set \
    project_id     = "your-project-id",
    location       = "us-west1",
    product_set_id = "your-product-set-id"

  client = Google::Cloud::Vision.product_search

  parent = client.location_path project: project_id, location: location

  config = {
    product_set_id: product_set_id
  }

  # 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 = true

  # The purge operation is async.
  operation = client.purge_products parent:                   parent,
                                    product_set_purge_config: config,
                                    force:                    force

  puts "Processing operation name: #{operation.name}"
  operation.wait_until_done! # Waits for the operation to complete

  puts "Products in product set #{product_set_id} deleted."
end

孤立した商品を削除する

リクエスト内でこのオプションを指定すると、商品セットに含まれないすべての商品を削除できます。

REST とコマンドライン

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • project-id: GCP プロジェクト ID
  • location-id: 有効なロケーション ID。有効なロケーション識別子は us-west1us-east1europe-west1asia-east1 です。

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 application-default print-access-token) \
-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 application-default print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

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 を使って、このオペレーションの進行状況を追跡できます。オペレーションのステータスの取得例については、オペレーションのステータスの取得をご覧ください。

C#

private static int PurgeOrphanProducts(PurgeOrphanProductsOptions opts)
{
    var client = ProductSearchClient.Create();
    var parent = LocationName.Format(opts.ProjectID, opts.ComputeRegion);

    var request = new PurgeProductsRequest
    {
        Parent = parent,
        DeleteOrphanProducts = true,
        Force = true
    };

    // Purge operation is async.
    var operation = client.PurgeProductsAsync(request);

    // wait until long operation to finish.
    operation.Result.PollUntilCompleted();
    Console.WriteLine("Orphan products deleted.");

    return 0;
}

Go

import (
	"context"
	"fmt"
	"io"

	vision "cloud.google.com/go/vision/apiv1"
	visionpb "google.golang.org/genproto/googleapis/cloud/vision/v1"
)

// 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: %v", 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: %v", err)
	}
	fmt.Fprintf(w, "Processing operation name: %q\n", op.Name())

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

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

	return nil
}

Java

import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.vision.v1.LocationName;
import com.google.cloud.vision.v1.ProductSearchClient;
import com.google.cloud.vision.v1.PurgeProductsRequest;
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 response = client.purgeProductsAsync(request);
      response.getPollingFuture().get(180, TimeUnit.SECONDS);

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

Node.js

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

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

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

  /**
   * 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);
  }
}

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;

/**
 * Delete all products not in any product sets.
 *
 * @param string $projectId Your Google Cloud project ID
 * @param string $location Google Cloud compute region name
 * @param boolean $force force purge
 */
function purge_orphan_products($projectId, $location, $force)
{
    $client = new ProductSearchClient();

    $parent = $client->locationName($projectId, $location);
    printf("Deleting orphan products" . PHP_EOL);
    $operationResponse  = $client->purgeProducts($parent, ['deleteOrphanProducts' => true, 'force' => $force]);
    $operationResponse->pollUntilComplete();
    if ($operationResponse->operationSucceeded()) {
        print('Operation succeeded' . PHP_EOL);
    # print_r($operationResponse->getResult());
    } else {
        print('Operation failed' . PHP_EOL);
        print_r($operationResponse->getError());
    }
    $client->close();
}

Python

from google.cloud import vision

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 = client.location_path(
        project=project_id, location=location)

    # The purge operation is async.
    operation = client.purge_products(
        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=300)

    print('Orphan products deleted.')

Ruby

require "google/cloud/vision"

# Delete all products not in any product sets.
def product_search_purge_orphan_products project_id = "your-project-id",
                                         location   = "us-west1"

  client = Google::Cloud::Vision.product_search

  parent = client.location_path project: project_id, location: 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 exception.
  force = true

  # The purge operation is async.
  operation = client.purge_products parent:                 parent,
                                    force:                  force,
                                    delete_orphan_products: true

  puts "Processing operation name: #{operation.name}"
  operation.wait_until_done! # Waits for the operation to complete

  puts "Orphan products deleted."
end

オペレーションのステータスの取得

operation-id を使用して、長時間実行オペレーション(商品セットの削除、孤立した商品の削除など)のステータスを取得できます。

REST とコマンドライン

後述のリクエストのデータを使用する前に、次のように置き換えます。

  • location-id: 有効なロケーション ID。有効なロケーション識別子は us-west1us-east1europe-west1asia-east1 です。
  • operation-id: オペレーションの ID。この ID は、オペレーションの名前の最後の要素です。例:
    • オペレーション名: projects/project-id/locations/location-id/operations/bc4e1d412863e626
    • オペレーション ID: bc4e1d412863e626

HTTP メソッドと URL:

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

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

次のコマンドを実行します。

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

PowerShell

次のコマンドを実行します。

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

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