Reputation: 116
Is there a way to do this in redis ?
SET counter 0
INCR counter
SET KEY:{counter} "Content of line 1"
INCR counter
SET KEY:{counter} "Different content of line 2"
My example code should be substituted (i.e., transformed at runtime by the redis-cli) into:
SET counter 0
INCR counter
SET KEY:1 "Content of line 1"
INCR counter
SET KEY:2 "Different content of line 2"
etc.
My problem is NOT how to auto-increment the counter.
My problem is syntax: How to include a generic {wildcard} into something like:
SET keyname:{currentcounter} "value" ...
Any help is appreciated. Thanks a lot !
bernie
Upvotes: 3
Views: 5317
Reputation: 131978
If you are using redis 2.6+ then you can use lua scripting along with EVAL command like the following:
eval "local c = redis.call('incr', KEYS[1]);
return redis.call('set', KEYS[2] .. ':' .. c, ARGV[1])"
2 counter KEY "Content of line 1"
I broke it up onto multiple lines to make it easier to read.
EDIT
Sorry, I was away on business for a few days. Here is a sample showing that it works.
redis 127.0.0.1:6379> flushdb
OK
redis 127.0.0.1:6379> eval "local c = redis.call('incr', KEYS[1]); return redis.call('set', KEYS[2] .. ':' .. c, ARGV[1])" 2 counter KEY "Content of line 1"
OK
redis 127.0.0.1:6379> keys *
1) "KEY:1"
2) "counter"
redis 127.0.0.1:6379> get counter
"1"
redis 127.0.0.1:6379> get KEY:1
"Content of line 1"
redis 127.0.0.1:6379> eval "local c = redis.call('incr', KEYS[1]); return redis.call('set', KEYS[2] .. ':' .. c, ARGV[1])" 2 counter KEY "Content of the next thing"
OK
redis 127.0.0.1:6379> keys *
1) "KEY:1"
2) "KEY:2"
3) "counter"
redis 127.0.0.1:6379> get counter
"2"
redis 127.0.0.1:6379> get KEY:2
"Content of the next thing"
Upvotes: 1
Reputation: 12031
Nope, SET/GET commands don't support this.
You can do similar things using LUA scripts in redis, or even simpler; you can issue the commands as redis expect them using trivial programming/scripting
Upvotes: 0