我们有几个带有lft
/的 MySQL 表rgt
(嵌套集/修改的前序树遍历),parent_id
以及level
其中的列。每天晚上,我们都会擦除表格并从客户那里获取新数据。由于我们从客户端数据库中获取数据的方式,我们可以轻松计算parent_id
and level
,但是lgt
andrgt
是在我们与存储过程同步之后设置的。到目前为止,我们只需要处理非常小的结果集,不超过 30,000 行。但是现在我们正在查看超过 200,000 个 em,而且这需要很长时间。我已经同步运行了一个多小时,但仍然没有完成,通常需要大约 5-15 分钟(我也觉得有点多)。
在存储到数据库之前是否有另一种方法来计算lft
/ ?rgt
(最好用python)
我们同步的一些伪代码:
class Node(object):
def __init__(self, id, data=None):
self.id = id
self.children = []
self.data = data
self.parent = None
def add_child(self, child):
self.children.append(child)
child.parent = self
def sync(source_sql_result):
node_map = {}
current_id = 0
parent_node = None
for source_row in source_sql_result:
for i, row in enumerate(get_subrows(source_row), 1):
try:
parent_node = node_map[row['identifier']]
except KeyError:
# New node found
current_id += 1
row['level'] = i
node = Node(id=current_id, data=row)
if parent_node is not None:
parent_node.add_child(node)
node_map[row['identifier']] = node
parent_node = node
for node in node_map.values():
yield node.data