Creating a product set resource

A product set is a simple container for a group of products.

Manually creating an empty product set

We recommend a single product set for all of your items. You can create additional product sets for testing. The following code samples show you how to create an empty product set.

Command-line

To create a product set, send a POST to the https://vision.googleapis.com/v1/{parent=projects/*/locations/*}/productSets endpoint in the following format.
  • Replace project-id with the id of your Google Cloud Platform (GCP) project.
  • Replace location-id with a valid location identifier.Valid location identifiers are: us-west1, us-east1, europe-west1, and asia-east1.
  • Replace display-name with the display name for your new product set.
curl -X POST \
    -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
    -H "Content-Type: application/json" \ 
    "https://vision.googleapis.com/v1/projects/project-id/locations/location-id/productSets" -d '{
       'displayName' : 'display-name'
    }

Java

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

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);

    // Create a product set with the product set specification in the region.
    ProductSet myProductSet =
        ProductSet.newBuilder().setDisplayName(productSetDisplayName).build();
    CreateProductSetRequest request =
        CreateProductSetRequest.newBuilder()
            .setParent(formattedParent)
            .setProductSet(myProductSet)
            .setProductSetId(productSetId)
            .build();
    ProductSet productSet = client.createProductSet(request);
    // Display the product set information
    System.out.println(String.format("Product set name: %s", productSet.getName()));
  }
}

Node.js

// 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 productSetDisplayName = 'Display name of the product set';

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

const productSet = {
  displayName: productSetDisplayName,
};

const request = {
  parent: locationPath,
  productSet: productSet,
  productSetId: productSetId,
};

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

PHP

namespace Google\Cloud\Samples\Vision;

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

/**
 * Create a 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 set
 * @param string $productSetDisplayName Display name of the product set
 */
function product_set_create($projectId, $location, $productSetId, $productSetDisplayName)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # create a product set with the product set specification in the region.
    $productSet = (new ProductSet())
        ->setDisplayName($productSetDisplayName);

    # the response is the product set with the `name` field populated.
    $response = $client->createProductSet($locationPath, $productSet, ['productSetId' => $productSetId]);

    # display the product information.
    printf('Product set name: %s' . PHP_EOL, $response->getName());

    $client->close();
}

Python

from google.cloud import vision

