Class: FastExists::Backends::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/fast_exists/backends/redis.rb

Instance Attribute Summary collapse

Attributes inherited from Base

#options

Instance Method Summary collapse

Methods inherited from Base

#load, #rebuild, #save

Constructor Details

#initialize(options = {}) ⇒ Redis

Returns a new instance of Redis.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/fast_exists/backends/redis.rb', line 11

def initialize(options = {})
  super
  @redis = options[:redis] || FastExists.configuration.redis
  @key_prefix = options[:namespace] ? "fast_exists:#{options[:namespace]}" : "fast_exists:default"

  # Bloom filter parameters calculation
  n = @expected_elements
  p = @false_positive_rate
  @bit_size = (-(n * Math.log(p)) / (Math.log(2)**2)).ceil
  @hash_count = [((@bit_size.to_f / n) * Math.log(2)).round, 1].max
  @count_key = "#{@key_prefix}:count"
  @bit_key = "#{@key_prefix}:bits"
end

Instance Attribute Details

#bit_sizeObject (readonly)

Returns the value of attribute bit_size.



9
10
11
# File 'lib/fast_exists/backends/redis.rb', line 9

def bit_size
  @bit_size
end

#hash_countObject (readonly)

Returns the value of attribute hash_count.



9
10
11
# File 'lib/fast_exists/backends/redis.rb', line 9

def hash_count
  @hash_count
end

#key_prefixObject (readonly)

Returns the value of attribute key_prefix.



9
10
11
# File 'lib/fast_exists/backends/redis.rb', line 9

def key_prefix
  @key_prefix
end

Instance Method Details

#add(element) ⇒ Object



25
26
27
28
29
30
31
32
33
34
# File 'lib/fast_exists/backends/redis.rb', line 25

def add(element)
  indexes = hash_indexes(element.to_s)
  execute_redis do |client|
    indexes.each do |idx|
      client.setbit(@bit_key, idx, 1)
    end
    client.incr(@count_key)
  end
  true
end

#capacityObject



58
59
60
# File 'lib/fast_exists/backends/redis.rb', line 58

def capacity
  @expected_elements
end

#clearObject



45
46
47
48
49
50
# File 'lib/fast_exists/backends/redis.rb', line 45

def clear
  execute_redis do |client|
    client.del(@bit_key, @count_key)
  end
  true
end

#contains?(element) ⇒ Boolean

Returns:

  • (Boolean)


36
37
38
39
40
41
42
43
# File 'lib/fast_exists/backends/redis.rb', line 36

def contains?(element)
  indexes = hash_indexes(element.to_s)
  execute_redis do |client|
    indexes.all? do |idx|
      client.getbit(@bit_key, idx) == 1
    end
  end
end

#countObject



52
53
54
55
56
# File 'lib/fast_exists/backends/redis.rb', line 52

def count
  execute_redis do |client|
    (client.get(@count_key) || 0).to_i
  end
end

#statsObject



62
63
64
65
66
67
68
69
70
71
72
# File 'lib/fast_exists/backends/redis.rb', line 62

def stats
  {
    backend: :redis,
    bit_key: @bit_key,
    expected_elements: @expected_elements,
    false_positive_rate: @false_positive_rate,
    inserted_items: count,
    bit_size: @bit_size,
    hash_count: @hash_count
  }
end