This topic describes how to use Image Search SDK for Node.js and provides sample code.

Methods

Method Description
Add Adds one or more images.
SearchImageByPic Searches for similar images based on an image.
SearchImageByName Searches for similar images based on the name of an existing image in the image gallery.
Delete Deletes one or more images.
Update Updates image information.
Detail Queries instance information.
DumpMeta Creates a task to export metadata.
DumpMetaList Queries the tasks that are used to export metadata.
BatchTask Creates a batch task.
BatchTaskList Queries the tasks that are used to perform batch operations.

Preparations

  • Before you install and use an Alibaba Cloud SDK, make sure that you have created an Alibaba Cloud account and obtained the AccessKey pair of the Alibaba Cloud account. For more information, see Obtain an AccessKey pair.
  • Run the following command to install Image Search SDK for Node.js:
npm install @alicloud/imagesearch20201214@4.0.0 --save

Add

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'});
    var picContent = fs.createReadStream("D:/123.jpg");
    async function demo() {
      const addImageAdvanceRequest = new imagesearch.AddImageAdvanceRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXX",
         // Required. The ID of the product. The ID cannot exceed 512 characters in length. 
         // A product ID can correspond to multiple image names. 
        productId: "123455",
        // Required. The name of the image. The name cannot exceed 512 characters in length. 
        // 1. Required. An image is uniquely identified by the product ID (ProductId) and image name (PicName). 
        // 2. If you add an image whose product ID (ProductId) and image name (PicName) are the same as those of an existing image, the newly added image overwrites the existing image. 
        picName: "this",
        // The image. The image cannot exceed 4 MB in size. The transmission timeout period is 5 seconds. Only the following image formats are supported: PNG, JPG, JPEG, BMP, GIF, WebP, TIFF, and PPM.        
        // For product, brand, and generic images, the length and the width of the image must range from 100 pixels to 4,096 pixels.        
        // For cloth images, the length and the width of the image must range from 448 pixels to 4,096 pixels.        
        // The image cannot contain rotation properties.
        picContentObject: picContent,
        // Optional. The ID of the product category. 
        // 1. For product search: If a category is specified, the specified category prevails. If no category is specified, the system estimates and selects a category. The category selected by the system is included in the response. 
        // 2. For cloth, brand, and generic image searches: The category ID is set to 88888888 regardless of whether a category ID is set. 
        categoryId : 3,
        // Optional. The description that you want to add. The description cannot exceed 4,096 characters in length. 
        // If you set this parameter, the response includes this parameter and its value. You can add text such as an image description. 
        customContent : "this is a simple test",
        // Optional. The attribute of the INT type. The attribute can be used to filter images in image searches. If you set this parameter, the response includes this parameter and its value. 
        // For example, you can set different attributes for images from different sites or different users. This way, users can filter images by attribute and obtain more accurate search results.
        intAttr : 56,
        // Optional. The attribute of the STRING type. The value cannot exceed 128 characters in length. The attribute can be used to filter images in image searches. If you set this parameter, the response includes this parameter and its value. 
        strAttr : "test",
        // Optional. Specifies whether to recognize the subject in the image. Default value: true. 
        // 1. If you set this parameter to true, the system recognizes the subject in the image, and searches for images based on the recognized subject. The response includes the recognition result. 
        // 2. If you set this parameter to false, the system searches for images based on the entire image without subject recognition. 
        // 3. For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        crop : true,
        // Optional. The subject area of the image, in the format of x1,x2,y1,y2. Specifically, x1 and y1 specify the upper-left pixel, and x2 and y2 specify the lower-right pixel. The specified region cannot cross the boundary of the image. 
        // If you set the Region parameter, the search is conducted based on the value of the Region parameter regardless of the value of the Crop parameter. 
        // For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        region : "167,467,221,407"
      });
      let ossRuntime = new oss.RuntimeOptions({});
      const addResponse = await client.addImageAdvance(addImageAdvanceRequest, ossRuntime);
      console.log(1, addResponse);
    }
    demo();
  • Sample responses
    AddImageResponse {
      requestId: 'B85D5B4A-92AF-44C1-A3FB-9B554950F8D1',
      success: true,
      message: 'success',
      code: 0,
      picInfo: AddImageResponsePicInfo { categoryId: 0, region: '167,477,221,407' }
    }

