BloomFilter(s) in Ruby: Native counting filter + Redis counting/non-counting filters
Bloom filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. False positives are possible, but false negatives are not. For more detail, check the wikipedia article. Instead of using k different hash functions, this implementation seeds the CRC32 hash with k different initial values (0, 1, ..., k-1). This may or may not give you a good distribution, it all depends on the data.
Performance of the Bloom filter depends on a number of variables:
MRI/C implementation which creates an in-memory filter which can be saved and reloaded from disk.
bf = BloomFilter::Native.new(:size => 100, :hashes => 2, :seed => 1, :bucket => 3, :raise => false) bf.insert("test") bf.include?("test") # => true bf.include?("blah") # => false
bf.delete("test") bf.include?("test") # => false
Hash with a bloom filter!
bf["test2"] = "bar" bf["test2"] # => true bf["test3"] # => false
=> Number of filter bits (m): 10
=> Number of filter elements (n): 2
=> Number of filter hashes (k) : 2
=> Predicted false positive rate = 10.87%
bf = BloomFilter::Redis.new
bf.insert('test') bf.include?('test') # => true bf.include?('blah') # => false
bf.delete('test') bf.include?('test') # => false
Uses regular Redis get/set counters to implement a counting filter with optional TTL expiry. Because each "bit" requires its own key in Redis, you do incur a much larger memory overhead.
bf = BloomFilter::CountingRedis.new(:ttl => 2)
bf.insert('test') bf.include?('test') # => true
sleep(2) bf.include?('test') # => false
Tatsuya Mori [email protected] (Original C implementation: http://vald.x0.com/sb/)
MIT License - Copyright (c) 2011 Ilya Grigorik