Redis 排序命令
SORT 命令SORT key
sort 可以有set ,list ,zset 进行排序,默认按集合的元素值转换为数值进行从小到大排序。
参数: :如果元素值不是数据,则可以指定ALPHA参数,按照字典顺序排序。
:默认sort是从小到大排序,可以指定DESC 为降序
: 从排序结果中取序号为offset开始的count个元素
:把排序结果存储在一个List变量中
localhost:6379> sadd myset 1 3 5 6 7 0 9
(integer) 7
localhost:6379> sort myset
1) "0"
2) "1"
3) "3"
4) "5"
5) "6"
6) "7"
7) "9"
localhost:6379> sadd netsites 163 sohu yahoo baidu 12306
(integer) 5
localhost:6379> sort netsites alpha
1) "12306"
2) "163"
3) "baidu"
4) "sohu"
5) "yahoo"
localhost:6379> sort netsites alpha limit 0 3
1) "12306"
2) "163"
3) "baidu"
localhost:6379> sort netsites alpha limit 0 3 desc
1) "yahoo"
2) "sohu"
3) "baidu"
localhost:6379> sort netsites alpha limit 0 3 desc store sort:netsites
(integer) 3
localhost:6379> lrange sort:netsites 0 -1
1) "yahoo"
2) "sohu"
3) "baidu"
参数说明:
参数说明:
localhost:6379> set students:name:1 tom //ID=1的学生名字
OK
localhost:6379> set students:name:2 carry//ID=2的学生名字
OK
localhost:6379> set students:name:3 jack//ID=3的学生分名字
OK
localhost:6379> set students:name:4 lisa//ID=4的学生分名字
localhost:6379> set students:score:1 98 //ID=1的学生分值98
OK
localhost:6379> set students:score:2 39//ID=2的学生分值39
OK
localhost:6379> set students:score:3 80//ID=3的学生分值80
OK
localhost:6379> set students:score:4 58//ID=4的学生分值58
OK
localhost:6379> lpush students 1 2 3 4 //学生id存入list
(integer) 4
localhost:6379> sort students //按照集合中元素值(id)排序的结果
1) "1"
2) "2"
3) "3"
4) "4"
localhost:6379> sort students by students:score:* //关联分值的排序结果 用studnets中的元素值替换students:score:*中的*而生成的key 的值进行排序。
1) "2" //替换后排序的元为:students:score:1,students:score:2,students:score:3,students:score:4
2) "4"//对这4个key进行排序,依据该排序结果输出对应的集合元素顺序
3) "3"
4) "1"
localhost:6379>sort students by students:score:*get students:name:* //按照集合排序结果中的元素值替换 get之后的key的中的*而生成的实际key来获取值
1) "carry"
2) "lisa"
3) "jack"
4) "tom"
//sort students by students:score:* 排序后结果为 2,4,3,1 替换get 之后的key而生成 :
students:name:2
students:name:4
students:name:3
students:name:1
以上key对应的值顺序为:
1) "carry"
2) "lisa"
3) "jack"
4) "tom"
localhost:6379> hmset student:1 name lining age 32 sex boy score 76
OK
localhost:6379> hmset student:2 name lisi age 21sex girlscore 87
OK
localhost:6379> hmset student:7 name tom age 25sex boy score 34
OK
localhost:6379> sadd studentIds 1 2 7
(integer) 3
localhost:6379> sort studentIds
1) "1"
2) "2"
3) "7"
localhost:6379> sort studentIds by student:*->score////关联分值的排序结果用studentIds中的元素值替换student:*->score,而生成:student:1->score,student:2->score,student:7->score,表明是按散列表的score值时行排序,依据该排序结果输出对应的集合元素顺序
1) "7"
2) "1"
3) "2"
localhost:6379> sort studentIds by student:*->score get student:*->name
1) "tom"
2) "lining"
3) "lisi"
//可以通过get获取多个值
localhost:6379> sort studentIds by student:*->score get student:*->name get student:*->age get student:*->sex
1) "tom"
2) "25"
3) "boy"
4) "lining"
5) "32"
6) "boy"
7) "lisi"
8) "21"
9) "girl"
页:
[1]