


Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model
Introduction
Imagine you’re shopping online and come across a product you love but don’t know its name. Wouldn’t it be amazing to upload a picture and have the app find it for you?
In this article, we’ll show you how to build exactly that: an image-based product search feature using Spring Boot and Google Cloud Vertex AI.
Overview of the Feature
This feature allows users to upload an image and receive a list of products that match it, making the search experience more intuitive and visually driven.
The image-based product search feature leverages Google Cloud Vertex AI to process images and extract relevant keywords. These keywords are then used to search for matching products in the database.
Technology Stack
- Java 21
- Spring boot 3.2.5
- PostgreSQL
- Vertex AI
- ReactJS
We’ll walk through the process of setting up this functionality step-by-step.
Step-by-Step Implementation
1. Create a new project on Google Console
First, we need to create a new project on Google Console for this.
We need to go to https://console.cloud.google.com and create a new account if you already have one. If you have one, sign in to the account.
If you add your bank account, Google Cloud will offer you a free trial.
Once you have created an account or signed in to an already existing account, you can create a new project.
2. Enable Vertex AI Service
On the search bar, we need to find Vertex AI and enable all recommended APIs.
Vertex AI is Google Cloud’s fully managed machine learning (ML) platform designed to simplify the development, deployment, and management of ML models. It allows you to build, train, and deploy ML models at scale by providing tools and services like AutoML, custom model training, hyperparameter tuning, and model monitoring
Gemini 1.5 Flash is part of Google’s Gemini family of models, specifically designed for efficient and high-performance inference in ML applications. Gemini models are a series of advanced AI models developed by Google, often used in natural language processing (NLP), vision tasks, and other AI-powered applications
Note: For other frameworks, you can use Gemini API directly at https://aistudio.google.com/app/prompts/new_chat. Use the structure prompt feature because you can customize your output to match the input so you will get better results.
3. Create a new prompt that matches your application
At this step, we need to customize a prompt that matching with your application.
Vertex AI Studio has provided a lot of sample prompts at Prompt Gallery. We use sample Image text to JSON to extract keywords that are related to the product image.
My application is a CarShop, so I build a prompt like this. My expectation the model will respond to me with a list of keywords relating to the image.
My prompt: Extract the name car to a list keyword and output them in JSON. If you don’t find any information about the car, please output the list empty.nExample response: [”rolls”, ”royce”, ”wraith”]
After we customize a suitable prompt with your application. Now, we go to explore how to integrate with Spring Boot Application.
4. Integrate with Spring Boot Application
I have built an E-commerce application about cars. So I want to find cars by the image.
First, in the pom.xml file, you should update your dependency:
<!-- config version for dependency--> <properties> <spring-cloud-gcp.version>5.1.2</spring-cloud-gcp.version> <google-cloud-bom.version>26.32.0</google-cloud-bom.version> </properties> <!-- In your dependencyManagement, please add 2 dependencies below --> <dependencyManagement> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>spring-cloud-gcp-dependencies</artifactId> <version>${spring-cloud-gcp.version}</version> <type>pom</type> <scope>import</scope> </dependency> <dependency> <groupId>com.google.cloud</groupId> <artifactId>libraries-bom</artifactId> <version>${google-cloud-bom.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <!-- In your tab dependencies, please add the dependency below --> <dependencies> <dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-vertexai</artifactId> </dependency> </dependencies>
After you have done the config in the pom.xml file, you create a config class GeminiConfig.java
- MODEL_NAME: “gemini-1.5-flash”
- LOCATION: “Your location when setting up the project”
- PROJECT_ID: “your project ID ”
import com.google.cloud.vertexai.VertexAI; import com.google.cloud.vertexai.generativeai.GenerativeModel; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration(proxyBeanMethods = false) public class GeminiConfig { private static final String MODEL_NAME = "gemini-1.5-flash"; private static final String LOCATION = "asia-southeast1"; private static final String PROJECT_ID = "yasmini"; @Bean public VertexAI vertexAI() { return new VertexAI(PROJECT_ID, LOCATION); } @Bean public GenerativeModel getModel(VertexAI vertexAI) { return new GenerativeModel(MODEL_NAME, vertexAI); } }
Second, create layers Service, Controller to implement the find car function. Create class service.
Because the Gemini API responds with markdown format, we need to create a function to help convert to JSON, and from JSON we will convert to List string in Java.
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.cloud.vertexai.api.Content; import com.google.cloud.vertexai.api.GenerateContentResponse; import com.google.cloud.vertexai.api.Part; import com.google.cloud.vertexai.generativeai.*; import com.learning.yasminishop.common.entity.Product; import com.learning.yasminishop.common.exception.AppException; import com.learning.yasminishop.common.exception.ErrorCode; import com.learning.yasminishop.product.ProductRepository; import com.learning.yasminishop.product.dto.response.ProductResponse; import com.learning.yasminishop.product.mapper.ProductMapper; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.multipart.MultipartFile; import java.util.HashSet; import java.util.List; import java.util.Objects; import java.util.Set; @Service @RequiredArgsConstructor @Slf4j @Transactional(readOnly = true) public class YasMiniAIService { private final GenerativeModel generativeModel; private final ProductRepository productRepository; private final ProductMapper productMapper; public List<ProductResponse> findCarByImage(MultipartFile file){ try { var prompt = "Extract the name car to a list keyword and output them in JSON. If you don't find any information about the car, please output the list empty.\nExample response: [\"rolls\", \"royce\", \"wraith\"]"; var content = this.generativeModel.generateContent( ContentMaker.fromMultiModalData( PartMaker.fromMimeTypeAndData(Objects.requireNonNull(file.getContentType()), file.getBytes()), prompt ) ); String jsonContent = ResponseHandler.getText(content); log.info("Extracted keywords from image: {}", jsonContent); List<String> keywords = convertJsonToList(jsonContent).stream() .map(String::toLowerCase) .toList(); Set<Product> results = new HashSet<>(); for (String keyword : keywords) { List<Product> products = productRepository.searchByKeyword(keyword); results.addAll(products); } return results.stream() .map(productMapper::toProductResponse) .toList(); } catch (Exception e) { log.error("Error finding car by image", e); return List.of(); } } private List<String> convertJsonToList(String markdown) throws JsonProcessingException { ObjectMapper objectMapper = new ObjectMapper(); String parseJson = markdown; if(markdown.contains("``` json")){ parseJson = extractJsonFromMarkdown(markdown); } return objectMapper.readValue(parseJson, List.class); } private String extractJsonFromMarkdown(String markdown) { return markdown.replace(" ```json\n", "").replace("\n``` ", ""); } }
We need to create a controller class to make an endpoint for front end
import com.learning.yasminishop.product.dto.response.ProductResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.util.List; @RestController @RequestMapping("/ai") @RequiredArgsConstructor @Slf4j public class YasMiniAIController { private final YasMiniAIService yasMiniAIService; @PostMapping public List<ProductResponse> findCar(@RequestParam("file") MultipartFile file) { var response = yasMiniAIService.findCarByImage(file); return response; } }
5. IMPORTANT step: Login to Google Cloud with Google Cloud CLI
The Spring Boot Application can not verify who you are and isn't able for you to accept the resource in Google Cloud.
So we need to log in to Google and provide authorization.
5.1 First we need to install GCloud CLI on your machine
Link tutorial: https://cloud.google.com/sdk/docs/install
Check the above link and install it on your machine
5.2 Login
- Open your terminal at the project (you must cd into the project)
- Type: gcloud auth login
- Enter, and you will see the windows that allow you to login
gcloud auth login
Note: After you log in, credentials are saved in the Google Maven package, and you don’t need to log in again when restart the Spring Boot application.
Conclusion
So these implement above based on my project E-commerce, you can modify matching with your project, and your framework. In other frameworks, not spring boot (NestJs, ..), you can use https://aistudio.google.com/app/prompts/new_chat. and don’t need to create a new Google Cloud account.
You can check the detailed implementation at my repo:
Backend: https://github.com/duongminhhieu/YasMiniShop
Front-end: https://github.com/duongminhhieu/YasMini-Frontend
Happy learning !!!
The above is the detailed content of Image-Based Product Search Using Spring Boot, Google Cloud Vertex AI, and Gemini Model. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Java supports asynchronous programming including the use of CompletableFuture, responsive streams (such as ProjectReactor), and virtual threads in Java19. 1.CompletableFuture improves code readability and maintenance through chain calls, and supports task orchestration and exception handling; 2. ProjectReactor provides Mono and Flux types to implement responsive programming, with backpressure mechanism and rich operators; 3. Virtual threads reduce concurrency costs, are suitable for I/O-intensive tasks, and are lighter and easier to expand than traditional platform threads. Each method has applicable scenarios, and appropriate tools should be selected according to your needs and mixed models should be avoided to maintain simplicity

In Java, enums are suitable for representing fixed constant sets. Best practices include: 1. Use enum to represent fixed state or options to improve type safety and readability; 2. Add properties and methods to enums to enhance flexibility, such as defining fields, constructors, helper methods, etc.; 3. Use EnumMap and EnumSet to improve performance and type safety because they are more efficient based on arrays; 4. Avoid abuse of enums, such as dynamic values, frequent changes or complex logic scenarios, which should be replaced by other methods. Correct use of enum can improve code quality and reduce errors, but you need to pay attention to its applicable boundaries.

JavaNIO is a new IOAPI introduced by Java 1.4. 1) is aimed at buffers and channels, 2) contains Buffer, Channel and Selector core components, 3) supports non-blocking mode, and 4) handles concurrent connections more efficiently than traditional IO. Its advantages are reflected in: 1) Non-blocking IO reduces thread overhead, 2) Buffer improves data transmission efficiency, 3) Selector realizes multiplexing, and 4) Memory mapping speeds up file reading and writing. Note when using: 1) The flip/clear operation of the Buffer is easy to be confused, 2) Incomplete data needs to be processed manually without blocking, 3) Selector registration must be canceled in time, 4) NIO is not suitable for all scenarios.

