Redis

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

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.spring-doc.cn

Redis Search and Query extends the core features of Redis OSS and allows you to use Redis as a vector database:spring-doc.cn

Prerequisites

  1. A Redis Stack instancespring-doc.cn

  2. EmbeddingModel instance to compute the document embeddings. Several options are available:spring-doc.cn

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:spring-doc.cn

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

or to your Gradle build.gradle build file.spring-doc.cn

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.spring-doc.cn

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

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

Here is an example of the needed bean:spring-doc.cn

@Bean
public EmbeddingModel embeddingModel() {
    // Can be any other EmbeddingModel implementation.
    return new OpenAiEmbeddingModel(new OpenAiApi(System.getenv("SPRING_AI_OPENAI_API_KEY")));
}

To connect to Redis you need to provide access details for your instance. A simple configuration can either be provided via Spring Boot’s application.properties,spring-doc.cn

spring.ai.vectorstore.redis.uri=<your redis instance uri>
spring.ai.vectorstore.redis.index=<your index name>
spring.ai.vectorstore.redis.prefix=<your prefix>

# API key if needed, e.g. OpenAI
spring.ai.openai.api.key=<api-key>

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

Now you can Auto-wire the Redis Vector Store in your application and use itspring-doc.cn

@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.query("Spring").withTopK(5));

Configuration properties

You can use the following properties in your Spring Boot configuration to customize the Redis vector store.spring-doc.cn

Property Description Default value

spring.ai.vectorstore.redis.urispring-doc.cn

Server connection URIspring-doc.cn

redis://localhost:6379spring-doc.cn

spring.ai.vectorstore.redis.indexspring-doc.cn

Index namespring-doc.cn

default-indexspring-doc.cn

spring.ai.vectorstore.redis.initialize-schemaspring-doc.cn

Whether to initialize the required schemaspring-doc.cn

falsespring-doc.cn

spring.ai.vectorstore.redis.prefixspring-doc.cn

Prefixspring-doc.cn

default:spring-doc.cn

Metadata filtering

You can leverage the generic, portable metadata filters with RedisVectorStore as well.spring-doc.cn

For example, you can use either the text expression language:spring-doc.cn

vectorStore.similaritySearch(
   SearchRequest
      .query("The World")
      .withTopK(TOP_K)
      .withSimilarityThreshold(SIMILARITY_THRESHOLD)
      .withFilterExpression("country in ['UK', 'NL'] && year >= 2020"));

or programmatically using the expression DSL:spring-doc.cn

FilterExpressionBuilder b = new FilterExpressionBuilder();

vectorStore.similaritySearch(
   SearchRequest
      .query("The World")
      .withTopK(TOP_K)
      .withSimilarityThreshold(SIMILARITY_THRESHOLD)
      .withFilterExpression(b.and(
         b.in("country", "UK", "NL"),
         b.gte("year", 2020)).build()));

The portable filter expressions get automatically converted into Redis search queries. For example, the following portable filter expression:spring-doc.cn

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

is converted into Redis query:spring-doc.cn

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

Manual configuration

If you prefer not to use the auto-configuration, you can manually configure the Redis Vector Store. Add the Redis Vector Store and Jedis dependenciesspring-doc.cn

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

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>5.1.0</version>
</dependency>
Refer to the Dependency Management section to add the Spring AI BOM to your build file.

Then, create a RedisVectorStore bean in your Spring configuration:spring-doc.cn

@Bean
public VectorStore vectorStore(EmbeddingModel embeddingModel) {
  RedisVectorStoreConfig config = RedisVectorStoreConfig.builder()
     .withURI("redis://localhost:6379")
     // Define the metadata fields to be used
     // in the similarity search filters.
     .withMetadataFields(
        MetadataField.tag("country"),
        MetadataField.numeric("year"))
     .build();

  return new RedisVectorStore(config, embeddingModel);
}

It is more convenient and preferred to create the RedisVectorStore as a Bean. But if you decide to create it manually, then you must call the RedisVectorStore#afterPropertiesSet() after setting the properties and before using the client.spring-doc.cn

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

Then in your main code, create some documents:spring-doc.cn

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

Now add the documents to your vector store:spring-doc.cn

vectorStore.add(documents);

And finally, retrieve documents similar to a query:spring-doc.cn

List<Document> results = vectorStore.similaritySearch(
   SearchRequest
      .query("Spring")
      .withTopK(5));

If all goes well, you should retrieve the document containing the text "Spring AI rocks!!".spring-doc.cn