Try similar search of Image Search using Java SDK [Search]

Purpose of this time (try searching using Java SDK)

Last time, I finished setting up Image Search and importing images. This time, I will try to access the Image Search I made last time programmatically.

Construction of implementation environment

This time I will create a project in Java. If you do not have a Java development environment, please install Java and Gradle. (The sample is created with Gradle, but Maven is also acceptable)

Reference: For Windows + Scoop

PS C:\Users\user> scoop install oraclejdk14
PS C:\Users\user> scoop install gradle

Creating a Java project

Let's create a Java project

Creating a project directory

PS C:\Users\user\Documents\temp> mkdir imagesearch-sample

    Directory: C:\Users\user\Documents\temp

Mode                 LastWriteTime         Length Name
----                 -------------         ------ ----
d----          2020/05/19    15:59                imagesearch-sample

PS C:\Users\user\Documents\temp> cd .\imagesearch-sample\
PS C:\Users\user\Documents\temp\imagesearch-sample>

Creating a Java project

PS C:\Users\user\Documents\temp\imagesearch-sample> gradle init

Select type of project to generate:
  1: basic
  2: application
  3: library
  4: Gradle plugin
Enter selection (default: basic) [1..4] 2

Select implementation language:
  1: C++
  2: Groovy
  3: Java
  4: Kotlin
  5: Swift
Enter selection (default: Java) [1..5] 3

Select build script DSL:
  1: Groovy
  2: Kotlin
Enter selection (default: Groovy) [1..2] 1

Select test framework:
  1: JUnit 4
  2: TestNG
  3: Spock
  4: JUnit Jupiter
Enter selection (default: JUnit 4) [1..4] 1

Project name (default: imagesearch-sample):
Source package (default: imagesearch.sample):

> Task :init
Get more help with your project:

2 actionable tasks: 2 executed
PS C:\Users\user\Documents\temp\imagesearch-sample>
PS C:\Users\user\Documents\temp\imagesearch-sample> tree /F
List of folder paths:Volume Windows
Volume serial number is 9411-0B65
│  .gitattributes
│  .gitignore
│  build.gradle
│  gradlew
│  gradlew.bat
│  settings.gradle
│  ├─6.4.1
│  │  │
│  │  │
│  │  ├─executionHistory
│  │  │      executionHistory.bin
│  │  │      executionHistory.lock
│  │  │
│  │  ├─fileChanges
│  │  │      last-build.bin
│  │  │
│  │  ├─fileHashes
│  │  │      fileHashes.bin
│  │  │      fileHashes.lock
│  │  │
│  │  └─vcsMetadata-1
│  ├─buildOutputCleanup
│  │      buildOutputCleanup.lock
│  │
│  │      outputFiles.bin
│  │
│  ├─checksums
│  │      checksums.lock
│  │
│  └─vcs-1
│  └─wrapper
│          gradle-wrapper.jar
    │  ├─java
    │  │  └─imagesearch
    │  │      └─sample
    │  │    
    │  │
    │  └─resources
        │  └─imagesearch
        │      └─sample
PS C:\Users\user\Documents\temp\imagesearch-sample>

Add dependency

Add SDK for Alibaba Cloud.


 * This file was generated by the Gradle 'init' task.
 * This generated file contains a sample Java project to get you started.
 * For more details take a look at the Java Quickstart chapter in the Gradle
 * User Manual available at

