V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
1iuh
V2EX  ›  问与答

树型结构数据的存储,我这个方案靠谱么?

  •  
  •   1iuh · 2017-06-22 10:18:14 +08:00 · 1572 次点击
    这是一个创建于 2520 天前的主题,其中的信息可能已经有所发展或是发生改变。

    项目中要存储一个树形结构。之前采用的是每条数据带一个 parent_id 这种邻接表的方案。

    然而这个方案查询所有下级节点的时候,需要迭代查询,所以效率非常低,所以考虑优化。

    一番 google 之后,选择了 Closure Table 闭包表的方案,这个方案查询所有上级节点或所有下级节点的效率都非常高。但是这个方案在序列化数据的时候依然很麻烦。

    前端要求组织的数据格式如下: { "id": "1", "name": "root", "children": [ { "id": "2", "name": "aaa", "children": [] } ] }

    现在序列化采取的方案是:

    1. 取出所有下级节点数据。
    2. 查询出所有节点的上级节点,放入节点数据中。
    3. 依据每个节点的上级节点,组织数据。(耗时较多,代码如下(省略了数据库查询部分))
    def insertNode(result, node, query_result):
        node_id = node['id']
        parent_id = node['parent']
        if findNode(result, node_id) is None:
            parent = findNode(result, parent_id)
            if parent is None:
                result = insertNode(result, query_result[parent_id], query_result)
                parent = findNode(result, parent_id)
            parent['children'].append(node)
        return result
    
    
    def findNode(result, node_id):
        if result.get('id', None) == node_id:
            return result
        else:
            for node in result.get('children', []):
                target = findNode(node, node_id)
                if target is not None:
                    return target
            return None
    
    
    if __name__ == '__main__':
        result = {}
        for node in nodes:
        	result = insertNode(result, node, query_result)
        print(json.dumps(result))
        	
    

    总之,我就想问下各位大佬,这个方案靠谱么?

    如果靠谱,还有什么地方可以优化?

    如果不靠谱,我应该怎么做?

    2 条回复    2017-08-02 01:01:38 +08:00
    1iuh
        1
    1iuh  
    OP
       2017-06-22 16:45:50 +08:00
    6 小时惨案~ 没有大佬指点一下么?
    HanSonJ
        2
    HanSonJ  
       2017-08-02 01:01:38 +08:00
    但看文字没看出跟原本的递归有何差别
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1002 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 20:55 · PVG 04:55 · LAX 13:55 · JFK 16:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.