当前位置:网站首页>性能优化:记一次树的搜索接口优化思路
性能优化:记一次树的搜索接口优化思路
2022-07-31 18:17:00 【我叫985】
表结构
树结构表设计一般有2种,如下所示。
个人认为第一种设计比较好,因为第二种分组和节点的数据都放在一起,假设现在树的节点有很多,但是分组没多少,这样会导致查询分组的时候都需要过滤一张大表。而且只对分组修改的时候,如果开了事务等操作,也会将表锁住,会影响到节点的操作;第一种设计的话,分组和节点就可以互不影响。
- 第一种
// 分组表
create table "group" (
id
group_name
parent_group_id // 父分组id
);
// 分组节点表
create table "group_node" (
id
group_id // 所属分组id
node_name
);
- 第二种
// 分组表,自关联
create table "group" (
id
name
is_group
parent_of
);
搜索思路
下面按上述的第一种表设计来讨论,假设一棵树如下
人
|_ 消防员
|_张三
|_李四
|_医生
|_卢员外
|_护士
|_凤姐
车辆
|_ 救护车
|_宝马
现在搜索关键字输入"员",期望的结果如下
人
|_
消防员
医生
|_卢员外
搜索思路如下
1.分别搜分组表和节点表,名字like关键字的
select * group where name like ‘%员%’
select * group_nodewhere name like ‘%员%’
2.然后将搜到的group和groupNode转成一个GroupVo,放在一个List中,GroupVo结构如下
// 后端之所以用这种结构,是因为后端用这种结构比较好整理。
// 但是数据库却是将分组和节点分开的,因为分开对于curd会更加快
class GroupVo {
String id;
String name;
boolean isGroup;
String parentOf;
}
3.如果对于每一个group和groupNode都递归往上查找父节点,直到找到树的根节点。然后不停的往List塞GroupVo
4.最后在用List<GroupVo>
将数据整理成前端需要的结构。
不太好的做法
一开始做的时候很容易想到,从树的根节点开始查找,不断递归向下,判断节点是否匹配关键字。这样做是可以实现,但是缺点是需要遍历整颗树,当树的节点很多效率会很慢。
而从树匹配中的节点开始往上遍历出所有的节点,最后在组装成树,会大大减少需要查询处理的节点。
边栏推荐
- 【luogu P8326】Fliper(图论)(构造)(欧拉回路)
- Golang 必知必会Go Mod命令
- 架构师04-应用服务间加密设计和实践
- Apache EventMesh 分布式事件驱动多运行时
- Flutter gets the height of the status bar statusbar
- API for JD.com to obtain historical price information of commodities
- UserAgent 解析
- Multi-datacenter operation and detection of concurrent writes
- 2022年Android 面经总结(附含面试题 | 源码 | 面试资料)
- matplotlib ax bar color Set the color, transparency, label legend of the ax bar
猜你喜欢
随机推荐
2022 Android interview summary (with interview questions | source code | interview materials)
MySQL---sort and pagination
JD.com searches for products by keyword API
This 985 professor is on fire!After 10 years of Ph.D. supervisor, no one has graduated with a Ph.D.!
组合学笔记(六)局部有限偏序集的关联代数,Möbius反演公式
【愚公系列】2022年07月 Go教学课程 020-Go容器之数组
Flutter gets the height of the status bar statusbar
程序员如何学习开源项目,这篇文章告诉你
MySQL - single function
Bika LIMS open source LIMS set - use of SENAITE (detection process)
2022年Android 面经总结(附含面试题 | 源码 | 面试资料)
Anaconda如何顺利安装CV2
UVM RAL模型和内置seq
架构师04-应用服务间加密设计和实践
MySQL---Subqueries
go基础部分学习笔记记录
[TypeScript] OOP
[pytorch] 1.7 pytorch and numpy, tensor and array conversion
GP 6 overall architecture study notes
全平台GPU通用AI视频补帧超分教程