Skip to content

Instantly share code, notes, and snippets.

@nrk
Created November 8, 2011 10:50
Show Gist options
  • Save nrk/1347484 to your computer and use it in GitHub Desktop.
Save nrk/1347484 to your computer and use it in GitHub Desktop.
Use Redis scripting to copy an hash to a new key.
<?php
require 'autoload.php';
$redis = new Predis\Client('tcp://127.0.0.1', 'dev');
// *** NOTE *** Lua's unpack() has a limit on the size of the table imposed by
// the number of Lua stack slots that a C function can use. This value is defined
// by LUAI_MAXCSTACK in luaconf.h and for Redis is set to 8000, which translates
// to an hash of 4000 elements since HGETALL returns a list that interleaves field
// names and their values.
// See: https://github.com/antirez/redis/blob/b903145/deps/lua/src/luaconf.h#L439
$script = <<<LUA
local hash = redis.call('hgetall', KEYS[1]);
if #hash == 0 then
return { err = 'The key "'..KEYS[1]..'" does not exist' }
end
return redis.call('hmset', KEYS[2], unpack(hash));
LUA;
$client->hmset('original', 'foo', 'bar', 'lol', 'wut', 'hoge', 'piyo');
$client->eval($script, 2, 'original', 'copied');
$copied = $client->hgetall('copied');
var_export($copied);
// array (
// 'foo' => 'bar',
// 'lol' => 'wut',
// 'hoge' => 'piyo',
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment