Priyath Gregory
Priyath Gregory

Reputation: 987

Set multiple keys having multiple values to Redis

I have a php backend using phpredis (a php client for the redis server) to store key value pairs to a Redis server. The data I need to store is of this form:

"key1" => "v1", "v2", "v3"
"key2" => "m1", "m2", "m3"
"key3" => "n1", "n2", "n3"
...

Based on my research, I can set multiple keys in a redis using the mset command like so:

$redis->mSet(array('key0' => 'value0', 'key1' => 'value1'));

But what I actually need is something like this:

$redis->mSet(array('key0' => array('v1','v2','v3') , 'key1' => array('m1', 'm2', 'm3')));

But this just stores the value for each key as "Array" instead of the actual array specified.

Is this possible to do with a single command like mset or do I need to iterate my data and set each key separately using something like lPush?

phpredis documentation: https://github.com/phpredis/phpredis

Upvotes: 2

Views: 15376

Answers (1)

Mikey
Mikey

Reputation: 2704

So rather than using mSet you can probably use sADD to get your desired functionality.

$redis->sAdd($key, ...$data);

Full documentation on it here.

This would mean iterating and doing it in multiple steps for which I'd reccomend reading into Redis Pipelines and the non-shameless plug link which contains more information.

Which would look something like;

$redis    = new Redis();
$pipeline = $redis->multi(Redis::PIPELINE);

foreach ($dataset as $data) {
    $pipeline->sAdd($data['key'], ...$data['values']);
}

$pipeline->exec();

I can't think off the top of my head a way to do this in a singular operation, someone else might come along though who knows more than me :)


Edit: Looks like I misunderstood your question a little as it was more focused on doing this in a single operation. Hopefully the above is still useful but to my knowledge you'll have to do this with multiple.

Upvotes: 1

Related Questions