Skip to content

[WIP] Optimize vector similarity calculation in Java application layer#5

Merged
IfeyChan702 merged 1 commit into
mainfrom
copilot/optimize-vector-calculation-java
Feb 10, 2026
Merged

[WIP] Optimize vector similarity calculation in Java application layer#5
IfeyChan702 merged 1 commit into
mainfrom
copilot/optimize-vector-calculation-java

Conversation

Copilot AI commented Feb 10, 2026

Copy link
Copy Markdown
Contributor

Vector Calculation Optimization - Plan A Implementation

Phase 1: Code Assessment and Planning

  • Explore repository structure
  • Review existing VectorUtil.java (already exists, uses Apache Commons Math)
  • Review existing EmbeddingUtil.java (already exists, has basic functionality)
  • Review RAGServiceImpl.java (currently uses MySQL cosine_similarity function)
  • Review NoteMapper.xml (uses MySQL cosine_similarity function)
  • Review sql/rag_init.sql (contains MySQL stored function)
  • Review application-rag.yml (basic RAG configuration)

Phase 2: Enhance Java Utilities (In Progress)

  • Enhance VectorUtil.java with parallel processing support
    • Add batchCosineSimilarity for parallel computation
    • Add manhattanDistance method
    • Add vectorDot and vectorMagnitude methods
    • Remove Apache Commons Math dependency (use native Java)
  • Enhance EmbeddingUtil.java
    • Add validateEmbedding method
    • Add embeddingDimension method
    • Add jsonToEmbeddingList method

Phase 3: Modify RAG Service

  • Update RAGServiceImpl.java to calculate similarity in Java
    • Remove SQL cosine_similarity dependency
    • Implement application-layer vector calculation
    • Add parallel processing with Stream API
    • Add performance monitoring

Phase 4: Simplify Database Layer

  • Update NoteMapper.java interface
    • Add selectNoteListByUserIdWithEmbedding method
  • Update NoteMapper.xml
    • Remove cosine_similarity function calls
    • Simplify searchSimilarNotes to just fetch data
    • Add new query to fetch all notes with embeddings
  • Update sql/rag_init.sql (MySQL)
    • Remove cosine_similarity stored function
    • Keep table structures unchanged
    • Add performance indexes

Phase 5: Configuration Updates

  • Update application-rag.yml
    • Add similarity algorithm configuration
    • Add performance settings (parallel processing)
    • Add monitoring configuration

Phase 6: Testing

  • Create VectorUtilTest.java
    • Test cosineSimilarity
    • Test euclideanDistance
    • Test manhattanDistance
    • Test batchCosineSimilarity
    • Test performance benchmarks
  • Create RAGServiceTest.java (optional - if test infrastructure exists)

Phase 7: Documentation

  • Create docs/OPTIMIZATION_GUIDE.md
  • Create docs/MIGRATION_PREPARATION.md

Phase 8: Final Verification

  • Verify all changes work together
  • Run security checks (CodeQL)
  • Code review
  • Final validation
Original prompt

MyEnglishNote 向量计算优化方案 A:Java 应用层优化 + MySQL 保持不变

目标

优化向量相似度计算,将其从 MySQL 存储函数迁移到 Java 应用层,性能提升 5-10 倍,同时完全保留 MySQL 数据库和 RuoYi 系统。

为什么是方案 A?

  1. 无需更改数据库 - MySQL 保持不变,所有 RuoYi 数据安全
  2. 性能提升显著 - 5-10 倍性能提升,足以支撑中等规模应用
  3. 实现简单 - 只需改进 Java 代码,数据库 SQL 简化
  4. 零风险 - 不动现有数据,随时可回滚
  5. 易于维护 - 业务逻辑集中在应用层,便于测试和修改

实现清单

第一部分:Java 代码优化 (~2000+ 行)

1. VectorUtil.java(增强的向量工具类)

位置:ruoyi-system/src/main/java/com/ruoyi/system/util/VectorUtil.java

