使用 materialized path 与嵌套集在 SQLAlchemy 中的实现思路?
解读
国内互联网面试中,树形结构存储与查询是后台架构高频考点。
materialized path(物化路径)与嵌套集(nested set)是两种无需递归即可在关系型数据库中高效查询树的经典模型。
面试官想确认:
- 你是否理解两种模型的存储格式、查询方式与更新代价;
- 能否用 SQLAlchemy 的自定义类型、事件钩子、CTE、索引等机制零魔法、零触发器地落地;
- 是否知道在高并发写场景下如何权衡一致性、性能与可维护性。
知识点
- materialized path:用一条字符串字段保存从根到当前节点的完整路径(如
/1/3/9/),查询子树用LIKE '/1/3/%'并配合函数索引或前缀索引。 - nested set:用
lft、rgt两个整数闭合区间表示节点,子树查询变成WHERE lft BETWEEN parent.lft AND parent.rgt,但插入/删除需重排区间。 - SQLAlchemy 工具箱:
- custom TypeDecorator 封装路径字符串与列表互转;
- before_insert / before_update 事件自动维护路径或左右值;
- postgresql.ARRAY + GIN 或 MySQL 前缀索引 加速 path 查询;
- CTE + recursive 作为 fallback 兼容方案;
- session.flush() 时机与行级锁(SELECT … FOR UPDATE) 保证并发安全;
- Alembic 批量迁移脚本中预计算 nested set 区间。
答案
以下给出两种模型的最小可运行骨架,均基于 SQLAlchemy 2.0 声明式风格,支持同步 Session 与 async AsyncSession(只需替换引擎与 session 工厂)。
一、materialized path 实现
from __future__ import annotations
from sqlalchemy import String, Index, event, select
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session
class Base(DeclarativeBase):
pass
class PathType(TypeDecorator):
impl = String(1000)
cache_ok = True
def process_bind_param(self, value: list[int] | None, dialect):
return '/' + '/'.join(map(str, value)) + '/' if value else None
def process_result_value(self, value: str | None, dialect):
return [int(x) for x in value.strip('/').split('/')] if value else []
class Category(Base):
__tablename__ = 'category'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
path: Mapped[list[int]] = mapped_column(PathType, index=True)
__table_args__ = (
Index('ix_category_path_prefix', 'path', postgresql_ops={'path': 'text_pattern_ops'}),
)
@event.listens_for(Category, 'before_insert')
def auto_path(mapper, connection, target: Category):
if target.path is None:
if target.parent_id is None:
target.path = [target.id]
else:
parent_path = connection.scalar(
select(Category.path).where(Category.id == target.parent_id)
)
target.path = parent_path + [target.id]
# 查询某节点全部后代
def descendants(session: Session, node_id: int):
node = session.get(Category, node_id)
return session.scalars(
select(Category).where(Category.path.like(f'{"/".join(map(str, node.path))}/%'))
).all()
关键点
- 用 TypeDecorator 把 Python
list[int]与数据库字符串互转,业务代码无感知; - before_insert 事件里直接通过
connection.scalar拿父路径,绕过 ORM 缓存,保证事务内一致; - PostgreSQL 用
text_pattern_ops索引,MySQL 用 prefix index (path(255)); - 删除节点时,级联删除所有
LIKE匹配行即可,无需额外锁。
二、nested set 实现
from sqlalchemy import Integer, event, select, func, and_
class NSNode(Base):
__tablename__ = 'ns_node'
id: Mapped[int] = mapped_column(primary_key=True)
name: Mapped[str]
lft: Mapped[int] = mapped_column(Integer, index=True)
rgt: Mapped[int] = mapped_column(Integer, index=True)
@event.listens_for(NSNode, 'before_insert')
def allocate_nested_set(mapper, connection, target: NSNode):
# 把新节点插成最后一个孩子:lft = parent.rgt, rgt = parent.rgt + 1
parent = connection.scalar(
select(NSNode).where(NSNode.id == target.parent_id).with_for_update()
)
if parent is None: # 作为新的根
max_rgt = connection.scalar(select(func.coalesce(func.max(NSNode.rgt), 0)))
target.lft = max_rgt + 1
target.rgt = max_rgt + 2
else:
# 预留空位:右移 ≥ parent.rgt 的所有节点
connection.execute(
NSNode.__table__.update().values(lft=NSNode.lft + 2),
NSNode.lft >= parent.rgt
)
connection.execute(
NSNode.__table__.update().values(rgt=NSNode.rgt + 2),
NSNode.rgt >= parent.rgt
)
target.lft = parent.rgt
target.rgt = parent.rgt + 1
# 查询子树
def subtree(session: Session, node_id: int):
node = session.get(NSNode, node_id)
return session.scalars(
select(NSNode).where(
and_(NSNode.lft >= node.lft, NSNode.rgt <= node.rgt)
).order_by(NSNode.lft)
).all()
关键点
- before_insert 里用 SELECT … FOR UPDATE 锁住父节点区间,防止并发插入导致区间重叠;
- 更新语句直接走
connection.execute,避免 ORM 批量同步带来的 N+1; - 删除节点需递归回收区间,可在 after_delete 事件里统一处理;
- 区间列用 整数索引,查询复杂度 O(k) 只与结果集大小相关,与树深度无关。
拓展思考
- 混合模型:对读多写少的类目系统,可用 materialized path 加速查询,再冗余一个
depth字段做层级过滤;对频繁移动节点的组织架构,nested set 区间重排代价高,可改用嵌套区间 + 浮点数(lft、rgt用numeric),插入时取中值,避免整表更新。 - 异步场景:在 AsyncSession 中事件回调拿不到同步
connection,需改用 async event(SQLAlchemy 1.4+)或显式 SQL 函数封装,确保await connection.execute()。 - 分库分表:若树按业务分区,path 里带上分片键(如
/{shard}/1/3/),查询时先路由到具体分片,再下推LIKE条件;nested set 则建议按根节点维度拆分,避免跨分片区间锁。 - 可视化运维:在 Alembic 升级脚本里加入
REINDEX与VACUUM命令,防止路径索引膨胀;同时提供python -m myapp.tree_rebuildCLI,一键重建 nested set 区间,方便运维同学快速修复数据漂移。