5

In redis, is it possible to set a maximum number of elements to a set so when one use the sadd, the redis server prevents the set from having more elements that a maximum amount? e.g. something like :

127.0.0.1:6379> SETSIZE KEY 100

Thanks in advance.

Geoffrey R.
  • 1,907
  • 1
  • 19
  • 32

1 Answers1

5

No, it`s not possible with usual commands but possible with LUA scripting:

local size = redis.call('SCARD', KEYS[1]);
if size < tonumber(ARGV[1], 10) then 
    return redis.call('SADD', KEYS[1], ARGV[2]);
end  
return -1;
Lukas Liesis
  • 24,652
  • 10
  • 111
  • 109
Nick Bondarenko
  • 6,211
  • 4
  • 35
  • 56
  • Not really. You can still modify the sets directly without going through the Kia script. – The Real Bill Jan 13 '16 at 21:47
  • 2
    It not possible do that in atomic way without LUA. You are wrong, @The Real Bill – Nick Bondarenko Jan 14 '16 at 04:39
  • 1
    What are you talking about? Nothing prevents you from adding things to the set without Lua. Nothing. I'd suggest toning down your attitude - especially when you are the one who is incorrect. Nobody said anything about atomic operations as that is irrelevant. Your proposed script does not cap the number of items in a set in Redis, it merely prevents that script from doing it. It can't actually cap a set as Redis doesn't have that feature. Calling SADD will still add items as long as there is memory available. – The Real Bill Jan 14 '16 at 12:47
  • The question is how to add elements to SET with a maximum amount - in few words "if count of elements in SET < X then add element ". Tell me please how to do this without LUA and atomic operations? And yes, the given LUA code executed in Redis instead of SADD realize the capped SET. – Nick Bondarenko Jan 14 '16 at 12:51
  • No the question was how to have Redis prevent SADD from adding beyond a number - capping the set. You can't do it. Client code, which includes Lua scripting, can avoid calling SADD but the server can not prevent an SADD from adding another member as long as there is memory available. All operations in Redis are atomic so that has nothing to do with it. – The Real Bill Jan 14 '16 at 13:00
  • I forgot that you're living in complex world of probabilities :) Man solves their specific business problem, not a feature for Redis internals. So good luck to you ;) – Nick Bondarenko Jan 14 '16 at 13:04
  • We call that world "software". ;) – The Real Bill Jan 14 '16 at 13:05
  • A normal people usually call this business requirements ;) – Nick Bondarenko Jan 14 '16 at 13:07