我有两个有序集,我想从第一组中分离记录,并通过从第二个有序集中排除记录来存储在新列表/有序集中。
以下是一个例子:
set1:1,2,3,4,5 set2:3,5,7,8,9
输出:1,2,4
编辑:我已经找到了加载脚本并使用eval从nodejs执行脚本的方法。
奇怪的是,当我执行你的脚本时,即使是5-10条记录也需要1秒才能处理,这让我怀疑如果我拥有数千条记录,它的可扩展性有多大。
以下是我的示例nodejs代码:
hsetxx = 'redis.call("ZINTERSTORE","temp",2,"set11","set21","weights",1,0) redis.call("ZUNIONSTORE","result",2,"set11","temp","weights",1,-1) redis.call("ZREMRANGEBYSCORE","result",0,0)';
var redis = require('redis');
var client = redis.createClient('14470', connection);
client.on('connect', function() {
console.log('Connected to Redis');
});
client.script('load',hsetxx,function(err, result) {
console.log(err+'------------'+result);
});
client.zadd('set11', 1,1,1,2,1,3,1,4,1,5);
client.zadd('set21', 1,1,1,5);
client.evalsha(
'39c0da298cab6a6223b4d1e8222cf6d6a84e67b1', //lua source
0,
function(err, result) {
client.zrange('result', 0, -1, function(err, result) {
console.log(err+'------------'+result);
});
}
);
答案 0 :(得分:1)
检查this问题:
你可以做的是先用ZUNIONSTORE创建一个临时集 将相交的分数设置为0.然后执行不包括0的范围, e.g:
127.0.0.1:6379> ZADD all 1 one 2 two 3 three (integer) 3 127.0.0.1:6379> SADD disabled two (integer) 1 127.0.0.1:6379> ZUNIONSTORE tmp 2 all disabled WEIGHTS 1 0 AGGREGATE MIN (integer) 3 127.0.0.1:6379> ZREVRANGEBYSCORE tmp +inf 1 WITHSCORES 1) "three" 2) "3" 3) "one" 4) "1"
答案 1 :(得分:1)
之前的讨论很棒。正如所承诺的那样,另一种应对挑战的方法是Lua和Redis'EVAL
。我不知道它会有多高效,但是这是一个模仿SDIFF
但是对于分类集的一个(不太经过测试的)脚本:
~/src/redis-lua-scripts$ cat zdiff.lua
-- ZDIFF key [key ...]
-- Returns the elements in the first key that are also present in all other keys
local key = table.remove(KEYS,1)
local elems = redis.call('ZRANGE', key, 0, -1)
local reply = {}
if #KEYS > 0 and #elems > 0 then
for i, e in ipairs(elems) do
local exists = true
for j, k in ipairs(KEYS) do
local score = redis.call('ZSCORE', k, e)
if not score then
exists = false
break
end
end
if exists then
reply[#reply+1] = e
end
end
end
return reply
~/src/redis-lua-scripts$ redis-cli SCRIPT LOAD "`cat zdiff.lua`"
"e25d895f05dc638be87d13aed64e8d5780f17c99"
~/src/redis-lua-scripts$ redis-cli ZADD zset1 0 a 0 b 0 c 0 d 0 e
(integer) 5
~/src/redis-lua-scripts$ redis-cli ZADD zset2 0 a
(integer) 1
~/src/redis-lua-scripts$ redis-cli ZADD zset3 0 a 0 b
(integer) 2
~/src/redis-lua-scripts$ redis-cli EVALSHA e25d895f05dc638be87d13aed64e8d5780f17c99 3 zset1 zset2 zset3
1) "a"
答案 2 :(得分:0)
我认为您正在寻找SDIFF:
key1 = {a,b,c,d}
key2 = {c}
key3 = {a,c,e}
SDIFF key1 key2 key3 = {b,d}
https://redis.io/commands/sdiff
但是,排序集没有等价物。