更新資源

更新產品

你可以使用下列程式碼,透過鍵/值組合 (例如 "style=womens""onSale=true") 更新產品的標籤。

<0

指令列

傳送 PATCH 要求時,系統會清除所有先前的欄位及其值,但 productCategory 欄位除外,因為該欄位不可變更。送出 PATCH 更新要求時,請一併傳送所有必要欄位及其值。

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

  • PROJECT_ID:您的 Google Cloud 專案 ID
  • LOCATION_ID:有效的地點 ID。有效的位置識別碼包括:us-west1us-east1europe-west1asia-east1
  • PRODUCT_ID:與參考圖片相關聯的產品 ID。這個 ID 是隨機設定,或由使用者在建立產品時指定。
  • display-name:您選擇的字串顯示名稱。這個值可以與先前的顯示名稱相同,也可以是更新後的值。
  • description:您選擇的字串說明。這可以與先前的顯示名稱相同,也可以是更新的值。如不需要,請省略 description 欄位和值。
  • productLabels:與產品相關聯的一或多個鍵/值組合。每個 KEY_STRING 都必須有相關聯的 VALUE_STRING

HTTP 方法和網址:

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

JSON 要求內文:

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

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

curl

將要求內文儲存在名為 request.json 的檔案中,然後執行下列指令:

curl -X PATCH \
-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/product-id"

PowerShell

將要求主體儲存在名為 request.json 的檔案中,然後執行下列指令:

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

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

您應該會收到如下的 JSON 回覆:

{
  "name": "projects/project-id/locations/location-id/products/product-id",
  "displayName": "display-name",
  "description": "description",
  "productCategory": "apparel-v2",
  "productLabels": [
    {
      "key": "style",
      "value": "womens"
    },
    {
      "key": "onSale",
      "value": "true"
    }
  ]
}

Go

如要瞭解如何安裝及使用 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"
	field_mask "google.golang.org/genproto/protobuf/field_mask"
)

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

	req := &visionpb.UpdateProductRequest{
		UpdateMask: &field_mask.FieldMask{
			Paths: []string{
				"product_labels",
			},
		},
		Product: &visionpb.Product{
			Name: fmt.Sprintf("projects/%s/locations/%s/products/%s", projectID, location, productID),
			ProductLabels: []*visionpb.Product_KeyValue{
				{
					Key:   key,
					Value: value,
				},
			},
		},
	}

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

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

	return nil
}

Java

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

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

/**
 * Update the product labels.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param productId -Id of the product.
 * @param productLabels - Labels of the product.
 * @throws IOException - on I/O errors.
 */
public static void updateProductLabels(
    String projectId, String computeRegion, String productId, String productLabels)
    throws IOException {
  try (ProductSearchClient client = ProductSearchClient.create()) {

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

    // Set product name, product labels and product display name.
    // Multiple labels are also supported.
    Product product =
        Product.newBuilder()
            .setName(formattedName)
            .addProductLabels(
                KeyValue.newBuilder()
                    .setKey(productLabels.split(",")[0].split("=")[0])
                    .setValue(productLabels.split(",")[0].split("=")[1])
                    .build())
            .build();

    // Set product update field name.
    FieldMask updateMask = FieldMask.newBuilder().addPaths("product_labels").build();

    // Update the product.
    Product updatedProduct = client.updateProduct(product, updateMask);
    // Display the product information
    System.out.println(String.format("Product name: %s", updatedProduct.getName()));
    System.out.println(String.format("Updated product labels: "));
    for (Product.KeyValue element : updatedProduct.getProductLabelsList()) {
      System.out.println(String.format("%s: %s", element.getKey(), element.getValue()));
    }
  }
}

Node.js

如要瞭解如何安裝及使用 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 updateProductLabels() {
  /**
   * 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 key = 'The key of the label';
  // const value = 'The value of the label';

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

  const product = {
    name: productPath,
    productLabels: [
      {
        key: key,
        value: value,
      },
    ],
  };

  const updateMask = {
    paths: ['product_labels'],
  };

  const request = {
    product: product,
    updateMask: updateMask,
  };

  const [updatedProduct] = await client.updateProduct(request);
  console.log(`Product name: ${updatedProduct.name}`);
  console.log(`Product display name: ${updatedProduct.displayName}`);
  console.log(`Product description: ${updatedProduct.description}`);
  console.log(`Product category: ${updatedProduct.productCategory}`);
  console.log(
    `Product Labels: ${updatedProduct.productLabels[0].key}: ${updatedProduct.productLabels[0].value}`
  );
}
updateProductLabels();

Python

如要瞭解如何安裝及使用 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 update_product_labels(project_id, location, product_id, key, value):
    """Update the product labels.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_id: Id of the product.
        key: The key of the label.
        value: The value of the label.
    """
    client = vision.ProductSearchClient()

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

    # Set product name, product label and product display name.
    # Multiple labels are also supported.
    key_value = vision.Product.KeyValue(key=key, value=value)
    product = vision.Product(name=product_path, product_labels=[key_value])

    # Updating only the product_labels field here.
    update_mask = field_mask.FieldMask(paths=["product_labels"])

    # This overwrites the product_labels.
    updated_product = client.update_product(product=product, update_mask=update_mask)

    # Display the updated product information.
    print(f"Product name: {updated_product.name}")
    print(f"Updated product labels: {product.product_labels}")


其他語言

C#:請按照用戶端程式庫頁面上的 C# 設定操作說明完成相關步驟,然後參閱「.NET 適用的 Vision API Product Search 參考文件」。

PHP:請按照用戶端程式庫頁面上的 PHP 設定操作說明完成相關步驟,然後參閱「PHP 適用的 Vision API 產品搜尋參考文件」。

Ruby:請按照用戶端程式庫頁面上的 Ruby 設定操作說明完成相關步驟,然後參閱 Ruby 適用的 Vision API Product Search 參考文件