SearchImageByPic

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXX",
      accessKeySecret: "XXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    var picContent = fs.createReadStream("D:/123.jpg");
    async function demo() {
      const searchImageByPicAdvanceRequest = new imagesearch.SearchImageByPicAdvanceRequest({
         // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXX",
        // The image. The file size of the image cannot exceed 4 MB. The transmission timeout period cannot exceed 5 seconds. Only the following image formats are supported: PNG, JPG, JPEG, BMP, GIF, WebP, TIFF, and PPM.        
        // For product, brand, and generic images, the length and the width of the image must range from 100 pixels to 4,096 pixels.        
        // For cloth images, the length and the width of the image must range from 448 pixels to 4,096 pixels.        
        // The image cannot contain rotation properties.
        picContentObject: picContent,
        // Optional. The ID of the product category. 
        // 1. For product search: If a category is specified, the specified category prevails. If no category is specified, the system estimates and selects a category. The category selected by the system is included in the response. 
        // 2. For cloth, brand, and generic image searches: The category ID is set to 88888888 regardless of whether a category ID is set. 
        categoryId: 3,
        // Optional. The number of entries to be returned. Valid values: 1 to 100. Default value: 10. 
        num: 10,
        // Optional. The ordinal number of the first entry that is returned. Valid values: 0 to 499. Default value: 0. 
        start: 0, // Optional. Specifies whether to recognize the subject in the image. Default value: true. 
        // 1. If you set this parameter to true, the system recognizes the subject in the image, and searches for images based on the recognized subject. The response includes the recognition result. 
        // 2. If you set this parameter to false, the system searches for images based on the entire image without subject recognition. 
        // 3. For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        crop: true,
        // Optional. The subject area of the image, in the format of x1,x2,y1,y2. Specifically, x1 and y1 specify the upper-left pixel, and x2 and y2 specify the lower-right pixel. The specified region cannot cross the boundary of the image. 
        // If you set the Region parameter, the search is conducted based on the value of the Region parameter regardless of the value of the Crop parameter. 
        // 3. For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. region: "167,467,221,407", // Optional. The filter conditions.
        // int_attr supports the following operators: >, >=, <, <= and =. str_attr supports the = and =! operators. You can set the logical operator between conditions to AND or OR. 
        // Examples:
        // 1. Filter images based on the int_attr field: int_attr>=100.
        // 2. Filter images based on StrAttr: str_attr!="value1".
        // 3. Filter images based on int_attr and str_attr fields: int_attr=1000 AND str_attr="value1".
        filter: "int_attr=56 AND str_attr=\"test\""
      });
      let ossRuntime = new oss.RuntimeOptions({});
      const searchImageByPicResponse = await client.searchImageByPicAdvance(searchImageByPicAdvanceRequest, ossRuntime);
      console.log(3, searchImageByPicResponse);
    }
    demo();
  • Sample responses
    SearchImageByPicResponse {
      requestId: 'A38BFBD4-D7AD-4BE9-9606-72BB765A9001',
      success: true,
      code: 0,
      msg: 'success',
      auctions: [
        SearchImageByPicResponseAuctions {
          categoryId: 0,
          productId: '1000',
          picName: 'vae.jpg',
          score:1.0,
          sortExprValues: '7.33136443711219e+24;0'
        },
      ...............
        SearchImageByPicResponseAuctions {
          categoryId: 0,
          productId: '123455',
          picName: 'this',
          score:1.0,
          sortExprValues: '7.33136443711219e+24;0'
        }
      ],
      head: SearchImageByPicResponseHead {
        docsReturn: 5,
        docsFound: 5,
        searchTime: 218
      },
      picInfo: SearchImageByPicResponsePicInfo {
        categoryId: 0,
        region: '167,477,221,407',
        allCategories: [
          [SearchImageByPicResponsePicInfoAllCategories],
          ........
          [SearchImageByPicResponsePicInfoAllCategories]
        ],
        "multiRegion": [
           [SearchImageByPicResponseBodyPicInfoMultiRegion],
          ........
          [SearchImageByPicResponseBodyPicInfoMultiRegion]
        ]
      }
    }

