建立及管理產品資源

建立產品組合後,即可建立產品並加入產品組合。建立產品時,必須提供產品的顯示名稱和產品類別。目前支援的類別包括:homegoods-v2apparel-v2toys-v2packagedgoods-v1general-v1*。

你也可以視需要提供產品說明和標籤。標籤是描述產品的鍵/值組合,例如 color=blackstyle=mens。你可以加入標籤來篩選產品搜尋結果,只搜尋特定產品圖片。

建立產品

你可以使用線上匯入功能建立個別產品。建立產品後,你可以為產品新增參考圖片,或將產品加入一或多個產品組合。

REST

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

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • DISPLAY_NAME:您選擇的字串顯示名稱。
  • PRODUCT_DESCRIPTION:您選擇的字串說明。
  • product-category:有效的產品類別。目前可用的產品類別如下:homegoods-v2apparel-v2toys-v2packagedgoods-v1general-v1
  • productLabels:與產品相關聯的一或多個鍵/值組合。每個 KEY_STRING 都必須有相關聯的 VALUE_STRING

HTTP 方法和網址:

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

JSON 要求主體:

{
  "displayName": "display-name",
  "description": "product-description",
  "productCategory": "product-category",
  "productLabels": [
      {
        "key": "key-string",
        "value": "value-string"
      }
  ]
}

如要傳送要求,請選擇以下其中一個選項:

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"

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" | Select-Object -Expand Content

要求主體範例:

{
  "displayName": "sample-product-1234",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
      {
        "key": "style",
        "value": "womens"
      },
      {
        "key": "color",
        "value": "blue"
      }
  ]
}

如果要求成功,伺服器會傳回 200 OK HTTP 狀態碼與 JSON 格式的回應。

畫面會顯示類似以下的輸出。您可以使用產品 ID (本例中為 37b9811d308c4e42) 對產品執行其他作業。

{
  "name": "projects/project-id/locations/location-id/products/37b9811d308c4e42",
  "displayName": "sample-product-456",
  "description": "Athletic shorts",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "color",
      "value": "blue"
    }
  ]
}

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"
)

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

	req := &visionpb.CreateProductRequest{
		Parent:    fmt.Sprintf("projects/%s/locations/%s", projectID, location),
		ProductId: productID,
		Product: &visionpb.Product{
			DisplayName:     productDisplayName,
			ProductCategory: productCategory,
		},
	}

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

	fmt.Fprintf(w, "Product name: %s\n", resp.Name)

	return nil
}

Java

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

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

/**
 * Create one product.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId - Id of the product.
 * @param productDisplayName - Display name of the product.
 * @param productCategory - Category of the product.
 * @throws IOException - on I/O errors.
 */
