Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get DIFF on sorted set

Tags:

redis

How do I get most weighted elements from a sorted set, but excluding those found in another set(or list or hash).

>zadd all 1 one
>zadd all 2 two
>zadd all 3 three
>sadd disabled 2
>sdiff all disabled

(error) WRONGTYPE Operation against a key holding the wrong kind of value

Is my only option is to get elements from the sorted set one-by-one and compare to the list of "disabled" items? Wouldn't that be very slow because of so many transactions to a server?

What is the approach here?

like image 577
exebook Avatar asked Mar 20 '26 20:03

exebook


1 Answers

Note: I assume you've meant sadd disabled two

As you've found out, SDIFF does not operate on sorted sets - that is because defining the difference between sorted sets isn't trivial.

What you could do is first create a temporary set with ZUNIONSTORE and set the intersect's scores to 0. Then do a range excluding the 0, e.g.:

127.0.0.1:6379> ZADD all 1 one 2 two 3 three
(integer) 3
127.0.0.1:6379> SADD disabled two
(integer) 1
127.0.0.1:6379> ZUNIONSTORE tmp 2 all disabled WEIGHTS 1 0 AGGREGATE MIN
(integer) 3
127.0.0.1:6379> ZREVRANGEBYSCORE tmp +inf 1 WITHSCORES
1) "three"
2) "3"
3) "one"
4) "1"
like image 170
Itamar Haber Avatar answered Mar 24 '26 23:03

Itamar Haber