功能:

  • cosineSimilarity(List<Double> vec1, List<Double> vec2) - 余弦相似度(核心)
  • euclideanDistance(List<Double> vec1, List<Double> vec2) - 欧氏距离(备选)
  • manhattanDistance(List<Double> vec1, List<Double> vec2) - 曼哈顿距离(备选)
  • normalizeVector(List<Double> vector) - 向量归一化
  • vectorDot(List<Double> v1, List<Double> v2) - 向量点积
  • vectorMagnitude(List<Double> vector) - 向量模长
  • batchCosineSimilarity(List<Double> queryVector, List<List<Double>> dbVectors) - 批量并行计算

特点:

  • 使用 Stream API 和并行流优化性能
  • 自动利用多核 CPU
  • 完整的输入验证
  • 详细的注释和文档
  • 性能监控(可选)

2. EmbeddingUtil.java(向量序列化工具)

位置:ruoyi-system/src/main/java/com/ruoyi/system/util/EmbeddingUtil.java

功能:

  • embeddingToJson(List<Double> embedding) - 向量转 JSON 存储
  • jsonToEmbedding(String json) - JSON 转向量对象
  • jsonToEmbeddingList(String json) - JSON 转向量列表
  • validateEmbedding(List<Double> embedding) - 验证向量有效性
  • embeddingDimension() - 获取向量维度(1536)

特点:

  • 处理 JSON 序列化/反序列化
  • 自动处理异常情况
  • 性能优化

3. RAGServiceImpl.java(改进的 RAG 服务)

位置:ruoyi-system/src/main/java/com/ruoyi/system/service/impl/RAGServiceImpl.java

改进点:

  • ❌ 删除所有 SQL 中的 cosine_similarity 函数调用
  • ✅ 在 Java 层计算向量相似度
  • ✅ 使用并行流处理大量笔记
  • ✅ 性能监控和日志
  • ✅ 支持多种相似度算法选择

核心逻辑:

searchNotes(userId, query, threshold, maxResults):
  1. 获取查询向量(调用 Deepseek API)
  2. 从数据库获取用户所有笔记(+ 向量)
  3. 使用并行流计算相似度
  4. 过滤(相似度 > threshold)
  5. 排序(相似度从高到低)
  6. 返回前 N 个结果

4. NoteMapper.xml(简化查询)

改进点:

  • ❌ 删除 cosine_similarity 函数的 SQL 调用
  • ✅ 仅查询基础数据(无计算)
  • ✅ 简化的 SQL,更快的执行

5. 单元测试

VectorUtilTest.java

  • testCosineSimilarity() - 基本功能
  • testEuclideanDistance() - 距离计算
  • testNormalizeVector() - 向量归一化
  • testBatchCosineSimilarity() - 批量并行计算
  • testPerformance() - 性能基准测试(1000 个 1536 维向量)

第二部分:数据库脚本简化 (~150 行)

1. sql/mysql/rag_init.sql(简化版本)

改进点:

  • ❌ 删除 cosine_similarity 存储函数(不再需要)
  • ✅ 保留 3 个表(english_note, review_record, embedding_record)
  • ✅ 简化表结构(只存储,不计算)
  • ✅ 性能索引优化
  • ✅ 详细注释

表结构保持不变:

  • english_note - 笔记表(含 embedding JSON 字段)
  • review_record - 复习记录表
  • embedding_record - 向量记录表(可选)

第三部分:配置更新

1. application-rag.yml(更新)

新增配置:

rag:
  # 相似度算法选择
  similarity:
    algorithm: cosine  # 或 euclidean, manhattan
    
  # 性能相关配置
  performance:
    # 是否使用并行流
    parallel-enabled: true
    # 线程池大小(0 = 自动)
    parallel-pool-size: 0
    # 是否启用性能监控
    monitor-enabled: true
    # 慢查询阈值(毫秒)
    slow-query-threshold-ms: 1000

第四部分:文档

1. docs/OPTIMIZATION_GUIDE.md(优化指南)

内容:

  • 优化方案说明
  • 性能对比数据
  • 使用方式说明
  • 常见问题解决
  • 未来扩展方向