public static void createProduct(
    String projectId,
    String computeRegion,
    String productId,
    String productDisplayName,
    String productCategory)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = LocationName.format(projectId, computeRegion);
    // Create a product with the product specification in the region.
    // Multiple labels are also supported.
    Product myProduct =
        Product.newBuilder()
            .setName(productId)
            .setDisplayName(productDisplayName)
            .setProductCategory(productCategory)
            .build();
    Product product = client.createProduct(formattedParent, myProduct, productId);
    // Display the product information
    System.out.println(String.format("Product name: %s", product.getName()));
  }
}

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 createProduct() {
  /**
   * 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 productDisplayName = 'Display name of the product';
  // const productCategory = 'Catoegory of the product';

  // Resource path that represents Google Cloud Platform location.
  const locationPath = client.locationPath(projectId, location);

  const product = {
    displayName: productDisplayName,
    productCategory: productCategory,
  };

  const request = {
    parent: locationPath,
    product: product,
    productId: productId,
  };

  const [createdProduct] = await client.createProduct(request);
  console.log(`Product name: ${createdProduct.name}`);
}
createProduct();

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 create_product(
    project_id, location, product_id, product_display_name, product_category
):
    """Create one product.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        product_display_name: Display name of the product.
        product_category: Category of the product.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = f"projects/{project_id}/locations/{location}"

    # Create a product with the product specification in the region.
    # Set product display name and product category.
    product = vision.Product(
        display_name=product_display_name, product_category=product_category
    )

    # The response is the product with the `name` field populated.
    response = client.create_product(
        parent=location_path, product=product, product_id=product_id
    )

    # Display the product information.
    print(f"Product name: {response.name}")


其他語言

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_SET_ID:要對其執行作業的產品組合 ID。
  • PRODUCT_NAME:產品的完整資源名稱。 格式:
    • projects/PROJECT_ID/locations/LOCATION_ID/products/PRODUCT_ID

HTTP 方法和網址:

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

JSON 要求主體:

{
  "product": "product-name"
}

如要傳送要求,請選擇以下其中一個選項:

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/productSets/product-set-id:addProduct"

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/productSets/product-set-id:addProduct" | 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"
)

// addProductToProductSet adds a product to a product set.
func addProductToProductSet(w io.Writer, projectID string, location string, productID 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.AddProductToProductSetRequest{
		Name:    fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
		Product: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

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

	fmt.Fprintf(w, "Product added to product set.\n")

	return nil
}

Java

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

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


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

    // Get the full path of the product set.
    String formattedName = ProductSetName.format(projectId, computeRegion, productSetId);

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

    // Add the product to the product set.
    client.addProductToProductSet(formattedName, productPath);

    System.out.println(String.format("Product added to product set."));
  }
}

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 addProductToProductSet() {
  /**
   * 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 productSetId = 'Id of the product set';

  const productPath = client.productPath(projectId, location, productId);
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  const request = {
    name: productSetPath,
    product: productPath,
  };

  await client.addProductToProductSet(request);
  console.log('Product added to product set.');
}
addProductToProductSet();

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 add_product_to_product_set(project_id, location, product_id, product_set_id):
    """Add a product to a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        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
    )

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

    # Add the product to the product set.
    client.add_product_to_product_set(name=product_set_path, product=product_path)
    print("Product added to 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
  • PRODUCT_SET_ID:要對其執行作業的產品組合 ID。
  • PRODUCT_NAME:產品的完整資源名稱。 格式:
    • projects/PROJECT_ID/locations/LOCATION_ID/products/PRODUCT_ID

HTTP 方法和網址:

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

JSON 要求主體:

{
  "product": "product-name"
}

如要傳送要求,請選擇以下其中一個選項:

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/productSets/product-set-id:removeProduct"

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/productSets/product-set-id:removeProduct" | 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"
)

// removeProductFromProductSet removes a product from a product set.
func removeProductFromProductSet(w io.Writer, projectID string, location string, productID 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.RemoveProductFromProductSetRequest{
		Name:    fmt.Sprintf("projects/%s/locations/%s/productSets/%s", projectID, location, productSetID),
		Product: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
	}

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

	fmt.Fprintf(w, "Product removed from product set.\n")

	return nil
}

Java

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

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


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

    // Get the full path of the product set.
    String formattedParent = ProductSetName.format(projectId, computeRegion, productSetId);

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

    // Remove the product from the product set.
    client.removeProductFromProductSet(formattedParent, formattedName);

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

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

const client = new vision.ProductSearchClient();

async function removeProductFromProductSet() {
  /**
   * TODO(developer): Uncomment the following line before running the sample.
   */
  const productSetPath = client.productSetPath(
    projectId,
    location,
    productSetId
  );

  const productPath = client.productPath(projectId, location, productId);

  const request = {
    name: productSetPath,
    product: productPath,
  };

  await client.removeProductFromProductSet(request);
  console.log('Product removed from product set.');
}
removeProductFromProductSet();

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 remove_product_from_product_set(project_id, location, product_id, product_set_id):
    """Remove a product from a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        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
    )

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

    # Remove the product from the product set.
    client.remove_product_from_product_set(name=product_set_path, product=product_path)
    print("Product removed from product set.")


其他語言

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

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

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