SearchImageByName

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    var picContent = fs.createReadStream("D:/123.jpg");
    async function demo() {
      const searchImageByNameRequest = new imagesearch.SearchImageByNameRequest({
         // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXX",
        // Required. The ID of the product. The ID cannot exceed 512 characters in length. 
        // A product ID can correspond to multiple image names. 
        productId: "123455",
        // Required. The name of the image. The name cannot exceed 512 characters in length. 
       // 1. Required. An image is uniquely identified by the product ID (ProductId) and image name (PicName). 
        picName: "this",
        // Optional. The ID of the product category. 
        // 1. For product search: If a category is specified, the specified category prevails. If no category is specified, the system estimates and selects a category. The category selected by the system is included in the response. 
        // 2. For cloth, brand, and generic image searches: The category ID is set to 88888888 regardless of whether a category ID is set. 
        categoryId: 3,
        // Optional. The number of entries to be returned. Valid values: 1 to 100. Default value: 10. 
        num: 10,
        // Optional. The ordinal number of the first entry that is returned. Valid values: 0 to 499. Default value: 0. 
        start: 0, // Optional. Specifies whether to recognize the subject in the image. Default value: true. 
        // 1. If you set this parameter to true, the system recognizes the subject in the image, and searches for images based on the recognized subject. The response includes the recognition result. 
        // 2. If you set this parameter to false, the system searches for images based on the entire image without subject recognition. 
        // 3. For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. 
        crop: true,
        // Optional. The subject area of the image, in the format of x1,x2,y1,y2. Specifically, x1 and y1 specify the upper-left pixel, and x2 and y2 specify the lower-right pixel. The specified region cannot cross the boundary of the image. 
        // If you set the Region parameter, the search is conducted based on the value of the Region parameter regardless of the value of the Crop parameter. 
        // 3. For cloth image searches, this parameter does not take effect. The system searches for images based on the entire image. region: "167,467,221,407", // Optional. The filter conditions.
        // int_attr supports the following operators: >, >=, <, <= and =. str_attr supports the = and =! operators. You can set the logical operator between conditions to AND or OR. 
        // Examples:
        // 1. Filter images based on the int_attr field: int_attr>=100.
        // 2. Filter images based on StrAttr: str_attr!="value1".
        // 3. Filter images based on int_attr and str_attr fields: int_attr=1000 AND str_attr="value1".
        filter: "int_attr=56 AND str_attr=\"test\""
      });
      const searchImageByNameResponse = await client.searchImageByName(searchImageByNameRequest);
      console.log(2, searchImageByNameResponse);
    }
    demo();
  • Sample responses
    SearchImageByNameResponse {
      requestId: '4B039098-B274-41DE-9A55-32550B6F74E1',
      success: true,
      code: 0,
      msg: 'success',
      auctions: [
        SearchImageByNameResponseAuctions {
          categoryId: 0,
          productId: '1000',
          picName: 'vae.jpg',
          score:1.0,
          sortExprValues: '7.33136443711219e+24;0'
        },
          .........
        SearchImageByNameResponseAuctions {
          categoryId: 0,
          productId: '123455',
          picName: 'this',
          score:1.0,
          sortExprValues: '7.33136443711219e+24;0'
        }
      ],
      head: SearchImageByNameResponseHead {
        docsReturn: 5,
        docsFound: 5,
        searchTime: 11
      },
      picInfo: SearchImageByNameResponsePicInfo {
        categoryId: 0,
          allCategories: [
          [SearchImageByNameResponsePicInfoAllCategories],
          ......
          [SearchImageByNameResponsePicInfoAllCategories]
        ],
         "multiRegion": [
           [SearchImageByPicResponseBodyPicInfoMultiRegion],
          ........
          [SearchImageByPicResponseBodyPicInfoMultiRegion]
        ]
      }
    }

Delete

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    var picContent = fs.createReadStream("D:/123.jpg");
    async function demo() {
      const deleteImageRequest = new imagesearch.DeleteImageRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX",
         // Required. The ID of the product. The ID cannot exceed 512 characters in length. 
         // A product ID can correspond to multiple image names. 
        productId: "123455",
         // Optional. The name of the image. If you do not set this parameter, the system deletes all the images that are related to the specified product ID. If you set this parameter, the system deletes only the image that is specified by the ProductId and PicName parameters. 
        picName: "this"
      });
      const deleteImageResponse = await client.deleteImage(deleteImageRequest);
      console.log(4, deleteImageResponse);
    }
    demo();
  • Sample responses
    DeleteImageResponse {
      requestId: '3965B44B-0584-41DE-8764-0D8B36857CE1',
      success: true,
      message: 'success',
      code: 0
    }

Update

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    async function updateImage() {
      const request = new imagesearch.UpdateImageRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX",
        // Required. The ID of the product. The product ID cannot be changed. 
        productId: "1",
        // Required. The name of the image. The image name cannot be changed. 
        picName: "1",
        // Optional. The attribute of the INT type. The attribute can be used to filter images in image searches. If you set this parameter, the response includes this parameter and its value. 
        intAttr: "11",
        // Optional. The attribute of the STRING type. The value cannot exceed 128 characters in length. The attribute can be used to filter images in image searches. If you set this parameter, the response includes this parameter and its value. 
        strAttr: "text",
        // Optional. The description that you want to add. The value cannot exceed 4,096 characters in length. 
        customContent: "This is a sample description"
      });
      const response = await client.updateImage(request);
      console.log(4, response.body.toMap());
    }
    updateImage();
  • Sample responses
    4 {
      Code: 0,
      RequestId: '1DD89D33-9D60-179A-9D3E-07CA381F07B5',
      Success: true
    }
                        

Detail

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    async function detail() {
      const request = new imagesearch.DetailRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX"
      });
      const response = await client.detail(request);
      console.log(4, response.body.toMap());
    }
    detail();
  • Sample responses
    4 {
      Instance: {
        Capacity: 10,
        Name: 'xxxxxx',
        Qps: 1,
        Region: 'cn-shanghai',
        ServiceType: 0,
        TotalCount: 99999,
        UtcCreate: '1620382716000',
        UtcExpireTime: '1623081600000'
      },
      RequestId: '84ADF9D3-3668-1837-B0A9-ADB093F77DB2',
      Success: true
    }
                        

