Skip to content

Commit

Permalink
Added (simplified) zinterstore
Browse files Browse the repository at this point in the history
  • Loading branch information
dim committed Dec 1, 2011
1 parent 8e195fd commit 0e95441
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
24 changes: 24 additions & 0 deletions lib/redis/connection/memory.rb
@@ -1,3 +1,4 @@
require 'set'
require 'redis/connection/registry'
require 'redis/connection/command_helper'

Expand Down Expand Up @@ -783,6 +784,29 @@ def zrevrangebyscore(key, max, min, with_scores = nil)
end.flatten.map(&:to_s)
end

def zinterstore(out, _, *keys)
fail_unless_zset(out)

hashes = keys.map do |src|
case @data[src]
when Set
Hash[@data[src].zip([0] * @data[src].size)]
when Hash
@data[src]
else
nil
end
end.compact

@data[out] = ZSet.new
values = hashes.inject([]) {|r, h| r.empty? ? h.keys : r & h.keys }
values.each do |value|
@data[out][value] = hashes.inject(0) {|n, h| n + h[value].to_i }
end

@data[out].size
end

private

def is_a_set?(key)
Expand Down
19 changes: 19 additions & 0 deletions spec/sorted_sets_spec.rb
Expand Up @@ -106,6 +106,25 @@ module FakeRedis
@client.zrevrank("key", "four").should be_nil
end

it "should create untersections between multiple (sorted) sets and store the resulting sorted set in a new key" do
@client.zadd("key1", 1, "one")
@client.zadd("key1", 2, "two")
@client.zadd("key1", 3, "three")
@client.zadd("key2", 5, "two")
@client.zadd("key2", 7, "three")
@client.sadd("key3", 'one')
@client.sadd("key3", 'two')

@client.zinterstore("out", ["key1", "key2"]).should == 2
@client.zrange("out", 0, 100, :with_scores => true).should == ['two', '7', 'three', '10']

@client.zinterstore("out", ["key1", "key3"]).should == 2
@client.zrange("out", 0, 100, :with_scores => true).should == ['one', '1', 'two', '2']

@client.zinterstore("out", ["key1", "key2", "key3"]).should == 1
@client.zrange("out", 0, 100, :with_scores => true).should == ['two', '7']
end

#it "should remove all members in a sorted set within the given indexes"

#it "should remove all members in a sorted set within the given scores"
Expand Down

0 comments on commit 0e95441

Please sign in to comment.