Spring AI with Typesense Vector Database: Spring Boot Integration Guide

In modern AI-powered applications, vector search is a crucial component for enabling fast, efficient, and intelligent information retrieval. TypeSense, an open-source search engine, provides robust vector-based search capabilities, making it an excellent choice for integrating AI-driven search functionality into applications.

This sequence diagram shows the interaction between the User, ProductController, ProductRepository, TypeSenseTemplate, and the TypeSense Database during two main operations: saving and searching for a product.

  1. Saving a Product:

    • The User sends a POST request with product data to the ProductController.
    • The ProductController passes the data to the ProductRepository, which calls the TypeSenseTemplate to store the product using the upsert() method.
    • The TypeSenseTemplate communicates with the TypeSense Database, which saves the product.
    • The ProductController responds to the User, confirming that the product has been saved.
  2. Searching for Products:

    • The User sends a GET request with a search query to the ProductController.
    • The ProductController calls the ProductRepository, which then calls the TypeSenseTemplate to search for matching products using the query.
    • The TypeSenseTemplate retrieves the products from the TypeSense Database.
    • The ProductController sends the list of matching products back to the User.

This flow covers both product storage and search functionality in the system.

This guide walks you through an end-to-end implementation of Spring Boot with TypeSense Vector Database using Spring AI. You'll learn how to:
✅ Set up a Spring Boot project with Spring AI - TypeSense integration
✅ Configure TypeSense for vector-based search
✅ Create a REST API to store and search products using TypeSense
✅ Run and test the application using Postman or cURL

By the end of this guide, you will have a fully functional AI-powered search system that leverages Spring Boot and TypeSense, enabling high-performance search capabilities for your applications. 🚀


Step 1: Set Up a Spring Boot Project

1.1. Create a New Spring Boot Project using Spring Initializr

  • Go to Spring Initializr
  • Select Maven Project
  • Choose Java as the language
  • Spring Boot Version: 3.x.x
  • Add the following dependencies:
    • Spring Web (For REST API)
    • Lombok (For reducing boilerplate code)
    • Spring AI - TypeSense Vector Database (spring-ai-typesense-store-spring-boot-starter)
  • Extract the ZIP and open it in your favorite IDE (IntelliJ, VS Code, Eclipse).

Step 2: Complete pom.xml

Make sure the following dependencies are in your pom.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.4.2</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
		<spring-ai.version>1.0.0-M5</spring-ai.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.ai</groupId>
			<artifactId>spring-ai-typesense-store-spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.ai</groupId>
				<artifactId>spring-ai-bom</artifactId>
				<version>${spring-ai.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<annotationProcessorPaths>
						<path>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</path>
					</annotationProcessorPaths>
				</configuration>
			</plugin>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>
	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
			<snapshots>
				<enabled>false</enabled>
			</snapshots>
		</repository>
	</repositories>

</project>

Step 3: Install & Start TypeSense Vector Database

3.1. Run TypeSense via Docker

If you don’t have TypeSense installed, you can run it using Docker:

docker run -d -p 8108:8108 -v/tmp/typesense-data:/data typesense/typesense:0.24.1 \
  --data-dir /data --api-key=your-typesense-api-key

Alternatively, if you want to run TypeSense manually, follow the official guide.


Step 4: Configure TypeSense in application.yml

In your src/main/resources/application.yml file, add the following configuration:

spring:
  ai:
    typesense:
      host: http://localhost
      port: 8108
      api-key: your-typesense-api-key
      protocol: http

Step 5: Create a Data Model

Define a simple Product model that we will store in TypeSense.

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Product {
    private String id;
    private String name;
    private String description;
    private double price;
}

Step 6: Create a Repository for TypeSense

This repository class will interact with TypeSense for storing and searching products.

import org.springframework.ai.typesense.client.TypeSenseTemplate;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public class ProductRepository {
    private final TypeSenseTemplate typeSenseTemplate;

    public ProductRepository(TypeSenseTemplate typeSenseTemplate) {
        this.typeSenseTemplate = typeSenseTemplate;
    }

    // Save product in TypeSense
    public void save(Product product) {
        typeSenseTemplate.index("products").upsert(product);
    }

    // Search products based on query
    public List<Product> search(String query) {
        return typeSenseTemplate.index("products").search(query, Product.class);
    }
}

Step 7: Create a REST Controller

Expose API endpoints to interact with TypeSense via REST.

import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/products")
public class ProductController {
    private final ProductRepository productRepository;

    public ProductController(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @PostMapping
    public String saveProduct(@RequestBody Product product) {
        productRepository.save(product);
        return "Product saved!";
    }

    @GetMapping("/search")
    public List<Product> searchProducts(@RequestParam String query) {
        return productRepository.search(query);
    }
}

Step 8: Run & Test the Application

8.1. Start Your Spring Boot App

mvn spring-boot:run

8.2. Test API Using Postman or curl

Add a product

curl -X POST http://localhost:8080/products \
  -H "Content-Type: application/json" \
  -d '{"id":"1", "name":"Laptop", "description":"High-performance laptop", "price":999.99}'

Search for products

curl "http://localhost:8080/products/search?query=Laptop"

Step 9: Summary

Spring Boot setup with TypeSense Vector Database
Spring AI integration for semantic search
End-to-end REST API for indexing and querying

Now, you can build AI-powered search applications with Spring Boot and TypeSense! 🚀

Comments

Popular posts from this blog

Spring Boot OpenAI Integration: Step-by-Step Guide

Orchestration-Based Saga Architecture and Spring Boot Microservices Implementation Guide

Spring Boot 3 + Angular 15 + Material - Full Stack CRUD Application Example