Search code examples
pythonluaredisredis-py

Redis: Finding the SCARD of an SINTER result without storing the intermediate set


I need the length (SCARD) of the intersection of 2 large sets in redis.

So this achieves what I want:

> SINTERSTORE intermediate s:1 s:2
> SCARD intermediate

However the sets are large, so I don't want to store the intermediate value. Conceptually I want:

> SCARD (SINTER s:1 s:2)

Is there a way to achieve this in a single command, perhaps with Lua scripting? Or is my best bet to script it out in my application language and delete the intermediate value when I'm done? e.g. using python and redis-py:

>>> r = redis.Redis(...)
>>> pipe = r.pipeline()
>>> res = pipe.sinterstore('intermediate', 's:1', 's:2').scard('intermediate').delete('intermediate').execute()
>>> print res[1]

Solution

  • Redis doesn't do nested commands so the conceptual version, while helpful to describe the need, isn't supported.

    I suggest that you use the intermediate value approach, but instead of pipelining use a transaction (MULTI/EXEC) to wrap the intersect, cardinality and delete operations.