Class: HeavyKeeper::MinHeap

Inherits:
Object
  • Object
show all
Defined in:
lib/heavy_keeper/min_heap.rb

Instance Method Summary collapse

Constructor Details

#initialize(storage = HeavyKeeper.config.storage) ⇒ MinHeap

Returns a new instance of MinHeap.



9
10
11
# File 'lib/heavy_keeper/min_heap.rb', line 9

def initialize(storage = HeavyKeeper.config.storage)
  @storage = storage
end

Instance Method Details

#add(key, item, value, top_k) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/heavy_keeper/min_heap.rb', line 36

def add(key, item, value, top_k)
  count = storage.zcard(sorted_set_key(key))

  storage.multi do
    storage.zadd(sorted_set_key(key), value, item)
    storage.hset(hash_key(key), item, value)
  end

  if count >= top_k
    dropped_item, _ = storage.zpopmin(sorted_set_key(key))
    storage.hdel(hash_key(key), dropped_item)

    if dropped_item != item
      value
    end
  else
    value
  end
end

#clear(key) ⇒ Object



66
67
68
69
# File 'lib/heavy_keeper/min_heap.rb', line 66

def clear(key)
  storage.del(sorted_set_key(key))
  storage.del(hash_key(key))
end

#count(key, item) ⇒ Object



23
24
25
# File 'lib/heavy_keeper/min_heap.rb', line 23

def count(key, item)
  storage.hget(hash_key(key), item).to_i
end

#delete(key, item) ⇒ Object



71
72
73
74
# File 'lib/heavy_keeper/min_heap.rb', line 71

def delete(key, item)
  storage.zrem(sorted_set_key(key), item)
  storage.hdel(hash_key(key), item)
end

#exist?(key, item) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
# File 'lib/heavy_keeper/min_heap.rb', line 32

def exist?(key, item)
  storage.hexists(hash_key(key), item)
end

#list(key, total) ⇒ Object



13
14
15
16
17
18
19
20
21
# File 'lib/heavy_keeper/min_heap.rb', line 13

def list(key, total)
  items = storage.zrevrange(sorted_set_key(key), 0, total - 1)

  if items.empty?
    {}
  else
    storage.mapped_hmget(hash_key(key), *items)
  end
end

#min(key) ⇒ Object



27
28
29
30
# File 'lib/heavy_keeper/min_heap.rb', line 27

def min(key)
  item = storage.zrangebyscore(sorted_set_key(key), - Float::INFINITY, Float::INFINITY, limit: [0, 1]).first
  item ? count(key, item) : 0
end

#update(key, item, value) ⇒ Object



56
57
58
59
60
61
62
63
64
# File 'lib/heavy_keeper/min_heap.rb', line 56

def update(key, item, value)
  storage.multi do
    storage.zrem(sorted_set_key(key), item)
    storage.zincrby(sorted_set_key(key), value, item)
    storage.hset(hash_key(key), item, value)
  end

  value
end