当前位置: 首页 > news >正文

133-Spring AI Alibaba Vector Redis 功能完整案例

本案例将引导您一步步构建一个 Spring Boot 应用,演示如何利用 Spring AI Alibaba 的 Redis 向量存储功能,实现文档的向量存储、检索和过滤功能。

1. 案例目标

我们将创建一个包含三个核心功能的 Web 应用:

  1. 数据导入 (/redis/import):将示例文档向量化并存储到 Redis 中,同时添加元数据以便后续过滤。
  2. 相似性搜索 (/redis/search):根据查询文本在 Redis 中搜索最相似的文档。
  3. 过滤删除 (/redis/delete-filter):根据元数据过滤条件删除 Redis 中的向量数据。

2. 技术栈与核心依赖

  • Spring Boot 3.x
  • Spring AI Alibaba (用于对接阿里云 DashScope 通义大模型)
  • Spring AI Redis Vector Store (用于向量存储和检索)
  • Redis (作为向量数据库)
  • Maven (项目构建工具)

在 pom.xml 中,你需要引入以下核心依赖:

<dependencies><!-- Spring AI Alibaba 核心启动器,集成 DashScope --><dependency><groupId>com.alibaba.cloud.ai</groupId><artifactId>spring-ai-alibaba-starter-dashscope</artifactId></dependency><!-- Spring Web 用于构建 RESTful API --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!-- Spring AI Redis Vector Store 用于向量存储 --><dependency><groupId>org.springframework.ai</groupId><artifactId>spring-ai-starter-vector-store-redis</artifactId></dependency>
</dependencies>

3. 项目配置

在 src/main/resources/application.yml 文件中,配置 DashScope API Key 和 Redis 连接信息。

server:port: 8080spring:application:name: redis-exampleai:dashscope:api-key: ${AI_DASHSCOPE_API_KEY} # 建议使用环境变量,更安全vectorstore:redis:initialize-schema: trueprefix: prefix_spring_ai_alibabaindex: index_spring_ai_alibabadata:redis:host: localhostport: 6379 # Redis服务器连接端口

重要提示:请将 AI_DASHSCOPE_API_KEY 环境变量设置为你从阿里云获取的有效 API Key。确保 Redis 服务器已启动并运行在配置的端口上。

4. Redis 向量存储配置

创建 RedisConfig.java 配置类,用于设置 Redis 向量存储:

package com.alibaba.cloud.ai.example.vector.redis.config;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.embedding.EmbeddingModel;
import org.springframework.ai.embedding.TokenCountBatchingStrategy;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.JedisPooled;@Configuration
public class RedisConfig {private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);@Value("${spring.data.redis.host}")private String host;@Value("${spring.data.redis.port}")private int port;@Value("${spring.ai.vectorstore.redis.prefix}")private String prefix;@Value("${spring.ai.vectorstore.redis.index}")private String indexName;@Beanpublic JedisPooled jedisPooled() {logger.info("Redis host: {}, port: {}", host, port);return new JedisPooled(host, port);}@Beanpublic RedisVectorStore vectorStore(JedisPooled jedisPooled, EmbeddingModel embeddingModel) {logger.info("create redis vector store");return RedisVectorStore.builder(jedisPooled, embeddingModel).indexName(indexName)                // Optional: defaults to "spring-ai-index".prefix(prefix)                  // Optional: defaults to "embedding:".metadataFields(                         // Optional: define metadata fields for filteringRedisVectorStore.MetadataField.tag("name"),RedisVectorStore.MetadataField.numeric("year")).initializeSchema(true)                   // Optional: defaults to false.batchingStrategy(new TokenCountBatchingStrategy()) // Optional: defaults to TokenCountBatchingStrategy.build();}
}

5. 编写控制器代码

创建 RedisController.java 控制器类,实现数据导入、相似性搜索和过滤删除功能:

package com.alibaba.cloud.ai.example.vector.redis.controller;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.document.Document;
import org.springframework.ai.vectorstore.SearchRequest;
import org.springframework.ai.vectorstore.filter.Filter;
import org.springframework.ai.vectorstore.filter.FilterExpressionBuilder;
import org.springframework.ai.vectorstore.redis.RedisVectorStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;
import java.util.List;
import java.util.Map;@RestController
@RequestMapping("/redis")
public class RedisController {private static final Logger logger = LoggerFactory.getLogger(RedisController.class);private final RedisVectorStore redisVectorStore;@Autowiredpublic RedisController(RedisVectorStore redisVectorStore) {this.redisVectorStore = redisVectorStore;}@GetMapping("/import")public void importData() {logger.info("start import data");HashMap<String, Object> map = new HashMap<>();map.put("id", "12345");map.put("year", "2025");map.put("name", "yingzi");List<Document> documents = List.of(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("year", 2024)),new Document("Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!", map));redisVectorStore.add(documents);}@GetMapping("/search")public List<Document> search() {logger.info("start search data");return redisVectorStore.similaritySearch(SearchRequest.builder().query("Spring").topK(2).build());}@GetMapping("delete-filter")public void searchFilter() {logger.info("start delete data with filter");FilterExpressionBuilder b = new FilterExpressionBuilder();Filter.Expression expression = b.eq("name", "yingzi").build();redisVectorStore.delete(expression);}
}

