srandmember
1. 基本語法
srandmember(key
, [count:<integer>]
, callback
)
key
, [count:<integer>]
, callback
) 對集合進行|count|
次隨機抽樣,並回傳抽樣結果;重複或不重複抽樣取決於count
正負。
count
取值
抽樣方式
回傳結果
正整數
不重複抽樣
小於等於count
個不重複成員;
若count
大於集合成員數量,最多僅回傳集合內所有成員。
負整數
重複抽樣
Redis版本2.6開始,回傳|count|
個可能重複的成員。
非整數
-
錯誤訊息
0
-
空值
2. 範例
(1) 隨機挑選1個成員
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
client.srandmember('food', redis.print);
client.srandmember('food', redis.print);
client.srandmember('food', redis.print);
Reply: apple
Reply: apple
Reply: potato
(2) [不重複抽樣]:隨機挑選n個不重複成員
n 不超過集合成員總數
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
let n = 2;
client.srandmember('food', n, redis.print);
client.srandmember('food', n, redis.print);
client.srandmember('food', n, redis.print);
Reply: apple,onion
Reply: apple,onion
Reply: potato,onion
n 超過集合成員總數
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
let n = 5;
client.srandmember('food', n, redis.print);
client.srandmember('food', n, redis.print);
client.srandmember('food', n, redis.print);
Reply: apple,onion,potato
Reply: apple,onion,potato
Reply: apple,onion,potato
(3) [重複抽樣]:隨機挑選n個成員,同一個成員可以被重複挑選。
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
let n = -5;
client.srandmember('food', n, redis.print);
client.srandmember('food', n, redis.print);
client.srandmember('food', n, redis.print);
Reply: apple,apple,apple,onion,apple
Reply: apple,potato,apple,onion,potato
Reply: potato,potato,potato,apple,potato
(4) 若count
非整數或超出範圍,則回傳錯誤
const arr = ['apple', 'potato', 'onion']
client.sadd('food', arr);
let n = 9223372036854775808;
client.srandmember('food', n, redis.print);
ReplyError: ERR value is not an integer or out of range
Last updated
Was this helpful?