Redis: 实现树形数据结构

来源:互联网 时间:1970-01-01

目的:

        实现树形数据结构

        一次获取所有子节点

 

节点间没有排序,如果要实现排序,可以在每个节点增加一个排序字段,在 SORT 的 BY 参数中指定排序依据。

原始树:

 

    id: root, name: Root

      id: 1, name: Node1

        id: 11, name: Node11

          id: 111, name: Node111

          id: 112, name: Node112

        id: 12, name: Node12

      id: 2, name: Node2

        id: 21, name: Node21

        id: 22, name: Node22

 

生成树的操作,添加节点时:

 

    hmset tree:root name "Root" path ""

 

    hmset tree:1 name "Node1" path "root"

    sadd tree:root:heirs 1

 

    hmset tree:11 name "Node11" path "root,1"

    sadd tree:root:heirs 11

    sadd tree:1:heirs 11

 

    hmset tree:111 name "Node111" path "root,1,11"

    sadd tree:root:heirs 111

    sadd tree:1:heirs 111

    sadd tree:11:heirs 111

 

    hmset tree:112 name "Node112" path "root,1,11"

    sadd tree:root:heirs 112

    sadd tree:1:heirs 112

    sadd tree:11:heirs 112

 

    hmset tree:12 name "Node12" path "root,1"

    sadd tree:root:heirs 12

    sadd tree:1:heirs 12

 

    hmset tree:2 name "Node2" path "root"

    sadd tree:root:heirs 2

 

    hmset tree:21 name "Node21" path "root,2"

    sadd tree:root:heirs 21

    sadd tree:2:heirs 21

 

    hmset tree:22 name "Node22" path "root,2"

    sadd tree:root:heirs 22

    sadd tree:2:heirs 22

 

根据 id 获取子节点:

 

    SORT tree:root:heirs BY n/a GET tree:*->name GET tree:*->path

    SORT tree:1:heirs BY n/a GET tree:*->name GET tree:*->path

    SORT tree:11:heirs BY n/a GET tree:*->name GET tree:*->path

    SORT tree:2:heirs BY n/a GET tree:*->name GET tree:*->path

 

删除节点 111(没有子节点):

 

    // 检查子节点

    SMEMBERS tree:111:heirs         // 没有子节点

    // 删除上级节点的引用

    HGET tree:111 path              // root,1,11

    SREM tree:root:heirs 111

    SREM tree:1:heirs 111

    SREM tree:11:heirs 111

    // 删除自己

    DEL tree:111

 

删除节点 11(还有子节点112):

 

    // 检查子节点

    SMEMBERS tree:111:heirs         // 112

    // 删除子节点 ... 参见删除节点 111

    // 删除上级节点的引用

    HGET tree:11 path               // root,1

    SREM tree:root:heirs 11

    SREM tree:1:heirs 11

    // 删除自己

    DEL tree:111



相关阅读:
Top