HashMap implements key-value pair storage through hash tables in Java, and its core lies in quickly positioning data locations. 1. First use the hashCode() method of the key to generate a hash value and convert it into an array index through bit operations; 2. Different objects may generate the same hash value, resulting in conflicts. At this time, the node is mounted in the form of a linked list. After JDK8, the linked list is too long (default length 8) and it will be converted to a red and black tree to improve efficiency; 3. When using a custom class as a key, the equals() and hashCode() methods must be rewritten; 4. HashMap dynamically expands capacity. When the number of elements exceeds the capacity and multiplies by the load factor (default 0.75), expand and rehash; 5. HashMap is not thread-safe, and Concu should be used in multithreaded

Java enumerations not only represent constants, but can also encapsulate behavior, carry data, and implement interfaces. 1. Enumeration is a class used to define fixed instances, such as week and state, which is safer than strings or integers; 2. It can carry data and methods, such as passing values through constructors and providing access methods; 3. It can use switch to handle different logics, with clear structure; 4. It can implement interfaces or abstract methods to make differentiated behaviors of different enumeration values; 5. Pay attention to avoid abuse, hard-code comparison, dependence on ordinal values, and reasonably naming and serialization.

Singleton design pattern in Java ensures that a class has only one instance and provides a global access point through private constructors and static methods, which is suitable for controlling access to shared resources. Implementation methods include: 1. Lazy loading, that is, the instance is created only when the first request is requested, which is suitable for situations where resource consumption is high and not necessarily required; 2. Thread-safe processing, ensuring that only one instance is created in a multi-threaded environment through synchronization methods or double check locking, and reducing performance impact; 3. Hungry loading, which directly initializes the instance during class loading, is suitable for lightweight objects or scenarios that can be initialized in advance; 4. Enumeration implementation, using Java enumeration to naturally support serialization, thread safety and prevent reflective attacks, is a recommended concise and reliable method. Different implementation methods can be selected according to specific needs

Optional can clearly express intentions and reduce code noise for null judgments. 1. Optional.ofNullable is a common way to deal with null objects. For example, when taking values from maps, orElse can be used to provide default values, so that the logic is clearer and concise; 2. Use chain calls maps to achieve nested values to safely avoid NPE, and automatically terminate if any link is null and return the default value; 3. Filter can be used for conditional filtering, and subsequent operations will continue to be performed only if the conditions are met, otherwise it will jump directly to orElse, which is suitable for lightweight business judgment; 4. It is not recommended to overuse Optional, such as basic types or simple logic, which will increase complexity, and some scenarios will directly return to nu.

The core workaround for encountering java.io.NotSerializableException is to ensure that all classes that need to be serialized implement the Serializable interface and check the serialization support of nested objects. 1. Add implementsSerializable to the main class; 2. Ensure that the corresponding classes of custom fields in the class also implement Serializable; 3. Use transient to mark fields that do not need to be serialized; 4. Check the non-serialized types in collections or nested objects; 5. Check which class does not implement the interface; 6. Consider replacement design for classes that cannot be modified, such as saving key data or using serializable intermediate structures; 7. Consider modifying