2. docs/MIGRATION_PREPARATION.md(迁移准备指南)

内容:

  • 为什么当前选择方案 A
  • 将来如何迁移到 PostgreSQL(预留)
  • 迁移时机和条件
  • 预期成本估算
  • 测试策略

文件清单

Java 源代码

  • ruoyi-system/src/main/java/com/ruoyi/system/util/VectorUtil.java - 向量计算工具
  • ruoyi-system/src/main/java/com/ruoyi/system/util/EmbeddingUtil.java - 向量序列化工具
  • ruoyi-system/src/main/java/com/ruoyi/system/service/impl/RAGServiceImpl.java - RAG 服务改进版
  • ruoyi-system/src/main/java/com/ruoyi/system/mapper/NoteMapper.java - Mapper 优化版

测试代码

  • ruoyi-system/src/test/java/com/ruoyi/system/util/VectorUtilTest.java - 向量工具测试
  • ruoyi-system/src/test/java/com/ruoyi/system/service/RAGServiceTest.java - RAG 服务测试

数据库脚本

  • sql/mysql/rag_init.sql - MySQL 初始化脚本(优化版,删除函数)

配置文件

  • ruoyi-admin/src/main/resources/application-rag.yml - 更新配置

XML 映射文件

  • ruoyi-system/src/main/resources/mapper/NoteMapper.xml - 简化版 SQL

文档

  • docs/OPTIMIZATION_GUIDE.md - 优化指南
  • docs/MIGRATION_PREPARATION.md - 迁移准备(为将来)

性能对比

场景:查询 1000 个笔记,向量维度 1536

优化前(MySQL 存储函数):
  查询时间:800-1200ms
  主要瓶颈:JSON 处理、单线程

优化后(Java 应用层):
  查询时间:100-200ms
  性能提升:5-10 倍 🚀
  优势:并行计算、多核 CPU、Java 优化

适用场景:
  • 100 万笔记以内
  • 10 万用户以内
  • 中等规模应用

关键改进

  1. 性能 - 5-10 倍提升,使用并行流充分利用多核 CPU
  2. 可维护性 - 业务逻辑集中在 Java 层,易于测试和修改
  3. 可扩展性 - 支持多种相似度算法,易于扩展
  4. 零风险 - 不动现有数据,完全兼容 MySQL
  5. 易于部署 - 无需更改基础设施,直接升级应用

实施步骤

  1. ✅ 合并此 PR
  2. ✅ 修改应用配置(如需自定义)
  3. ✅ 运行 SQL 脚本初始化数据库(删除函数,保留表)
  4. ✅ 运行单元测试验证功能
  5. ✅ 部署升级
  6. ✅ 监控性能

技术细节

Java 代码特点

  • Stream API - 使用现代 Java 特性
  • 并行流 - parallelStream() 自动利用多核
  • 零依赖 - 不需要额外库,使用 JDK 自带
  • 类型安全 - 完整的泛型支持
  • 异常处理 - 完善的错误处理

数据库兼容性

  • 100% 兼容 MySQL - 所有现有数据不变
  • 保持简单 - 删除复杂的 SQL 函数
  • 易于维护 - SQL 更直观

完成后你将拥有

✅ 性能提升 5-10 倍的应用
✅ 完全兼容现有 MySQL 和 RuoYi
✅ 清晰易维护的代码结构
✅ 完整的单元测试覆盖
✅ 详细的优化文档
✅ 为将来迁移预留的设计空间

This pull request was created from Copilot chat.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

@IfeyChan702
IfeyChan702 marked this pull request as ready for review February 10, 2026 09:54
@IfeyChan702
IfeyChan702 merged commit 6610194 into main Feb 10, 2026
1 check failed
@IfeyChan702

Copy link
Copy Markdown
Owner

5

Copilot AI requested a review from IfeyChan702 February 10, 2026 09:55
Copilot stopped work on behalf of IfeyChan702 due to an error February 10, 2026 09:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants