Redis Sorted Sets: How to get the first intersecting element?

There are some large sorted sets in Redis (5m-25m) and I want to get the first item that appears in the combination of these sets. for example i have 20 sets and you want to take set 1, 5, 7 and 12 and get only the first intersection of only those sets.

It would seem that ZINTERSTORE followed by "ZRANGE foo 0 0" would do a lot more work that I need as it will compute all intersections and then return the first one. Is there an alternative solution that doesn't need to compute all intersections?

+3


source to share


1 answer


There is no direct, native alternative, although I would suggest the following:

Create a hash whose members are your items. Each time you add to one of your sorted sets, increment the corresponding member (using HINCRBY

). Of course, you will only increment after you have verified that the item does not already exist in the sorted set you are trying to add.



This way you can quickly find out which items appear in the 4 sets.

UPDATE: Now that I've rethought about this, it might be too expensive to query your hash to find items with a value of 4 (O (n)). Another option would be to create another Sorted Set that has your elements as members and their score increases (as I described earlier, but using ZINCRBY

) and you can quickly pull all elements with a count of 4 (using ZRANGEBYSCORE

).

+2


source







All Articles