리소스 삭제

API로 작성된 참조 이미지, 제품 또는 제품 세트 리소스를 삭제할 수 있습니다.

개별 리소스 삭제

참조 이미지 삭제

제품과 연결된 참조 이미지를 삭제할 수 있습니다.

작업 요청 후 이미지는 삭제된 것으로 표시되지만 다음 번에 색인을 만들 때까지 제품에 그대로 남아 있습니다.

Cloud Storage의 실제 이미지 파일은 이 작업에 의해 삭제되지 않습니다. 제품에서 이미지를 가리키는 참조만 삭제됩니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

제품 삭제

특정 프로젝트와 연결된 제품을 삭제할 수 있습니다.

제품을 삭제하면 하위 이미지가 삭제됩니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

제품 세트 삭제

제품 세트를 삭제할 수도 있습니다.

상품 세트를 삭제하면 결과에서 상품 세트가 즉시 삭제됩니다. 그러나 하나의 상품이 서로 다른 여러 세트에 속할 수 있으므로 상품 세트를 삭제해도 세트의 개별 상품이 제거되지 않습니다. 다음 번 색인 생성을 기다리지 않아도 변경사항이 즉시 적용됩니다.

Cloud Storage의 실제 이미지 파일은 이 작업에 의해 삭제되지 않습니다. ReferenceImage API로 생성된 리소스는 삭제되지 않습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.


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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

/**
 * 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

리소스 일괄 삭제

이제 제품을 일괄 삭제할 수 있습니다. 제품 일괄 삭제는 다음 제품 유형에 사용할 수 있습니다.

  • 특정 제품 세트의 모든 제품
  • 제품 세트에 포함되지 않은 모든 제품

동시 작업 오류를 방지하려면 일괄 제품 삭제 작업이 완료된 후 제품 세트가 삭제될 때까지 기다립니다. 비워진 제품 세트를 재사용하는 경우 일괄 삭제가 완료될 때까지 기다린 후에 새 제품을 가져옵니다.

이와 같은 고려 사항은 개별 제품과 유사합니다. 즉, 일괄 삭제와 관련된 개별 제품에 대해 조치를 취하지 않아야 합니다. 예를 들어 이러한 제품은 결국 삭제되므로 다른 제품 세트에 추가하지 않아야 합니다.

제품 세트의 제품 삭제

요청에서 제품 세트 ID를 지정하여 특정 제품 세트의 모든 제품을 삭제할 수 있습니다.

다른 제품 세트에 속하는지 여부에 관계없이 제품 세트의 모든 제품이 삭제됩니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

분리된 제품 삭제

요청에서 이 옵션을 지정하여 제품 세트에 없는 모든 제품을 삭제할 수 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Go API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Java API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Node.js API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

// 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 제품 검색용 클라이언트 라이브러리를 설치하고 사용하는 방법은 Vision API 제품 검색 클라이언트 라이브러리를 참조하세요. 자세한 내용은 Vision API 제품 검색 Python API 참조 문서를 확인하세요.

Vision API 제품 검색에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

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 제품 검색 참조 문서를 참조하세요.

PHP: 클라이언트 라이브러리 페이지의 PHP 설정 안내를 따른 다음 PHP용 Vision API 제품 검색 참조 문서를 참조하세요.

Ruby: 클라이언트 라이브러리 페이지의 Ruby 설정 안내를 따른 다음 Ruby용 Vision API 제품 검색 참조 문서를 참조하세요.

작업 상태 가져오기

장기 실행 작업의 operation-id(예: 제품 세트 삭제 또는 분리된 제품 삭제)를 사용하여 상태를 가져올 수 있습니다.

REST

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • LOCATION_ID: 유효한 위치 식별자입니다. 유효한 위치 식별자는 us-west1, us-east1, europe-west1, asia-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 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
  }
}