Reputation: 2172
Redis is awesome !
If I have 2 sorted sets like - "set1 = key1:100, key2:200, key3:300"
and another like "set2 = key1:1, key2:2, key3:3"
then is it possible to get like this - set3 = key1:100_1, key2:200_2, key3:300_3
I do not want to add values of same key or take min/max of same key. Is it possible to get these values together ? I want to get both of these values in together for that same key.
Upvotes: 1
Views: 1754
Reputation: 73306
A score in a sorted set has to be a numerical value, so it is not possible to return a simple concatenation of the scores in intersection/union operations.
However, if you can bound the value of the scores for each set to a given range, it is possible to use the SUM operation to encode two values in a single value with simple arithmetic.
Example:
# For s1, we assume the score is between 0 and 999
> zadd s1 100 key1 200 key2 300 key3
(integer) 3
# For s2, we assume the score is between 0 and 99
> zadd s2 1 key1 2 key2 3 key3
(integer) 3
# Get the intersection, dividing the s2 score by 100
> zinterstore s3 2 s1 s2 WEIGHTS 1 0.01
(integer) 3
# Get the result with scores
> zrange s3 0 -1 withscores
1) "key1"
2) "100.01000000000001"
3) "key2"
4) "200.02000000000001"
5) "key3"
6) "300.02999999999997"
In the resulting scores, the integer part contains the score coming from s1, the fractional part contains the score coming from s2.
Please note the score is a double floating point number. It has some consequences:
you may have to round it properly if you manipulate only integers (i.e. 0.0299999... is actually 0.03)
encoding two numerical values in one means the precision is divided by 2 (16 digits to 8 digits only). It may or may not suit your needs.
Upvotes: 1