YoungDinosaur
YoungDinosaur

Reputation: 1560

Redis Chain Commands

I'm wondering what is the best way to chain together a series of commands so that they all execute on redis before returning the final result? All of my data is stored in Sets.

data1 = [ a, b, c, d, e]
data2 = [b, c]

How would I go about getting the intersection of data1 and data2 (result=b,c) and then call SRANDMEMBER on the result? In a series it would look like:

redis> SINTER data1 data2
redis> SRANDMEMBER <previous result>

There could of course be other operations to chain together like SDIFF and SADD but choosing a random item from an intersection seems like the simplest example.

I tries creating a lua script but I received the message "Lua redis() command arguments must be strings or integers" when I attempted to execute the following code:

local k1, k2 = KEYS[1], KEYS[2]
local intersect, single_record

if not redis.call("exists", k1) then return 0 end

intersect_data = redis.call("SINTER", k1, k2)
single_record = redis.call("SRANDMEMBER", intersect_data)

return single_record

Upvotes: 0

Views: 744

Answers (1)

Itamar Haber
Itamar Haber

Reputation: 50112

tl;dr - you're passing a Lua table (intersect_data) instead of a string and an optional number to SRANDMEMBER.

SINTER may return 0 or more results as a Lua table. SRANDMEMBER requires a single key name that is a Redis Set and an optional count (integer) argument.

The biggest issue I see with the above logic is that it appears to assume that the intersect yields exactly one result. It doesn't care about 0 or more than 1...

Assuming that a single result is always returned from the intersect, you should call SRANDMEMBER with intersect_data[1] (the first element in the table).

Upvotes: 1

Related Questions