fix(database/gdb): Fix N+1 query problem and add fine-grained query control with batch recursive scanning #4656
+1,146
−287
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
解决With/WithAll的多层递归的查询次数N+1问题并且增加更加可控的颗粒度分批查询控制
前提
#4620 中提到了多层嵌套查询导致查询次数不可控暴涨问题,所以有了此次改进,允许逐层统一收集当前结果然后统一查询下一层数据,也可以控制每一层在达到指定数量后使用分批查询,也可以什么也不改使用原本的默认查询方式
提前说明
With和WIthAll功能原本的设计我不清楚是不是故意设计成这种可能无限膨胀的模式,也有可能时希望开发者自己控制层数不要太深,所以我并不清楚我的这次改进是否有意义,需要大家来判断。概述
本次改进在保留原有的 WithAll 功能基础上,新增了 WithBatch 功能,解决传统 ORM 关联查询中的 N+1 问题。
核心改进
1. 保留原有功能
2. 批量查询优化
通过
WithBatch()方法启用批量查询功能,将 N+1 查询优化为固定次数的批量查询:3. 分批处理机制
针对大数据量场景,引入分批处理机制:
batchSize:每批处理的最大记录数batchThreshold:启用批量查询的最小记录数阈值使用方法
1. 基础用法
定义关联结构体
普通关联查询(可能存在N+1问题)
启用批量优化查询
2. 高级用法
在结构体标签中配置分批参数
四层嵌套关联查询示例
3. 性能优化建议
选择合适的批量参数
batchThreshold:对于小数据集(< 5条记录),可以不启用批量查询batchSize:根据数据库性能和内存情况调整,一般建议 50-5004. 实现原理
批量查询核心逻辑
分批处理策略
当关联数据量超过
batchSize时,系统会自动将查询分批执行:5. 注意事项
orm:"with:..."标签batchThreshold和batchSize参数优势对比
通过合理使用 WithBatch 功能和适当的参数配置,可以显著提升关联查询的性能,有效解决 N+1 查询问题。