zrange和zrangebyscore区别

zrange和zrangebyscore区别

先提出结论:
zrange是通过索引查询,也就是数组的索引(这里类比成数组),说白了就是查询第几个元素。
zrangebyscore是通过score查询,查出对应score的元素。

需求

需要在zset中查询score为某一特定值的key有哪些。
在try.redis.io中做的实验。

zrange zs 0 -1 withscores
1) "wangwu"
2) -1.8
3) "zhangsan"
4) 0.0
5) "lisi"
6) 2.0
7) "mickeal"
8) 2.0
9) "ccg"
10) 7.33

zset内容是上面的,现在我想查询score为2的

zrange zs 2 2 withscores
1) "lisi"
2) 2.0

这么只得到了一个结果,于是我就开始查验,我们直接看官方文档。

查证

https://redis.io/commands/zrange,上面对于zrange的解释:

Index ranges
By default, the command performs an index range query. The and arguments represent zero-based indexes, where 0 is the first element, 1 is the next element, and so on. These arguments specify an inclusive range, so for example, ZRANGE myzset 0 1 will return both the first and the second element of the sorted set.(返回第一个和第二个zset的元素)

The indexes can also be negative numbers indicating offsets from the end of the sorted set, with -1 being the last element of the sorted set, -2 the penultimate element, and so on.

Out of range indexes do not produce an error.
If is greater than either the end index of the sorted set or , an empty list is returned.
If is greater than the end index of the sorted set, Redis will use the last element of the sorted set.

这段在最开始就说明了是使用索引,并说明了索引是什么,在下一段就是我们想要的查询score的方式

Score ranges
When the BYSCORE option is provided, the command behaves like ZRANGEBYSCORE and returns the range of elements from the sorted set having scores equal or between and .
and can be -inf and +inf, denoting the negative and positive infinities, respectively. This means that you are not required to know the highest or lowest score in the sorted set to get all elements from or up to a certain score.
By default, the score intervals specified by and are closed (inclusive). It is possible to specify an open interval (exclusive) by prefixing the score with the character (.
For example:
ZRANGE zset (1 5 BYSCORE
Will return all elements with 1 < score <= 5 while:
ZRANGE zset (5 (10 BYSCORE
Will return all the elements with 5 < score < 10 (5 and 10 excluded).

也就是说我们查询某个值对应的key,需要用byscore参数,同时可以通过括号指定开闭区间,加上括号是开区间,默认是闭区间。但是我在实验的时候发现redis并不认识这个参数,所以还是使用zrangebyscore指令。

 zrangebyscore zs 2 2
1) "lisi"
2) "mickeal"
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值