6. 主应用程序类

创建 RedisApplication.java 主应用程序类:

package com.alibaba.cloud.ai.example.vector.redis;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class RedisApplication {public static void main(String[] args) {SpringApplication.run(RedisApplication.class, args);}
}

7. 运行与测试

  1. 启动 Redis 服务器:确保 Redis 服务器已启动并运行在默认端口 6379。
  2. 设置环境变量:设置 AI_DASHSCOPE_API_KEY 环境变量为你的阿里云 DashScope API Key。
  3. 启动应用:运行你的 Spring Boot 主程序。
  4. 使用浏览器或 API 工具(如 Postman, curl)进行测试

测试 1:导入数据

访问以下 URL,将示例文档向量化并存储到 Redis 中:

http://localhost:8080/redis/import

预期响应:无返回内容,但服务器日志会显示 "start import data" 和 "create redis vector store"。

测试 2:相似性搜索

访问以下 URL,搜索与 "Spring" 相关的文档:

http://localhost:8080/redis/search

预期响应:返回与 "Spring" 最相似的两个文档,以 JSON 格式显示:

[{"content": "Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!! Spring AI rocks!!","metadata": {"id": "12345","year": "2025","name": "yingzi"}},{"content": "The World is Big and Salvation Lurks Around the Corner","metadata": {}}
]

测试 3:过滤删除

访问以下 URL,删除元数据中 name 为 "yingzi" 的文档:

http://localhost:8080/redis/delete-filter

预期响应:无返回内容,但服务器日志会显示 "start delete data with filter"。再次执行搜索操作,将不会返回被删除的文档。

8. 实现思路与扩展建议

实现思路

本案例的核心思想是"向量存储与检索"。我们利用 Redis 作为向量数据库,结合 Spring AI 的向量存储功能,实现了:

  • 文档向量化:将文本文档转换为向量表示,便于进行相似性计算。
  • 元数据管理:为每个文档添加元数据,支持基于元数据的过滤操作。
  • 相似性搜索:根据查询文本在向量空间中找到最相似的文档。
  • 过滤删除:基于元数据条件删除文档,提供灵活的数据管理能力。

扩展建议

  • 批量导入:扩展数据导入功能,支持从文件系统或数据库批量导入文档。
  • 高级过滤:实现更复杂的过滤条件,如范围查询、逻辑组合等。
  • 向量可视化:添加向量可视化功能,帮助理解向量空间中文档的分布。
  • 性能优化:对于大规模数据集,考虑使用索引优化、分片等技术提高检索性能。
  • 集成其他 AI 功能:将向量存储与其他 AI 功能(如问答、摘要生成)结合,构建更复杂的应用。
  • 多模态支持:扩展支持图像、音频等多模态数据的向量存储和检索。

9. 总结

本案例展示了如何使用 Spring AI Alibaba 和 Redis 构建向量存储和检索系统。通过将文档向量化并存储在 Redis 中,我们可以高效地进行相似性搜索和基于元数据的过滤操作。这为构建检索增强生成(RAG)系统、推荐系统、语义搜索等应用提供了基础。

Spring AI Alibaba 简化了与阿里云 DashScope 的集成,而 Spring AI 的 Redis Vector Store 提供了便捷的向量存储接口。结合这些工具,开发者可以快速构建强大的 AI 应用,充分发挥向量数据库的潜力。

http://www.dtcms.com/a/545617.html

相关文章:

  • 线段树详解
  • AI 大模型应用中的图像,视频,音频的处理
  • 2025年大专建筑工程技术专业前景!
  • @1Panel 全面指南:从部署到高阶使用
  • SAP MM 采购申请转采购订单功能分享
  • FPGA设计中的“幽灵信号:一条走线,两种命运——浅析路径延迟导致的逻辑错误
  • 网站建设将新建用户授权为管理员免费搭建手机网站源码
  • 北京企业网站建设费用新闻最新消息
  • 算法工具箱之二分查找
  • undefined reference to `cJSON_AddStringToObject‘
  • 仓颉语言中TreeMap红黑树结构的实现与优化
  • Rust 的构建系统和包管理器
  • AI驱动嵌入式软件全链路变革:从芯片到系统的深度智能重构
  • 怎么修改网站域名推广网站排行榜
  • 靠谱的电磁阀维护保养
  • 【自动化测试函数 (下)】Web自动化攻坚:应对加载等待、浏览器导航与无头模式的自动化脚本艺术
  • 正向代理工具
  • 攀枝花建设工程有限责任公司网站中国兰州网
  • Kubernetes 部署
  • 网站建设投标人资质要求wordpress邮箱如何解析
  • 鞍山商城网站建设运城手机网站制作
  • 【GitLab/CD】前端 CD
  • 做简报的网站竹制品网站怎么做
  • Kafka使用-Consumer
  • 诸暨网站建设怎么建立微网站?
  • 【Docker】【1.docker常用命令总结】
  • 深圳的网站建设公司的外文名是wordpress异步加载
  • 创客匠人2025万人高峰论坛:如何融合创始人IP与AI?
  • Linux中完成根文件系统的最终准备和切换prepare_namespace函数的实现
  • A800 部署 Qwen2-VL-8B-Instruct 完整指南