plugins {
    // Apply the java plugin to add support for Java
    id 'java'

    // Apply the application plugin to add support for building a CLI application.
    id 'application'

repositories {
    // Use jcenter for resolving dependencies.
    // You can declare any Maven/Ivy/file repository here.

dependencies {
    // This dependency is used by the application.
    implementation ''
    // Alibaba Cloud
    compile 'com.aliyun:aliyun-java-sdk-imagesearch:2.0.0'
    compile 'com.aliyun:aliyun-java-sdk-core:[4.3.2,5.0.0)'

    // Use JUnit test framework
    testImplementation 'junit:junit:4.12'

application {
    // Define the main class for the application.
    mainClassName = 'imagesearch.sample.App'

Access the previously created Image Search

Use the access key and secret key created last time. Also, set the region and endpoint from the table below. This time, we will set Japan (Tokyo).

region end point
China(Hong Kong)

The images to be searched are placed in / src / resources. This time, I created it with the name "search01.jpg ". 2020-05-19.png

 * This Java source file was generated by the Gradle 'init' task.
package imagesearch.sample;

import java.util.Base64;
import java.util.List;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.imagesearch.model.v20190325.SearchImageRequest;
import com.aliyuncs.imagesearch.model.v20190325.SearchImageResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

public class App {
    /** AccessKey */
    private static final String ACCESS_KEY = "XXXXXXXXXXXXXXXXXXX";
    /** SeacretKey */
    private static final String KEY_SEACRET = "YYYYYYYYYYYYYYYYYY";

    public static void main(String[] args) throws Exception {
                //Initialization(Tokyo region)
                DefaultProfile.addEndpoint("ap-northeast-1", "ImageSearch", "");
                IClientProfile profile = DefaultProfile.getProfile("ap-northeast-1", ACCESS_KEY, KEY_SEACRET);
                IAcsClient client = new DefaultAcsClient(profile);
                //Make a request for search
                SearchImageRequest request = new SearchImageRequest();
                //Input Required. Image Search instance name.
                //Convert image to Base64
                ClassLoader loader = Thread.currentThread().getContextClassLoader();
                InputStream is = loader.getResourceAsStream("search01.jpg ");
                String image = Base64.getEncoder().encodeToString(is.readAllBytes());
                //Search by image
                SearchImageResponse response = client.getAcsResponse(request);
                //search results
                Boolean checkShowJsonItemName = response.checkShowJsonItemName();
                Integer code = response.getCode();
                SearchImageResponse.Head head = response.getHead();
                Integer docsFound = head.getDocsFound();
                Integer docsReturn = head.getDocsReturn();
                Integer searchTime = head.getSearchTime();
                String msg = response.getMsg();
                String requestId = response.getRequestId();
                Boolean success = response.getSuccess();
                SearchImageResponse.PicInfo picInfo = response.getPicInfo();
                List<SearchImageResponse.PicInfo.Category> categories = picInfo.getAllCategories();
                Integer categoryId = picInfo.getCategoryId();
                String region = picInfo.getRegion();
                System.out.printf("checkShowJsonItemName: %s%ncode: %s%ndocsFound: %s%nsearchTime:%s %nmsg: %s%nrequestId: %s%nsucess: %s%ncategoryId: %s%nregion: %s%n", checkShowJsonItemName, code, docsFound, docsReturn, searchTime, msg, requestId, success, categoryId, region);
                categories.forEach(s -> {
                    Integer id = s.getId();
                    String name = s.getName();
                    System.out.printf("Categories %n\tid: %s, name: %s%n", id, name);
                List<SearchImageResponse.Auction> list = response.getAuctions();
                list.forEach(s -> {
                    String productid = s.getProductId();
                    Integer categoryid = s.getCategoryId();
                    String customCountent = s.getCustomContent();
                    Integer intAttr = s.getIntAttr();
                    String picName = s.getPicName();
                    String sortExpValues = s.getSortExprValues();
                    String strAttr = s.getStrAttr();
                    System.out.printf("productId: %s %nCategoryId: %s %ncustomContent: %s %nintAttr: %s %npicName: %s %nsortExpValues: %s %nStrAttr: %s%n", productid, categoryid, customCountent, intAttr, picName, sortExpValues, strAttr);

checkShowJsonItemName: false
code: 0
docsFound: 11
msg: 99
requestId: success
sucess: 85B66F6E-9932-4BF6-A05F-4AA0AF4D7CD5
categoryId: true
region: 9
        id: 0, name: Tops
        id: 1, name: Dress
        id: 2, name: Bottoms
        id: 3, name: Bag
        id: 4, name: Shoes
        id: 5, name: Accessories
        id: 6, name: Snack
        id: 7, name: Makeup
        id: 8, name: Bottle
        id: 9, name: Furniture
        id: 20, name: Toy
        id: 21, name: Underwear
        id: 22, name: Digital device
        id: 88888888, name: Other
productId: 1011
CategoryId: 9
customContent: k1:v12,k2:v211,k3:v311
intAttr: null 
picName: 12.jpg
sortExpValues: 3.07306838035583;217
StrAttr: null
productId: 1010
CategoryId: 9
customContent: k1:v11,k2:v210,k3:v310
intAttr: null
picName: 11.jpg
sortExpValues: 2.97270393371582;222
StrAttr: null
productId: 1008
CategoryId: 9
customContent: k1:v09,k2:v208,k3:v308
intAttr: null
picName: 09.jpg
sortExpValues: 2.87724995613098;238
StrAttr: null
productId: 1009
CategoryId: 9
customContent: k1:v10,k2:v209,k3:v309
intAttr: null
picName: 10.jpg 
sortExpValues: 2.79507827758789;235
StrAttr: null
productId: 1001
CategoryId: 9
customContent: k1:v02,k2:v201,k3:v301
intAttr: null
picName: 02.jpg
sortExpValues: 2.67687916755676;251
StrAttr: null
productId: 1004
CategoryId: 9
customContent: k1:v05,k2:v204,k3:v304 
intAttr: null
picName: 05.jpg
sortExpValues: 2.67470407485962;249
StrAttr: null
productId: 1005
CategoryId: 9
customContent: k1:v06,k2:v205,k3:v305
intAttr: null
picName: 06.jpg
sortExpValues: 2.66586232185364;254
StrAttr: null
productId: 1003
CategoryId: 9
customContent: k1:v04,k2:v203,k3:v303
intAttr: null
picName: 04.jpg
sortExpValues: 2.63756942749023;255
StrAttr: null
productId: 1000
CategoryId: 9
customContent: k1:v01,k2:v200,k3:v300 
intAttr: null 
picName: 01.jpg
sortExpValues: 2.57631182670593;270
StrAttr: null
productId: 1006
CategoryId: 9
customContent: k1:v07,k2:v206,k3:v306
intAttr: null
picName: 07.jpg
sortExpValues: 2.52564144134521;253
StrAttr: null

The same result as the result thrown from the management screen last time was output.

Source code explanation

//Initialization(Tokyo region case
DefaultProfile.addEndpoint({regionId}, {product}, {endpoint});
IClientProfile profile = DefaultProfile.getProfile({regionId}, {accessKeyId}, {secret})
IAcsClient client = new DefaultAcsClient(profile);

For regionId, specify "ap-northeast-1" for the Tokyo region. Set "Image Search" for product and the endpoint URL in the above list for endpoint. product is a fixed value. It is troublesome to check the value of regionId for other regions. .. ..

//Make a request for search
SearchImageRequest request = new SearchImageRequest();
//Input Required. Image Search instance name.

A request for search is prepared for search, and a request object for addition and deletion is prepared for addition and deletion, respectively. Be careful with the instance name.


You must specify the "name" instead of the "ID".

//Search by image
request.setPicContent({BASE64 encoded image});
SearchImageResponse response = client.getAcsResponse(request);

This time I searched by image. You can also search by registered images or narrow down by parameters. We will verify these next time.

Up to here for this time. You can easily search using the SDK.

Recommended Posts

Try similar search of Image Search using Java SDK [Search]
Try Image Search's similar search using Java SDK [Registration]
Try using Hyperledger Iroha's Java SDK
Try image classification using TensorFlow Lite on Android (JAVA)
Try using RocksDB in Java
Try scraping using java [Notes]
Try Spark Submit to EMR using AWS SDK for Java
Try using Redis with Java (jar)
Handling of time zones using Java
[Java] Try to implement using generics
Try using IBM Java method tracing
Summary of object-oriented programming using Java
[Java] Where did you try using java?
I tried using GoogleHttpClient of Java
Try using Java framework Nablarch [Web application]
Try using || instead of the ternary operator
Try using the Stream API in Java
Study Java Try using Scanner or Map
Try using JSON format API in Java
Try using Microsoft Azure SDK For SQL API of Azure Cosmos DB Service 4.6
Status monitoring of java application using Elasticsearch
Try using JobScheduler's REST-API --Java RestClient implementation--
Acquisition of input contents using Scanner (Java)
Try using the Wii remote with Java
Try adding text to an image in Scala using the Java standard library
[Rails] Implementation of search function using gem's ransack
Try using JobScheduler's REST-API --Java RestClient Test class-
[Rails] Implementation of image enlargement function using lightbox2
Verification of performance impact when using Java volatile
Try local file search using Fess on CentOS7
Try local file search using Fess on CentOS8
Try using Sourcetrail (win version) in Java code
Try using GCP's Cloud Vision API in Java
Try using Sourcetrail (macOS version) in Java code
Try accessing the dataset from Java using JZOS
Try the free version of Progate [Java II]
[Java / Kotlin] Resize considering the orientation of the image
Example of using addition faster than using StringBuilder (Java)
[Rails] Implementation of image slide show using Bootstrap 3
Try communication using gRPC on Android + Java server
Try using the COTOHA API parsing in Java
Story of test automation using Appium [Android / java]
Try the free version of Progate [Java I]
Try using libGDX
Try using Maven
Try using powermock-mockito2-2.0.2
Try using GraalVM
Try Java 8 Stream
Try using jmockit 1.48
Try using SwiftLint
Try using Log4j 2.0
Roughly try Java 9
[Java] Overview of Java
Initialization of for Try to make Java problem TypeScript 5-4
I tried to operate SQS using AWS Java SDK
Try calling IBM Watson Assistant 2018-07-10 from the Java SDK.
Try to implement using Rakuten product search API (easy)
Try global hooking in Java using the JNativeHook library
Try to build a Java development environment using Docker
[Java10] Be careful of using var and generics together
Try using the query attribute of Ruby on Rails