Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compute the difference between two sets (sorted and simple)

Tags:

redis

Is there a way to compute the difference between two sorted sets (zset) or do I have to use simple sets for this?

Problem:

  1. Set F contains a list of sorted id's (sorted set, full list)
  2. Set K contains a list of id's (simple set, subset of F)

I want to retrieve every entry in F, in order, that's not in K.

Is this possible using Redis alone or do I have to do the computation on the application? If yes, what is the best way?

EDIT: SDIFF does not suit this purpose as it doesn't allow sorted sets.

like image 463
Andre Avatar asked Apr 15 '11 21:04

Andre


People also ask

What is the difference of set A and B?

The difference (subtraction) is defined as follows. The set A−B consists of elements that are in A but not in B. For example if A={1,2,3} and B={3,5}, then A−B={1,2}. In Figure 1.8, A−B is shown by the shaded area using a Venn diagram.

What are sorted sets?

Sorted set is essentially a unique collection of ordered Redis Strings that have a numeric score associated with them. Ordering is based on scores and the string lexicographical order (more on this later). The strings must be unique while the scores might be repeated.


1 Answers

Make a copy of F as a simple set. Let's call it G. Now perform the SDIFF.

Or...

Make a copy of F as a sorted set. Let's call it G. Iterate through K and remove each element from G.

SDIFF really should work on sorted sets, regular sets, or combinations. But, at this time, it does not.

Also, if F is very large, you may see some performance hits when you make a copy of it. In this case, create a set G in your Redis DB that it updated when K is updated. That is, F and G are initially equal. As you add elements to K, remove the element from G.

like image 196
BMiner Avatar answered Oct 26 '22 08:10

BMiner