Toll Free:

1800 889 7020

Integrating Vector Search with Spring AI

Spring is a Java framework responsible for creating scalable, high-performance application by providing features for dependency injection, data access, and microservices. It plays a important role in modern Java development services, enabling developers to create robust and efficient solutions. Vector AI, on the other hand, provides vector-based search and semantic comprehension, allowing for smart retrieval and customization. Let us explore an integration between vector search and Spring AI. Vector search, also called semantic search, is a strong method used to find valuable data by analyzing the meaning of text instead of just matching keywords. Advancements in embeddings by OpenAI have simplified the process of incorporating vector search for different uses.
  • Embeddings Creation: Text is transformed into numerical vectors using pre-trained AI models, such as GPT. These vectors represent the semantic meaning of the text in a high-dimensional space.
  • Indexing: The vectors are indexed through an algorithm e.g. Approximate nearest neighbor (ANN) to give better comparison and retrieval to the users.
  • Search: When a user submits a query, it is converted into a vector and compared against the indexed vectors to find the most relevant matches based on the proximity in the vector space.
  • Retrieval: The system returns the results ranked by semantic similarity, ensuring the most meaningful matches appear first.

1.2 Key Benefits

  • Improved optimization: Vector search returns more accurate results by understanding the query meaning rather than just relying on exact word matches
  • Synonym mapping: Easily identifies synonyms or variations, e.g., “car” and “automobile.”
  • Contextual Understanding: Considers the context of terms, making it ideal for complex queries.
  • Scalability: Works well with large datasets, as embeddings are compact and efficient.
  • Multilingual Support: Enables search across languages using embeddings that represent meaning universally.

1.3 Use Cases

  • Chatbots and Virtual Assistants: Ensures accurate responses by matching user queries to relevant answers based on meaning.
  • Recommendation Systems: Powers personalized recommendations in e-commerce, streaming platforms, and more.
  • Document Retrieval: Ideal for industries like law, medicine, or academia to find relevant documents quickly.
  • Image Search: Matches similar images based on semantic representations.
  • Personalized Content Delivery: Social media platforms and news aggregators can serve tailored content.
  • Intelligent Customer Support: Links user queries to support articles or FAQs with contextual relevance.

2. How to generate an OpenAI API key?

We will now understand how to obtain an OpenAI key required for this article.
  • Go to the OpenAI website. Sign up for a new account or use the existing open ai account.
  • After logging in, go to API key section.
  • Select the option to create a new API key. Assign a name or description to the key for easy reference.
  • Click the Generate Key button. Make sure to copy the newly created API key and store it in a safe place, as you will need it to access OpenAI’s services.

3. Code example

3.1 Adding Jar dependencies

Add the following code to your build.grade file. The file will download the required jar dependencies needed for this article.
plugins {
    id 'java'
    id 'org.springframework.boot' version '3.3.5'
    id 'io.spring.dependency-management' version '1.1.6'
}

group = 'com.aegisc'
version = '0.0.1-SNAPSHOT'

java {
    toolchain {
       languageVersion = JavaLanguageVersion.of(21)
    }
}

repositories {
    mavenCentral()
    maven { url 'https://repo.spring.io/milestone' }
}

ext {
    set('springAiVersion', "1.0.0-M3")
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation 'org.springframework.ai:spring-ai-openai-spring-boot-starter'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
}

dependencyManagement {
    imports {
       mavenBom "org.springframework.ai:spring-ai-bom:${springAiVersion}"
    }
}

tasks.named('test') {
    useJUnitPlatform()
}

3.2 Update the application properties file

Replace the existing code with below in the application.properties file. Remember to change the OpenAI key with your open ai api key.
# application properties
server.port=9091
spring.application.name=demo
spring.main.banner-mode=off

# open ai api key
spring.ai.openai.apikey=your_openai_api_key

3.3 Creating a configuration class

Create a configuration class to specify the Vector store. Once the application is started, the bean will be automatically created.
package com.demo.config;

import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class VectorStoreConfig {

    @Bean
    VectorStore vectorStore(EmbeddingModel model) {
        return new SimpleVectorStore(model);
    }
}

3.4 Creating the service class

Create a service class that generates the documents from the Vector stored based on the input query.
package com.demo.service;

import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.VectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class VectorService {

    @Autowired
    VectorStore vectorStore;

    public List<Document> simpleVector(String query) {
        List<Document> documents = List.of(
                new Document(
                        "Spring Framework simplifies development across multiple domains.".repeat(3),
                        Map.of("author", "John Doe", "category", "Tech")
                ),
                new Document("Cloud Computing: The Next Frontier in Software Architecture"),
                new Document("Exploring the Evolution of Microservices Architecture"),
                new Document(
                        "Innovative solutions emerge when we challenge the status quo.",
                        Map.of("author", "Jane Smith", "category", "Innovation")
                )
        );

        vectorStore.add(documents);

        return vectorStore.similaritySearch(
                SearchRequest.defaults()
                        .withQuery(query)
                        .withTopK(2)
        );
    }
}

3.4.1 Code explanation

  • The VectorService class is a Spring service component that provides a similar search functionality on a collection of documents using a vector store.
  • The simpleVector method initializes a list of Document objects, where each document in the list is a text content with optional metadata in the form of a key and value.
  • The vectorStore is used to store these documents by calling its add method, enabling further operations on the collection.
  • Lastly, the method performs a similarity search based on the provided query. It uses a SearchRequest static object to configure with the default settings and specifies the query text and the topK parameter retrieves the two most similar documents from the store. The result is a list of Document objects matching the query, demonstrating how the service enables efficient content search.

3.5 Creating the controller class

Create a controller class responsible for handling the clients’s request. The HTTP GET controller endpoint will accept an query parameter and will be passed to the service for generating the output response.
package com.demo.controller;

import com.demo.service.VectorService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class VectorCtrl {

    @Autowired
    VectorService vectorService;

    // Api endpoint: http://localhost:9091/api/gen?query=Spring
    @GetMapping("/gen")
    public String generateVectorToSearch(@RequestParam String query) {
        System.out.println("Api triggered for query= " + query);
        String content = vectorService.simpleVector(query)
                .getFirst()
                .getContent();
        System.out.println("Result collected. Returning result.");
        return content;
    }
}

3.6 Creating the main class

Create a main application that will serve as an entry point for the application.
package com.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
        System.out.println("Application started successfully...");
    }
}

4. Demo

Run the application and once the application is started hit the below api endpoint on the browser of your choice.
http://localhost:9091/api/gen?query=Spring
Once the endpoint is triggered the following output will be displayed. The backend system will perform the vector store similar search for the given query parameter and return the output to the user. You’re free to change the query parameter input as per your choice and play with this tutorial. // Fig. 1: Demo image

5. Conclusion

Spring, Generative Ai development Services and Vector AI together offer a robust foundation for building intelligent, scalable applications. While Spring streamlines application development with powerful tools and flexibility, Vector AI enhances user experience through semantic understanding and efficient data retrieval. This synergy enables developers to create modern, context-aware, and high-performance solutions for diverse industries.

6. Download the code

Download
You can download the full source code of this example here: Download

Harsh Savani

Harsh Savani is an accomplished Business Analyst with a strong track record of bridging the gap between business needs and technical solutions. With 15+ of experience, Harsh excels in gathering and analyzing requirements, creating detailed documentation, and collaborating with cross-functional teams to deliver impactful projects. Skilled in data analysis, process optimization, and stakeholder management, Harsh is committed to driving operational efficiency and aligning business objectives with strategic solutions.

Scroll to Top