「redis入門」ソート済みセット型(sorted set)を利用するサンプル

2018年8月25日

サンプルコード:
$redis = new Redis();
//接続
$redis->connect(‘172.12.10.111’, 6379);
//要素追加
echo $redis->zadd(‘set’, 1, ‘cat’);echo ‘<br>’;
echo $redis->zadd(‘set’, 2, ‘dog’);echo ‘<br>’;
echo $redis->zadd(‘set’, 3, ‘fish’);echo ‘<br>’;
echo $redis->zadd(‘set’, 4, ‘dog’);echo ‘<br>’;
echo $redis->zadd(‘set’, 4, ‘bird’);echo ‘<br>’;
//集合のすべての要素を返す
print_r($redis->zrange(‘set’, 0, -1));echo ‘<br>’;
print_r($redis->zrange(‘set’, 0, -1, true));echo ‘<br>’;
//要素のscore値を返す
echo $redis->zscore(‘set’, ‘dog’);echo ‘<br>’;
//数を返す
echo $redis->zcard(‘set’);echo ‘<br>’;
//指定されるメンバーを削除
$redis->zrem(‘set’, ‘cat’);
print_r($redis->zrange(‘set’, 0, -1));echo ‘<br>’;
// min~maxの個数を返す
print_r($redis->zcount(‘set’, 3, 5));echo ‘<br>’;
//min~maxの値を返す
print_r($redis->zrangebyscore(‘set’, 3, 5));echo ‘<br>’;
print_r($redis->zrangebyscore(‘set’, 3, 5, [‘withscores’=>true]));echo ‘<br>’;
//区間の値を返す
print_r($redis->zrevrange(‘set’, 1, 2));echo ‘<br>’;
print_r($redis->zrevrange(‘set’, 1, 2, true));echo ‘<br>’;
//有序集合中指定值的socre增加
echo $redis->zscore(‘set’, ‘dog’);echo ‘<br>’;
$redis->zincrby(‘set’, 2, ‘dog’);
echo $redis->zscore(‘set’, ‘dog’);echo ‘<br>’;
//min~maxの要素を削除
print_r($redis->zrange(‘set’, 0, -1, true));echo ‘<br>’;
print_r($redis->zremrangebyscore(‘set’, 3, 4));echo ‘<br>’;
print_r($redis->zrange(‘set’, 0, -1, true));echo ‘<br>’;

実行結果:
1
0
0
0
0
Array ( [0] => cat [1] => fish [2] => bird [3] => dog )
Array ( [cat] => 1 [fish] => 3 [bird] => 4 [dog] => 4 )
4
4
Array ( [0] => fish [1] => bird [2] => dog )
3
Array ( [0] => fish [1] => bird [2] => dog )
Array ( [fish] => 3 [bird] => 4 [dog] => 4 )
Array ( [0] => bird [1] => fish )
Array ( [bird] => 4 [fish] => 3 )
4
6
Array ( [fish] => 3 [bird] => 4 [dog] => 6 )
2
Array ( [dog] => 6 )