|
此版本仍在开发中,尚未被视为稳定版。为了获取最新的快照版本,请使用Spring AI 1.1.3! |
Redis
本节将引导您完成配置RedisVectorStore以存储文档嵌入并执行相似性搜索的过程。
Redis 是一个基于BSD授权的开源内存数据结构存储程序,可作为数据库、缓存、消息中间件和流处理引擎使用。Redis提供了字符串、哈希表、列表、集合、有序集合(支持范围查询)、位图、哈希计数器、地理空间索引和流等数据结构。
Redis 搜索与查询 延伸了 Redis OSS 的核心功能,允许您将 Redis 用作向量数据库:
-
将向量及其相关的元数据存储在哈希表或JSON文档中。
-
获取向量
-
进行向量相似性搜索(K近邻算法)
-
进行基于范围的向量搜索,使用半径阈值
-
在TEXT字段上进行全文搜索
-
支持多种距离度量方法(COSINE、L2、IP)和向量算法(HNSW、FLAT)
自动配置
|
There has been a significant change in the Spring AI auto-configuration, starter modules' artifact names. Please refer to the 升级说明以获取更多信息。 |
Spring Boot自动生成Redis Vector Store的配置参数。
要启用它,只需在项目Maven pom.xml文件中添加以下依赖项:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-redis</artifactId>
</dependency>
或者添加到您的Gradle 构建脚本文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis'
}
| 参考以下依赖管理部分,添加Spring AI BOM到你的构建文件中。 |
| 引用 Artifact 仓库 部分,以在构建文件中添加 Maven Central 和/或 Snapshot 仓库。 |
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 AI 中,此模式初始化是默认进行的。 |
请查看以下向量存储的配置参数列表,了解默认值和配置选项。这些配置参数的类型为C0。
此外,您还需要配置一个EmbeddingModel的豆。有关详细信息,请参阅
现在您可以在应用程序中自动将RedisVectorStore作为向量存储进行注入。
@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());
配置属性
连接到 Redis 并使用 RedisVectorStore,你需要提供你的实例访问细节。
一个简单的配置可以通过 Spring Boot 的 application.yml 提供,
spring:
data:
redis:
url: <redis instance url>
ai:
vectorstore:
redis:
initialize-schema: true
index-name: custom-index
prefix: custom-prefix
For Redis 连接配置,或者,可以通过 Spring Boot 的 application.properties 提供一个简单的配置。
spring.data.redis.host=localhost
spring.data.redis.port=6379
spring.data.redis.username=default
spring.data.redis.password=
以 spring.ai.vectorstore.redis.* 开头的属性用于配置 RedisVectorStore:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
是否初始化所需的模式 |
|
|
存储向量的索引名称 |
|
|
Redis键的前缀 |
|
|
向量相似性的距离度量 (余弦相似度,欧几里得距离,点积) |
|
|
其中,使用基于层次结构的NSW(HNSW)和非层次化(Flat)方法。 |
|
|
HNSW: 最大出线连接数 |
|
|
HNSW:在索引构建过程中允许的最大连接数 |
|
|
HNSW: 在搜索过程中需要考虑的连接数量 |
|
|
默认半径阈值用于范围搜索 |
|
|
文本评分算法 (BM25, TF-IDF, BM25增强版, DISMAX, DOCSCORE) |
|
元数据过滤
You can leverage the generic, portable 元数据过滤器 with Redis as well.
例如,你可以使用文本表达式语言:
vectorStore.similaritySearch(SearchRequest.builder()
.query("The World")
.topK(TOP_K)
.similarityThreshold(SIMILARITY_THRESHOLD)
.filterExpression("country in ['UK', 'NL'] && year >= 2020").build());
或通过编程方式使用 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());
| 那些(便携式)过滤表达式会自动转换为 Redis搜索查询。 |
例如,这个可移植的过滤表达式:
country in ['UK', 'NL'] && year >= 2020
被转换为专有 Redis 过滤器格式:
@country:{UK | NL} @year:[2020 inf]
手动配置
而不是使用Spring Boot的自动配置,你可以手动配置Redis向量存储。为此,你需要在你的项目中添加以下内容:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-redis-store</artifactId>
</dependency>
或者添加到您的Gradle 构建脚本文件中。
dependencies {
implementation 'org.springframework.ai:spring-ai-redis-store'
}
创建一个 零 bean:
@Bean
public JedisPooled jedisPooled() {
return new JedisPooled("<host>", 6379);
}
然后使用构建器模式创建 RedisVectorStore Bean:
@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:"
.contentFieldName("content") // Optional: field for document content
.embeddingFieldName("embedding") // Optional: field for vector embeddings
.vectorAlgorithm(Algorithm.HNSW) // Optional: HNSW or FLAT (defaults to HNSW)
.distanceMetric(DistanceMetric.COSINE) // Optional: COSINE, L2, or IP (defaults to COSINE)
.hnswM(16) // Optional: HNSW connections (defaults to 16)
.hnswEfConstruction(200) // Optional: HNSW build parameter (defaults to 200)
.hnswEfRuntime(10) // Optional: HNSW search parameter (defaults to 10)
.defaultRangeThreshold(0.8) // Optional: default radius for range searches
.textScorer(TextScorer.BM25) // Optional: text scoring algorithm (defaults to BM25)
.metadataFields( // Optional: define metadata fields for filtering
MetadataField.tag("country"),
MetadataField.numeric("year"),
MetadataField.text("description"))
.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")));
}
|
必须明确列出所有用于过滤表达式的元数据字段名称及其类型( |
访问原生客户端
Redis向量存储的实现提供访问底层Redis客户端(代码块0)的方法:
RedisVectorStore vectorStore = context.getBean(RedisVectorStore.class);
Optional<JedisPooled> nativeClient = vectorStore.getNativeClient();
if (nativeClient.isPresent()) {
JedisPooled jedis = nativeClient.get();
// Use the native client for Redis-specific operations
}
本地客户端让你可以访问Redis特定功能和操作,这些功能和操作可能不会通过VectorStore接口暴露出来。
距离度量
Redis向量存储支持三种用于向量相似性的距离度量方法:余弦相似度、Jaccard相似度和哈明距离。
-
余弦: 余弦相似度(默认) - 用于衡量向量之间的余弦角度
-
L2: 欧氏距离 - 用于衡量向量之间的直线距离
-
IP: 内积 - 测量向量之间的点积
每个指标都会自动归一化为一个0-1相似性分数,其中1表示最相似。
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.distanceMetric(DistanceMetric.COSINE) // or L2, IP
.build();
HNSW算法配置
Redis向量存储(Redis Vector Store)默认使用HNSW(Hierarchical Navigable Small World)算法来进行高效的近邻搜索。您可以通过调整HNSW参数来适应您的具体场景需求:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.vectorAlgorithm(Algorithm.HNSW)
.hnswM(32) // Maximum outgoing connections per node (default: 16)
.hnswEfConstruction(100) // Connections during index building (default: 200)
.hnswEfRuntime(50) // Connections during search (default: 10)
.build();
参数指南:
-
M: 高值可以提高召回率,但会增加内存使用量和索引时间。 typical values: 12-48.
-
EF_CONSTRUCTION: 更高的值可以提高索引质量但会增加构建时间。典型值:100-500。
-
EF_运行时: 提高值可以提高搜索准确性,但会增加延迟。典型值范围:10-100。
对于较小的数据集,或者当需要精确结果时,改用FLAT算法。
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.vectorAlgorithm(Algorithm.FLAT)
.build();
文本搜索文本搜索
Redis向量存储(Redis Vector Store)支持全文本搜索功能,利用Redis Query Engine的full-text search(全文本搜索)特性。这使得你可以根据关键词和短语在TEXT字段中查找文档。
// Search for documents containing specific text
List<Document> textResults = vectorStore.searchByText(
"machine learning", // search query
"content", // field to search (must be TEXT type)
10, // limit
"category == 'AI'" // optional filter expression
);
文本搜索支持:
-
单词搜索
-
当0为真时,进行精确匹配搜索
-
基于单词的搜索,当0时为否时采用OR逻辑
-
停用词过滤,用于忽略常见单词
-
多种文本评分算法
在构建过程中配置文本搜索行为:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.textScorer(TextScorer.TFIDF) // Text scoring algorithm
.inOrder(true) // Match terms in order
.stopwords(Set.of("is", "a", "the", "and")) // Ignore common words
.metadataFields(MetadataField.text("description")) // Define TEXT fields
.build();
范围搜索
范围搜索返回所有落在指定半径范围内的文档,而不是固定数量的最近邻居:
// Search with explicit radius
List<Document> rangeResults = vectorStore.searchByRange(
"AI and machine learning", // query
0.8, // radius (similarity threshold)
"category == 'AI'" // optional filter expression
);
您也可以在构建时间设置一个默认范围阈值:
RedisVectorStore vectorStore = RedisVectorStore.builder(jedisPooled, embeddingModel)
.defaultRangeThreshold(0.8) // Set default threshold
.build();
// Use default threshold
List<Document> results = vectorStore.searchByRange("query");
范围搜索在需要检索所有相关文档且相似度阈值以上时非常有用,而不是限制在特定数量。
语义缓存语义缓存
语义缓存是一种强大的优化技术,它利用Redis向量搜索能力,基于用户查询的语义相似性而非精确字符串匹配,来缓存和检索AI聊天响应。 这使得即使用户以不同的方式表达类似的问题,智能响应也能得到重复利用。
为什么语义缓存?
传统缓存机制依赖于精确的关键匹配,这导致当用户使用不同措辞提出意义相同的问题时,这种方法会失效:
-
“法国的首都是什么?”
-
“告诉我法国的首都是什么”
-
“哪个城市是法国的首都?”
All three queries have the same answer, but traditional caching would treat them as different requests, resulting in redundant LLM API calls. Semantic caching solves this by comparing the 意义 of queries using vector embeddings.
Benefits:
-
降低API成本: 避免冗余调用昂贵的LLM API
-
返回缓存的响应,无需等待模型推理
-
改进的可扩展性:无需按比例增加API成本,即可处理更高的查询流量
-
一致响应: 返回语义相似问题的一致回答
自动配置
Spring AI提供了Spring Boot的自动配置功能,用于Redis语义缓存。
要启用它,将以下依赖项添加到您的项目Maven pom.xml文件中:
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-starter-vector-store-redis-semantic-cache</artifactId>
</dependency>
或者添加到你的 Gradle build.gradle 构建文件中:
dependencies {
implementation 'org.springframework.ai:spring-ai-starter-vector-store-redis-semantic-cache'
}
自动生成配置提供了一个优化的语义缓存预设模型(0)。
你可以通过提供自定义的 EmbeddingModel 豆来 override 这个设置。 |
配置属性
具有以0开头的属性可以配置语义缓存:
| 属性 | 描述 | 默认值 |
|---|---|---|
|
启用或禁用语义缓存 |
|
|
Redis 服务器主机 |
|
|
Redis 服务器端口 |
|
|
缓存命中相似度阈值(范围是0.0至1.0)。数值越高,需要语义越接近。 |
|
|
Redis搜索索引用于缓存项 |
|
|
Redis缓存条的前缀 |
|
示例配置在代码块0中:
spring:
ai:
vectorstore:
redis:
semantic-cache:
enabled: true
host: localhost
port: 6379
similarity-threshold: 0.85
index-name: my-app-cache
prefix: "my-app:semantic-cache:"
使用语义缓存顾问
The 零 与 Spring AI 的 一 指导模式无缝集成。
它自动缓存响应并返回相似查询的缓存结果:
@Autowired
private SemanticCache semanticCache;
@Autowired
private ChatModel chatModel;
public void example() {
// Create the cache advisor
SemanticCacheAdvisor cacheAdvisor = SemanticCacheAdvisor.builder()
.cache(semanticCache)
.build();
// First query - calls the LLM and caches the response
ChatResponse response1 = ChatClient.builder(chatModel)
.build()
.prompt("What is the capital of France?")
.advisors(cacheAdvisor)
.call()
.chatResponse();
// Similar query - returns cached response (no LLM call)
ChatResponse response2 = ChatClient.builder(chatModel)
.build()
.prompt("Tell me the capital city of France")
.advisors(cacheAdvisor)
.call()
.chatResponse();
// response1 and response2 contain the same cached answer
}
顾问会自动地:
-
在调用LLM之前,检查缓存中是否有语义上相似的查询
-
当相似度超过相似度阈值时,返回缓存的响应。
-
成功后的大语言模型(LLM)调用会缓存新的响应。
-
支持同步和流式聊天操作。
直接缓存使用
你可以直接与代码块进行交互,以获得精细级别的控制:
@Autowired
private SemanticCache semanticCache;
// Store a response with a query
semanticCache.set("What is the capital of France?", chatResponse);
// Store with TTL (time-to-live) for automatic expiration
semanticCache.set("What's the weather today?", weatherResponse, Duration.ofHours(1));
// Retrieve a semantically similar response
Optional<ChatResponse> cached = semanticCache.get("Tell me France's capital");
if (cached.isPresent()) {
// Use the cached response
String answer = cached.get().getResult().getOutput().getText();
}
// Clear all cached entries
semanticCache.clear();
手动配置
为了更多控制权,你可以手动配置语义缓存组件:
@Configuration
public class SemanticCacheConfig {
@Bean
public JedisPooled jedisPooled() {
return new JedisPooled("localhost", 6379);
}
@Bean
public SemanticCache semanticCache(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {
return DefaultSemanticCache.builder()
.jedisClient(jedisPooled)
.embeddingModel(embeddingModel)
.distanceThreshold(0.3) // Lower = stricter matching
.indexName("my-semantic-cache")
.prefix("cache:")
.build();
}
@Bean
public SemanticCacheAdvisor semanticCacheAdvisor(SemanticCache cache) {
return SemanticCacheAdvisor.builder()
.cache(cache)
.build();
}
}
缓存隔离与命名空间
对于多租户应用或需要隔离缓存条目的情况,使用不同的索引名称来隔离缓存条目:
// Create isolated caches for different users or contexts
SemanticCache user1Cache = DefaultSemanticCache.builder()
.jedisClient(jedisPooled)
.embeddingModel(embeddingModel)
.indexName("user-1-cache")
.build();
SemanticCache user2Cache = DefaultSemanticCache.builder()
.jedisClient(jedisPooled)
.embeddingModel(embeddingModel)
.indexName("user-2-cache")
.build();
// Each user gets their own isolated cache space
SemanticCacheAdvisor user1Advisor = SemanticCacheAdvisor.builder()
.cache(user1Cache)
.build();
系统提示隔离System Prompt Isolation
代码0自动根据系统提示词隔离缓存响应。 这确保了同一个用户查询在不同系统提示词下返回不同的缓存响应,这对于具有多个AI人像或依赖上下文行为的应用至关重要。
SemanticCacheAdvisor cacheAdvisor = SemanticCacheAdvisor.builder()
.cache(semanticCache)
.build();
// Query with technical support persona
ChatResponse technicalResponse = ChatClient.builder(chatModel)
.build()
.prompt()
.system("You are a technical support specialist. Provide detailed technical answers.")
.user("How do I reset my password?")
.advisors(cacheAdvisor)
.call()
.chatResponse();
// Same query with customer service persona - cache MISS (different context)
ChatResponse serviceResponse = ChatClient.builder(chatModel)
.build()
.prompt()
.system("You are a friendly customer service agent. Keep responses brief and helpful.")
.user("How do I reset my password?")
.advisors(cacheAdvisor)
.call()
.chatResponse();
// Same query with technical support persona again - cache HIT
ChatResponse technicalAgain = ChatClient.builder(chatModel)
.build()
.prompt()
.system("You are a technical support specialist. Provide detailed technical answers.")
.user("How do I reset my password?")
.advisors(cacheAdvisor)
.call()
.chatResponse();
// Returns the cached technical response
如何使用:
建议机计算系统提示的确定性哈希,并将其用作缓存响应存储和检索时的元数据过滤器:
-
同一个用户的问题 + 相同的系统提示 → 缓存命中
-
同一个用户问题加上不同的系统提示 → 缓存缺失(独立缓存条)
-
不带系统提示的查询共享一个公共缓存空间。
上下文意识缓存API
在复杂的使用场景下,您可以直接使用上下文意识缓存方法:
// Store with explicit context hash
String contextHash = "technical-support-context";
semanticCache.set("How do I reset my password?", response, contextHash);
// Retrieve with context filtering
Optional<ChatResponse> cached = semanticCache.get("How do I reset my password?", contextHash);
// Different context hash returns empty (no match)
Optional<ChatResponse> otherContext = semanticCache.get("How do I reset my password?", "billing-context");
调优相似度阈值
相似度阈值决定了查询必须与缓存条有多接近才会被认为是命中。 该阈值以介于0.0到1.0之间的值表示:
-
更高的阈值(例如0.95):需要非常接近的语义匹配。 减少了假阳性,但可能会错过有效的缓存命中。
-
下限(例如:0.70):允许更广泛的语义匹配。 增加缓存命中率,但可能返回较不相关的缓存响应。
// Strict matching - only very similar queries hit the cache
SemanticCache strictCache = DefaultSemanticCache.builder()
.jedisClient(jedisPooled)
.embeddingModel(embeddingModel)
.distanceThreshold(0.2) // Strict (distance-based, lower = stricter)
.build();
// Lenient matching - broader semantic similarity accepted
SemanticCache lenientCache = DefaultSemanticCache.builder()
.jedisClient(jedisPooled)
.embeddingModel(embeddingModel)
.distanceThreshold(0.5) // Lenient
.build();
| 从较高的阈值(更严格的匹配)开始,然后根据你的应用对语义变化的容忍度逐步降低这个阈值。 |
TTL和缓存过期时间TTL和缓存过期时间
缓存的响应可以通过 TTL 时间进行配置,以实现自动过期。这对于时间敏感的数据至关重要:
// Cache weather data for 1 hour
semanticCache.set("What's the weather in New York?", weatherResponse, Duration.ofHours(1));
// Cache general knowledge indefinitely (no TTL)
semanticCache.set("What is photosynthesis?", scienceResponse);
// Redis automatically removes expired entries
如何工作
语义缓存按照预先定义好的缓存策略,实现了数据流的高效管理。
-
查询嵌入: 当一个查询到达时,它会被转换为向量嵌入,使用配置的
零 -
向量搜索: Redis使用基于范围的向量搜索(
VECTOR_RANGE),在相似度阈值内查找缓存条目 -
缓存命中:Cache hit: If a semantically similar query is found, the cached
ChatResponseis returned immediately -
缓存缺失: 如果没有匹配项,查询将 proceeds to the LLM模型,且响应被缓存以供未来使用
该实现利用了Redis的高效向量索引(HNSW算法),用于快速相似性搜索,即使缓存规模很大。