{
  "schema_version": 3,
  "id": "integrate/spring-ai",
  "title": "Redis with Spring AI",
  "url": "https://redis.io/docs/latest/integrate/spring-ai/",
  "summary": "Use Redis as a Spring AI vector store, chat memory repository, and semantic cache.",
  "tags": [
    "docs",
    "integrate",
    "oss",
    "rs",
    "rc"
  ],
  "last_updated": "2026-11-26T13:47:29Z",
  "children": [],
  "page_type": "content",
  "content_hash": "1eb28a87fcee2b11874ec5bc12c3432c3f2bb244f3620db654f2b006d83a9c5d",
  "sections": [
    {
      "id": "overview",
      "title": "Overview",
      "role": "overview",
      "text": "[Spring AI](https://docs.spring.io/spring-ai/reference/) is a framework for building AI applications on Spring Boot. It has three Redis modules:\n\n| Module | Use it to |\n|--------|-----------|\n| `spring-ai-starter-vector-store-redis` | Store embeddings and run vector, range, and text searches with metadata filters, using [Redis Search](https://redis.io/docs/latest/develop/ai/search-and-query). |\n| `spring-ai-starter-model-chat-memory-repository-redis` | Keep chat history for each conversation, with an optional expiry. |\n| `spring-ai-redis-semantic-cache` | Cache chat responses by the meaning of the prompt, so a similar question skips the model call. |\n\nSee the [semantic cache](https://redis.io/docs/latest/develop/use-cases/semantic-cache), [memory layer](https://redis.io/docs/latest/develop/use-cases/memory-layer), and [recommendation engine](https://redis.io/docs/latest/develop/use-cases/recommendation-engine) use cases for more information about when to use these patterns."
    },
    {
      "id": "requirements",
      "title": "Requirements",
      "role": "content",
      "text": "- A Spring Boot application with a Spring AI [`EmbeddingModel`](https://docs.spring.io/spring-ai/reference/api/embeddings.html) bean. For the semantic cache, you also need a `ChatModel`.\n- Redis with [Redis Search](https://redis.io/docs/latest/develop/ai/search-and-query) and [JSON](https://redis.io/docs/latest/develop/data-types/json) (Redis 8 and later versions include both but earlier versions need Redis Stack).\n\nThe examples on this page were run with Spring AI 2.0.2, Spring Boot 4.1.2, Java 21, and Redis 8.10. They used a small test `EmbeddingModel` and `ChatModel` in place of a provider, so add the Spring AI starter for your own model provider.\n\nAdd the Spring AI bill of materials (BOM) and the Redis modules to your `pom.xml`:\n\n[code example]\n\nSpring AI's Redis modules use the [Jedis](https://redis.io/docs/latest/develop/clients/jedis) client. The vector store's auto-configuration needs a `JedisConnectionFactory` bean, and Spring Boot creates one only when you ask for Jedis. Set `spring.data.redis.client-type` to `jedis`, together with the usual connection settings:\n\n[code example]\n\nWithout `client-type`, the application fails to start with `required a bean of type 'org.springframework.data.redis.connection.jedis.JedisConnectionFactory' that could not be found`, because Boot chooses\n[Lettuce](https://redis.io/docs/latest/develop/clients/lettuce) when both clients are on the classpath."
    },
    {
      "id": "search-embeddings-with-the-vector-store",
      "title": "Search embeddings with the vector store",
      "role": "content",
      "text": "Set `initialize-schema` so that Spring AI creates the index on startup. It is `false` by default, and a search against a missing index fails with `SEARCH_INDEX_NOT_FOUND`:\n\n[code example]\n\nThen inject the `VectorStore`, add documents, and search:\n\n[code example]\n\nSpring AI stores each document as a Redis JSON document under the key prefix, and indexes it with a Redis Search index. The index takes its vector size from your embedding model. The default index name is `spring-ai-index`, the default prefix is `embedding:`, and the default algorithm is\n[HNSW with cosine distance](https://redis.io/docs/latest/develop/ai/search-and-query/vectors#hnsw-index). Set `spring.ai.vectorstore.redis.vector-algorithm` and `spring.ai.vectorstore.redis.distance-metric` to change them."
    },
    {
      "id": "filter-on-metadata",
      "title": "Filter on metadata",
      "role": "content",
      "text": "Declare each metadata key that you filter on, with its type, as a `List<RedisVectorStore.MetadataField>` bean:\n\n[code example]\n\nThen pass a filter expression to the search:\n\n[code example]\n\nA filter on a key that you didn't declare fails with `IllegalArgumentException: Not allowed filter identifier name: country`.\n\nThe vector store also supports `searchByRange()` for all documents within a similarity radius, and `searchByText()` for full-text search on a `text` metadata field. See the [Spring AI Redis vector store reference](https://docs.spring.io/spring-ai/reference/api/vectordbs/redis.html) for those and the HNSW tuning options."
    },
    {
      "id": "keep-chat-history",
      "title": "Keep chat history",
      "role": "content",
      "text": "Add the chat memory starter:\n\n[code example]\n\nThis module reads its own connection properties, not `spring.data.redis.*`. Set them, and an optional expiry:\n\n[code example]\n\nWrap the auto-configured `RedisChatMemoryRepository` in a `ChatMemory`:\n\n[code example]\n\nPass the same `ChatMemory` to a `MessageChatMemoryAdvisor` to give a `ChatClient` this history on every call.\n\nThe repository keeps each message as a Redis JSON document with a key of the form `chat-memory:<conversation id>:<timestamp>`, plus a `chat-memory:counter:<conversation id>` string. `time-to-live` sets a TTL on those keys. It also creates a Redis Search index, `chat-memory-idx` by default, so `AdvancedRedisChatMemoryRepository` can search messages by content, type, time range, and metadata."
    },
    {
      "id": "cache-responses-by-meaning",
      "title": "Cache responses by meaning",
      "role": "content",
      "text": "Add the semantic cache and its auto-configuration module:\n\n[code example]\n\nThe auto-configuration only activates when `spring-ai-transformers` is on the classpath, because its default embedding model is a Transformers model. Without that dependency, no `SemanticCache` bean is created and no error explains why. An `EmbeddingModel` bean in your application replaces the default model. Configure the cache:\n\n[code example]\n\nThen add a `SemanticCacheAdvisor` to the `ChatClient` calls that should use the cache:\n\n[code example]\n\nThe second call returns the first call's answer without calling the model. A prompt with a different meaning, such as `How do I bake bread?`, calls the model. `similarity-threshold` is from 0 to 1, where a higher value specifies that a closer match is required. The cache creates the `semantic-cache-index` index and stores each entry as a JSON document with the key prefix `semantic-cache:`.\n\nTo create the cache yourself instead, use `DefaultSemanticCache` and the Jedis `RedisClient`. Its `distanceThreshold` specifies a distance between vectors, so a lower value is stricter here\n(unlike `similarity-threshold` with the `SemanticCache` bean):\n\n[code example]\n\nThe third argument to `set()` is an optional expiry. A semantic cache returns an earlier response for any prompt that is close enough, but this can be wrong when a small change in wording changes the answer. Set the threshold strict, or skip the cache, for prompts where small differences are significant."
    },
    {
      "id": "more-information",
      "title": "More information",
      "role": "content",
      "text": "- [Spring AI Redis vector store reference](https://docs.spring.io/spring-ai/reference/api/vectordbs/redis.html)\n- [Spring AI chat memory reference](https://docs.spring.io/spring-ai/reference/api/chat-memory.html)\n- [Spring Data Redis and Spring Session](https://redis.io/docs/latest/integrate/spring-framework-cache), for caching, sessions, and data structures without Spring AI\n- [Redis LangCache](https://redis.io/docs/latest/develop/ai/langcache), a managed semantic cache"
    }
  ],
  "examples": [
    {
      "id": "requirements-ex0",
      "language": "xml",
      "code": "<dependencyManagement>\n  <dependencies>\n    <dependency>\n      <groupId>org.springframework.ai</groupId>\n      <artifactId>spring-ai-bom</artifactId>\n      <version>2.0.2</version>\n      <type>pom</type>\n      <scope>import</scope>\n    </dependency>\n  </dependencies>\n</dependencyManagement>\n\n<dependencies>\n  <dependency>\n    <groupId>org.springframework.boot</groupId>\n    <artifactId>spring-boot-starter-data-redis</artifactId>\n  </dependency>\n  <dependency>\n    <groupId>org.springframework.ai</groupId>\n    <artifactId>spring-ai-starter-vector-store-redis</artifactId>\n  </dependency>\n</dependencies>",
      "section_id": "requirements"
    },
    {
      "id": "requirements-ex1",
      "language": "properties",
      "code": "spring.data.redis.host=localhost\nspring.data.redis.port=6379\nspring.data.redis.client-type=jedis",
      "section_id": "requirements"
    },
    {
      "id": "search-embeddings-with-the-vector-store-ex0",
      "language": "properties",
      "code": "spring.ai.vectorstore.redis.initialize-schema=true\nspring.ai.vectorstore.redis.index-name=docs-index\nspring.ai.vectorstore.redis.prefix=doc:",
      "section_id": "search-embeddings-with-the-vector-store"
    },
    {
      "id": "search-embeddings-with-the-vector-store-ex1",
      "language": "java",
      "code": "@Autowired VectorStore vectorStore;\n\nvectorStore.add(List.of(\n    new Document(\"Redis is an in-memory data store\", Map.of(\"country\", \"UK\", \"year\", 2021)),\n    new Document(\"Llamas live in the Andes\", Map.of(\"country\", \"PE\", \"year\", 2019))));\n\nList<Document> results = vectorStore.similaritySearch(\n    SearchRequest.builder().query(\"data store\").topK(2).build());",
      "section_id": "search-embeddings-with-the-vector-store"
    },
    {
      "id": "filter-on-metadata-ex0",
      "language": "java",
      "code": "@Bean\nList<RedisVectorStore.MetadataField> redisMetadataFields() {\n    return List.of(\n        RedisVectorStore.MetadataField.tag(\"country\"),\n        RedisVectorStore.MetadataField.numeric(\"year\"));\n}",
      "section_id": "filter-on-metadata"
    },
    {
      "id": "filter-on-metadata-ex1",
      "language": "java",
      "code": "List<Document> filtered = vectorStore.similaritySearch(\n    SearchRequest.builder()\n        .query(\"data store\")\n        .topK(5)\n        .filterExpression(\"country in ['UK', 'NL'] && year >= 2020\")\n        .build());",
      "section_id": "filter-on-metadata"
    },
    {
      "id": "keep-chat-history-ex0",
      "language": "xml",
      "code": "<dependency>\n  <groupId>org.springframework.ai</groupId>\n  <artifactId>spring-ai-starter-model-chat-memory-repository-redis</artifactId>\n</dependency>",
      "section_id": "keep-chat-history"
    },
    {
      "id": "keep-chat-history-ex1",
      "language": "properties",
      "code": "spring.ai.chat.memory.repository.redis.host=localhost\nspring.ai.chat.memory.repository.redis.port=6379\nspring.ai.chat.memory.repository.redis.time-to-live=24h",
      "section_id": "keep-chat-history"
    },
    {
      "id": "keep-chat-history-ex2",
      "language": "java",
      "code": "@Autowired RedisChatMemoryRepository repository;\n\nChatMemory memory = MessageWindowChatMemory.builder()\n    .chatMemoryRepository(repository)\n    .maxMessages(10)\n    .build();\n\nmemory.add(\"conversation-1\", new UserMessage(\"Hello\"));\nmemory.add(\"conversation-1\", new AssistantMessage(\"Hi there\"));\nList<Message> history = memory.get(\"conversation-1\");",
      "section_id": "keep-chat-history"
    },
    {
      "id": "cache-responses-by-meaning-ex0",
      "language": "xml",
      "code": "<dependency>\n  <groupId>org.springframework.ai</groupId>\n  <artifactId>spring-ai-redis-semantic-cache</artifactId>\n</dependency>\n<dependency>\n  <groupId>org.springframework.ai</groupId>\n  <artifactId>spring-ai-autoconfigure-vector-store-redis-semantic-cache</artifactId>\n</dependency>\n<dependency>\n  <groupId>org.springframework.ai</groupId>\n  <artifactId>spring-ai-transformers</artifactId>\n</dependency>",
      "section_id": "cache-responses-by-meaning"
    },
    {
      "id": "cache-responses-by-meaning-ex1",
      "language": "properties",
      "code": "spring.ai.vectorstore.redis.semantic-cache.host=localhost\nspring.ai.vectorstore.redis.semantic-cache.port=6379\nspring.ai.vectorstore.redis.semantic-cache.similarity-threshold=0.8",
      "section_id": "cache-responses-by-meaning"
    },
    {
      "id": "cache-responses-by-meaning-ex2",
      "language": "java",
      "code": "@Autowired SemanticCache cache;\n@Autowired ChatModel chatModel;\n\nSemanticCacheAdvisor advisor = SemanticCacheAdvisor.builder().cache(cache).build();\n\nString first = ChatClient.builder(chatModel).build()\n    .prompt(\"What is the capital of France?\")\n    .advisors(advisor)\n    .call().content();\n\nString second = ChatClient.builder(chatModel).build()\n    .prompt(\"Tell me the capital city of France?\")   // similar: no model call\n    .advisors(advisor)\n    .call().content();",
      "section_id": "cache-responses-by-meaning"
    },
    {
      "id": "cache-responses-by-meaning-ex3",
      "language": "java",
      "code": "RedisClient jedisClient = RedisClient.builder().hostAndPort(\"localhost\", 6379).build();\n\nSemanticCache cache = DefaultSemanticCache.builder()\n    .jedisClient(jedisClient)\n    .embeddingModel(embeddingModel)\n    .distanceThreshold(0.3)\n    .indexName(\"my-semantic-cache\")\n    .prefix(\"cache:\")\n    .build();\n\ncache.set(\"What is the capital of France?\", chatResponse, Duration.ofHours(1));\nOptional<ChatResponse> hit = cache.get(\"Tell me the capital city of France\");",
      "section_id": "cache-responses-by-meaning"
    }
  ]
}
