如何在Redis中使用带有Lua脚本的sscan?

时间:2018-01-15 02:50:49

标签: lua redis

我希望在SSCAN command完成时获得多个值。

127.0.0.1:6379[2]> sadd Test:Info:Site 'www.naver.com' 'www.google.com' 'www.daum.net' 'www.korea.com'
(integer) 4
127.0.0.1:6379[2]> smembers Test:Info:Site
    1) "www.naver.com"
    2) "www.daum.net"
    3) "www.korea.com"
    4) "www.google.com" 

我想回来" 0"

127.0.0.1:6379[2]> sscan Test:Info:Site 0 match '*niver*'
    1) "0"
    2) (empty list or set)    <--- count this

我想返回&#34; 1&#34;

127.0.0.1:6379[2]> sscan Test:Info:Site 0 match '*naver*'
    1) "0"
    2) 1) "www.naver.com"    <--- count this

我想返回&#34; 3&#34;

127.0.0.1:6379[2]> sscan Test:Info:Site 0 match '*com*'
    1) "0"
    2) 1) "www.naver.com"     <-- count
       2) "www.korea.com"     <-- count
       3) "www.google.com"    <-- count 

我无法访问搜索结果的值。

127.0.0.1:6379[2]> EVAL "return #redis.call('sscan',KEYS[1],0,'match',ARGV[1])" 1 'Test:Info:Site' '*com*'
(integer) 2
    127.0.0.1:6379[2]> EVAL "return #redis.call('sscan',KEYS[1],0,'match',ARGV[1])" 1 'Test:Info:Site' '*niver*'
(integer) 2

1 个答案:

答案 0 :(得分:1)

您似乎正在尝试从Lua脚本执行SSCAN,以便对Set的成员进行模式匹配并返回计数。如果是这种情况,您需要重复调​​用SSCAN,直到光标返回到&#39; 0&#39;并计算每次迭代的结果。

以下是如何完成的示例:

$ cat sscan.lua
local key, pat = KEYS[1], ARGV[1]
local cursor, res = 0, 0

repeat
  local rep = redis.call('SSCAN', key, cursor, 'MATCH', pat)
  cursor = rep[1]
  res = res + #rep[2]
until cursor == '0'

return res

$ redis-cli --eval sscan.lua Test:Info:Site , "*niver*"
(integer) 0
$ redis-cli --eval sscan.lua Test:Info:Site , "*naver*"
(integer) 1
$ redis-cli --eval sscan.lua Test:Info:Site , "*com*"
(integer) 3