Redis

This section walks you through setting up RedisVectorStore to store document embeddings and perform similarity searches.

Redis is an open source (BSD licensed), in-memory data structure store used as a database, cache, message broker, and streaming engine. Redis provides data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes, and streams.

Redis Search and Query extends the core features of Redis OSS and allows you to use Redis as a vector database:

  • Store vectors and the associated metadata within hashes or JSON documents

  • Retrieve vectors

  • Perform vector searches

Prerequisites

  1. A Redis Stack instance

  2. EmbeddingModel instance to compute the document embeddings. Several options are available:

    • If required, an API key for the EmbeddingModel to generate the embeddings stored by the RedisVectorStore.

Auto-configuration

Spring AI provides Spring Boot auto-configuration for the Redis Vector Store. To enable it, add the following dependency to your project’s Maven pom.xml file:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-redis-store-spring-boot-starter</artifactId>
</dependency>

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-redis-store-spring-boot-starter'
}
Refer to the Dependency Management section to add the Spring AI BOM to your build file.
Refer to the Repositories section to add Milestone and/or Snapshot Repositories to your build file.

The vector store implementation can initialize the requisite schema for you, but you must opt-in by specifying the initializeSchema boolean in the appropriate constructor or by setting …​initialize-schema=true in the application.properties file.

this is a breaking change! In earlier versions of Spring AI, this schema initialization happened by default.

Please have a look at the list of configuration parameters for the vector store to learn about the default values and configuration options.

Additionally, you will need a configured EmbeddingModel bean. Refer to the EmbeddingModel section for more information.

Now you can auto-wire the RedisVectorStore as a vector store in your application.

@Autowired VectorStore vectorStore;

// ...

List <Document> documents = List.of(
    new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", Map.of("meta1", "meta1")),
    new Document("The World is Big and Salvation Lurks Around the Corner"),
    new Document("You walk forward facing the past and you turn back toward the future.", Map.of("meta2", "meta2")));

// Add the documents to Redis
vectorStore.add(documents);

// Retrieve documents similar to a query
List<Document> results = this.vectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(5).build());

Configuration Properties

To connect to Redis and use the RedisVectorStore, you need to provide access details for your instance. A simple configuration can be provided via Spring Boot’s application.yml,

spring:
  data:
    redis:
      uri: <redis instance uri>
  ai:
    vectorstore:
      redis:
        initialize-schema: true
        index-name: custom-index
        prefix: custom-prefix
        batching-strategy: TOKEN_COUNT # Optional: Controls how documents are batched for embedding

Properties starting with spring.ai.vectorstore.redis.* are used to configure the RedisVectorStore:

Property Description Default Value

spring.ai.vectorstore.redis.initialize-schema

Whether to initialize the required schema

false

spring.ai.vectorstore.redis.index-name

The name of the index to store the vectors

spring-ai-index

spring.ai.vectorstore.redis.prefix

The prefix for Redis keys

embedding:

spring.ai.vectorstore.redis.batching-strategy

Strategy for batching documents when calculating embeddings. Options are TOKEN_COUNT or FIXED_SIZE

TOKEN_COUNT

Metadata Filtering

You can leverage the generic, portable metadata filters with Redis as well.

For example, you can use either the text expression language:

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression("country in ['UK', 'NL'] && year >= 2020").build());

or programmatically using the Filter.Expression DSL:

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(SearchRequest.builder()
        .query("The World")
        .topK(TOP_K)
        .similarityThreshold(SIMILARITY_THRESHOLD)
        .filterExpression(b.and(
                b.in("country", "UK", "NL"),
                b.gte("year", 2020)).build()).build());
Those (portable) filter expressions get automatically converted into Redis search queries.

For example, this portable filter expression:

country in ['UK', 'NL'] && year >= 2020

is converted into the proprietary Redis filter format:

@country:{UK | NL} @year:[2020 inf]

Manual Configuration

Instead of using the Spring Boot auto-configuration, you can manually configure the Redis vector store. For this you need to add the spring-ai-redis-store to your project:

<dependency>
    <groupId>org.springframework.ai</groupId>
    <artifactId>spring-ai-redis-store</artifactId>
</dependency>

or to your Gradle build.gradle build file.

dependencies {
    implementation 'org.springframework.ai:spring-ai-redis-store'
}

Create a JedisPooled bean:

@Bean
public JedisPooled jedisPooled() {
    return new JedisPooled("<host>", 6379);
}

Then create the RedisVectorStore bean using the builder pattern:

@Bean
public VectorStore vectorStore(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
    return RedisVectorStore.builder(jedisPooled, embeddingModel)
        .indexName("custom-index")                // Optional: defaults to "spring-ai-index"
        .prefix("custom-prefix")                  // Optional: defaults to "embedding:"
        .metadataFields(                         // Optional: define metadata fields for filtering
            MetadataField.tag("country"),
            MetadataField.numeric("year"))
        .initializeSchema(true)                   // Optional: defaults to false
        .batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy
        .build();
}

// This can be any EmbeddingModel implementation
@Bean
public EmbeddingModel embeddingModel() {
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("OPENAI_API_KEY")));
}

You must list explicitly all metadata field names and types (TAG, TEXT, or NUMERIC) for any metadata field used in filter expressions. The metadataFields above registers filterable metadata fields: country of type TAG, year of type NUMERIC.