Redis:实现树形数据结构⽬的:
实现树形数据结构
⼀次获取所有⼦节点
节点间没有排序,如果要实现排序,可以在每个节点增加⼀个排序字段,在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获取⼦节点:
redis五种数据结构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

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。