DumpMeta

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    async function dumpMeta() {
      const request = new imagesearch.DumpMetaRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX"
      });
      const response = await client.dumpMeta(request);
      console.log(4, response.body.toMap());
    }
    dumpMeta();
  • Sample responses
    4 {
      Data: { DumpMetaStatus: 'PROCESSING', Id: '571' },
      RequestId: '8B639BD9-5EAB-127D-89EF-3EBE3277E02F',
      Success: true
    }
                        

DumpMetaList

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    async function dumpMetaList() {
      const request = new imagesearch.DumpMetaListRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX",
        // Optional. The ID of the task that is used to export metadata. 
        id: 567,
        // Optional. The ordinal number of the first entry that is returned. Default value: 1. 
        pageNumber: 1,
        // Optional. The number of entries to be returned. Default value: 20. 
        pageSize: 1
      });
      const response = await client.dumpMetaList(request);
      console.log(4, response.body.toMap());
      console.log(4, response.body.data.dumpMetaList);
    }
    dumpMetaList();
  • Sample responses
    4 {
      Data: {
        DumpMetaList: [ [Object] ],
        PageNumber: 1,
        PageSize: 1,
        TotalCount: 1
      },
      RequestId: 'BFE47106-BF23-1581-A3AB-F3F54D8866BC'
    }
    4 [
      DumpMetaListResponseBodyDataDumpMetaList {
        code: '0',
        id: 567,
        metaUrl: 'https://xxx/xxx',
        msg: 'success',
        status: 'SUCCESS',
        utcCreate: '1639969113000',
        utcModified: 1639969140000
      }
    ]
    
                        

BatchTask

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    async function batchTask() {
      const request = new imagesearch.IncreaseInstanceRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX"
        // Required. If images are stored in an Object Storage Service (OSS) bucket, enter the bucket name. 
        bucketName: "xxxx",
        // Required. The path to the service where the images are stored. The path must start with a forward slash (/) and cannot end with a forward slash (/). 
        path: "/public/xxx",
        // Optional. The callback address if the call succeeds. The address must start with the string http:// or https://. 
        callbackAddress: "http://xxx/xx"
      });
      const response = await client.increaseInstance(request);
      console.log(4, response.body.toMap());
    }
    batchTask();
  • Sample responses
    4 {
      Data: { Id: '1474', IncrementStatus: 'PROCESSING' },
      RequestId: 'E2AF05CC-F642-1481-BD97-70DC7EBAF7C8',
      Success: true
    }
                        

BatchTaskList

  • Sample code
    const oss = require('@alicloud/oss-util');
    const fs = require('fs');
    const imagesearch = require('@alicloud/imagesearch20201214')
    const client = new imagesearch.default({
      accessKeyId: "XXXXXXXXXX",
      accessKeySecret: "XXXXXXXXXXXXX",
      type: "access_key",
      endpoint: "imagesearch.cn-shanghai.aliyuncs.com",
      regionId: "cn-shanghai",
      protocol: 'http'
    });
    async function batchTaskList() {
      const request = new imagesearch.IncreaseListRequest({
        // Required. The name of the Image Search instance. 
        instanceName: "XXXXXXXXXXXXXXXXXX",
        // Required. If images are stored in an OSS bucket, enter the bucket name. 
        bucketName: "xxxx",
        // Required. The path to the service where the images are stored. The path must start with a forward slash (/) and cannot end with a forward slash (/). 
        path: "/public/xxx",
        // Optional. The ID of the task that is used to export metadata. 
        id: 1464,
        // Optional. The ordinal number of the first entry that is returned. Default value: 1. 
        pageNumber: 1,
        // Optional. The number of entries to be returned. Default value: 20. 
        pageSize: 1
      });
      const response = await client.increaseList(request);
      console.log(4, response.body.toMap());
      console.log(4, response.body.data.increments.toMap());
    }
    batchTaskList();
  • Sample responses
    4 {
      Data: {
        Increments: { Instance: [Array] },
        PageNumber: 1,
        PageSize: 1,
        TotalCount: 1
      },
      RequestId: 'F51B5D0D-3E10-170B-88ED-79997736C6E8'
    }
    4 {
      Instance: [
        {
          BucketName: 'cccxxx',
          Code: '0',
          ErrorUrl: 'https://x/x',
          Id: 1464,
          Msg: 'success',
          Path: '/public/xxx',
          Status: 'NORMAL',
          UtcCreate: '1639107872000',
          UtcModified: 1639125540000
        }
      ]
    }