1
votes

Is it possible to use ZUNIONSTORE for a certain range of a sorted set? I'm currently using Andy McCurdy's Python Redis Module: https://github.com/andymccurdy/redis-py

For example. Let's say I have two sorted sets. set1 has 5 elements and set2 has 10 elements.

Here is set1:

[('1', 1.0), ('2', 2.0), ('3', 3.0), ('4', 4.0), ('5', 5.0)]

Here is set2

[('6', 6.0), ('7', 7.0), ('8', 8.0), ('9', 9.0), ('10', 10.0), ('11', 11.0), ('12', 12.0), ('13', 13.0), ('14', 14.0), ('15', 15.0)]

I tried grabbing the top 5 elements from set2 by doing:

trimmed_set = r_server.zrevrange('set2', 0, 4, withscores=True)

This returns:

[('11', 11.0), ('12', 12.0), ('13', 13.0), ('14', 14.0), ('15', 15.0)]

so far so good. But now I would like to merge the trimmed set with set1.

I tried doing:

r_server.zunionstore('set3', ['set1', 'trimmed_set'])

This didn't work. All it did was make set3 a copy of set1.

Is there any other way I can achieve something like this without going through a loop?

1

1 Answers

1
votes

ZUNIONSTORE takes only keys as parameters, not Python variables. So you should iterate on trimmed_setvalues and store them into a new sorted set using the ZADD function. If the key of this ZSET is trimmed_set, then your last line of code will work:

r_server.zunionstore('set3', ['set1', 'trimmed_set'])  

Alternatively you could use a Lua script to perform the trimming and storage of the second set inside Redis.