def create_product_set(
        project_id, location, product_set_id, product_set_display_name):
    """Create a product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        product_set_id: Id of the product set.
        product_set_display_name: Display name of the product set.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = client.location_path(
        project=project_id, location=location)

    # Create a product set with the product set specification in the region.
    product_set = vision.types.ProductSet(
            display_name=product_set_display_name)

    # The response is the product set with `name` populated.
    response = client.create_product_set(
        parent=location_path,
        product_set=product_set,
        product_set_id=product_set_id)

    # Display the product set information.
    print('Product set name: {}'.format(response.name))

Using bulk import to create a product set with products

You can also use the bulk import function to simultaneously create a product set, create multiple products and their reference images. Perform bulk import by running the following code:

Command-line

To import the products in your product set, send a POST request to the following URI.
  • Replace project-id with the id of your Google Cloud Platform (GCP) project.
  • Replace location-id with a valid location identifier.Valid location identifiers are: us-west1, us-east1, europe-west1, and asia-east1.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
"https://vision.googleapis.com/v1/projects/$PROJECT_ID/locations/$LOCATION_ID/productSets:import" -d '{
  "inputConfig": {
    "gcsSource": {
      "csvFileUri": "gs://bucket/path/to/file.csv"
    }
  }
}'
A successful response contains a long-running operation object:
{
  "name": "locations/location-id/operations/operation-id"
}
To request the status of the operation, call the operations endpoint and pass the operation-id that was returned from your call to the import method. Replace location-id with the location id from your call to the import method.
curl -X GET -H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://vision.googleapis.com/v1/locations/location-id/operations/operation-id
The response looks like:
{
  "name": "locations/us-west1/operations/eea5667a0ed419d8",
  "metadata": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.BatchOperationMetadata",
    "state": "SUCCESSFUL",
    "endTime": "2018-04-18T21:45:14.926185506Z"
  },
  "done": true,
  "response": {
    "@type": "type.googleapis.com/google.cloud.vision.v1.ImportProductSetsResponse",
    "referenceImages": [
      {
        "name": "projects/media-demo-service/locations/us-west1/products/160421_kids_01/referenceImages/17196263426604931544-0",
        "uri": "gs://cloud-ml-api-e2e-testing/vision/product_search/client-lib/160421_kids_01.jpg"
      },
      {
        "name": "projects/media-demo-service/locations/us-west1/products/160421_kids_02/referenceImages/17196263426604931544-1",
        "uri": "gs://cloud-ml-api-e2e-testing/vision/product_search/client-lib/160421_kids_02.jpg"
      },
      {
        "name": "projects/media-demo-service/locations/us-west1/products/160421_kids_04/referenceImages/17196263426604931544-2",
        "uri": "gs://cloud-ml-api-e2e-testing/vision/product_search/client-lib/160421_kids_04.jpg"
      },
      {
        "name": "projects/media-demo-service/locations/us-west1/products/160421_kids_05/referenceImages/17196263426604931544-3",
        "uri": "gs://cloud-ml-api-e2e-testing/vision/product_search/client-lib/160421_kids_05.jpg"
      },
      {
        "name": "projects/media-demo-service/locations/us-west1/products/160421_women_05/referenceImages/17196263426604931544-4",
        "uri": "gs://cloud-ml-api-e2e-testing/vision/product_search/client-lib/160421_women_05.jpg"
      },
      {
        "name": "projects/media-demo-service/locations/us-west1/products/160421_women_07/referenceImages/17196263426604931544-5",
        "uri": "gs://cloud-ml-api-e2e-testing/vision/product_search/client-lib/160421_women_07.jpg"
      }
    ],
    "statuses": [
      {},
      {},
      {},
      {},
      {},
      {}
    ]
  }
}

Java

/**
 * Import images of different products in the product set.
 *
 * @param projectId - Id of the project.
 * @param computeRegion - Region name.
 * @param gcsUri - Google Cloud Storage URI.Target files must be in Product Search CSV format.
 * @throws Exception - on client errors.
 */
public static void importProductSets(String projectId, String computeRegion, String gcsUri)
    throws Exception {
  try (ProductSearchClient client = ProductSearchClient.create()) {

    // A resource that represents Google Cloud Platform location.
    String formattedParent = ProductSearchClient.formatLocationName(projectId, computeRegion);
    Builder gcsSource = ImportProductSetsGcsSource.newBuilder().setCsvFileUri(gcsUri);

    // Set the input configuration along with Google Cloud Storage URI
    ImportProductSetsInputConfig inputConfig =
        ImportProductSetsInputConfig.newBuilder().setGcsSource(gcsSource).build();

    // Import the product sets from the input URI.
    OperationFuture<ImportProductSetsResponse, BatchOperationMetadata> response =
        client.importProductSetsAsync(formattedParent, inputConfig);

    System.out.println(String.format("Processing operation name: %s", response.getName()));
    ImportProductSetsResponse results = response.get();
    System.out.println("Processing done.");
    System.out.println("Results of the processing:");

    for (int i = 0; i < results.getStatusesCount(); i++) {
      System.out.println(
          String.format(
              "Status of processing line %s of the csv: %s", i, results.getStatuses(i)));
      // Check the status of reference image.
      if (results.getStatuses(i).getCode() == 0) {
        ReferenceImage referenceImage = results.getReferenceImages(i);
        System.out.println(referenceImage);
      } else {
        System.out.println("No reference image.");
      }
    }
  }
}

Node.js

async function importProductSets(projectId, location, gcsUri) {
  // 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 gcsUri = 'Google Cloud Storage path of the input image'';

  // A resource that represents Google Cloud Platform location.
  const projectLocation = client.locationPath(projectId, location);

  // Set the input configuration along with Google Cloud Storage URI
  const inputConfig = {
    gcsSource: {
      csvFileUri: gcsUri,
    },
  };

  // Import the product sets from the input URI.
  const [response, operation] = await client.importProductSets({
    parent: projectLocation,
    inputConfig: inputConfig,
  });

  console.log('Processing operation name: ', operation.name);

  // synchronous check of operation status
  const [result] = await response.promise();
  console.log('Processing done.');
  console.log('Results of the processing:');

  for (const i in result.statuses) {
    console.log('Status of processing ', i, 'of the csv:', result.statuses[i]);

    // Check the status of reference image
    if (result.statuses[i].code === 0) {
      console.log(result.referenceImages[i]);
    } else {
      console.log('No reference image.');
    }
  }

PHP

namespace Google\Cloud\Samples\Vision;

use Google\Cloud\Vision\V1\ProductSearchClient;
use Google\Cloud\Vision\V1\ImportProductSetsGcsSource;
use Google\Cloud\Vision\V1\ImportProductSetsInputConfig;


/**
 * Import images of different products in the product set.
 *
 * @param string $projectId Your Google Cloud Project ID
 * @param string $location Google Cloud compute region name
 * @param string $gcsUri Google Cloud Storage URI
 */
function product_set_import($projectId, $location, $gcsUri)
{
    $client = new ProductSearchClient();

    # a resource that represents Google Cloud Platform location.
    $locationPath = $client->locationName($projectId, $location);

    # set the input configuration along with Google Cloud Storage URI
    $gcsSource = (new ImportProductSetsGcsSource())
        ->setCsvFileUri($gcsUri);
    $inputConfig = (new ImportProductSetsInputConfig())
        ->setGcsSource($gcsSource);

    # import the product sets from the input URI
    $operation = $client->importProductSets($locationPath, $inputConfig);
    $operationName = $operation->getName();
    printf('Processing operation name: %s' . PHP_EOL, $operationName);

    $operation->pollUntilComplete();
    print('Processing done.' . PHP_EOL);

    if ($result = $operation->getResult()) {
        $referenceImages = $result->getReferenceImages();

        foreach ($result->getStatuses() as $count => $status) {
            printf('Status of processing line %d of the csv: ' . PHP_EOL, $count);
            # check the status of reference image
            # `0` is the code for OK in google.rpc.Code.
            if ($status->getCode() == 0) {
                $referenceImage = $referenceImages[$count];
                printf('name: %s' . PHP_EOL, $referenceImage->getName());
                printf('uri: %s' . PHP_EOL, $referenceImage->getUri());
            } else {
                printf('Status code not OK: %s' . PHP_EOL, $status->getMessage());
            }
        }
    } else{
        print($operation->getError()->getMessage());
    }

    $client->close();
}

Python

def import_product_sets(project_id, location, gcs_uri):
    """Import images of different products in the product set.
    Args:
        project_id: Id of the project.
        location: A compute region name.
        gcs_uri: Google Cloud Storage URI.
            Target files must be in Product Search CSV format.
    """
    client = vision.ProductSearchClient()

    # A resource that represents Google Cloud Platform location.
    location_path = client.location_path(
        project=project_id, location=location)

    # Set the input configuration along with Google Cloud Storage URI
    gcs_source = vision.types.ImportProductSetsGcsSource(
        csv_file_uri=gcs_uri)
    input_config = vision.types.ImportProductSetsInputConfig(
        gcs_source=gcs_source)

    # Import the product sets from the input URI.
    response = client.import_product_sets(
        parent=location_path, input_config=input_config)

    print('Processing operation name: {}'.format(response.operation.name))
    # synchronous check of operation status
    result = response.result()
    print('Processing done.')

    for i, status in enumerate(result.statuses):
        print('Status of processing line {} of the csv: {}'.format(
            i, status))
        # Check the status of reference image
        # `0` is the code for OK in google.rpc.Code.
        if status.code == 0:
            reference_image = result.reference_images[i]
            print(reference_image)
        else:
            print('Status code not OK: {}'.format(status.message))
Was this page helpful? Let us know how we did:

Send feedback about...

Cloud Vision API Product Search
Need help? Visit our support page.