Grav v1.14.0

BloomFilter

import "std/collections" (included in import "std") · namespace std.collections

A Bloom filter answers "certainly not seen" or "probably seen" for millions of items in a little memory: to skip a database lookup for a name that cannot be taken, or a cache lookup for a key that was never stored.

grav
import "std"

fn main() {
    let seen = new BloomFilter(100000, 0.01)        // 100,000 items, 1% false positives
    print("${seen.byteSize()} bytes, ${seen.hashCount} hashes")
    for (i in 0..100000) { seen.add("user:${i}") }
    print(seen.mightContain("user:42"))              // added: always true
    let wrong = 0
    for (i in 0..10000) { if (seen.mightContain("other:${i}")) { wrong += 1 } }
    print(wrong < 200)                               // about 1 in 100 unseen answer true
    let copy = BloomFilter.fromBytes(seen.toBytes())
    print(copy.mightContain("user:99999"))
}
Output
119814 bytes, 7 hashes
true
true
true
  • Size comes from the items expected and the false positive rate accepted: -n ln p / (ln 2)² bits and (bits / n) ln 2 hashes. A million items at 1% take 1.2 MB.
  • No false negatives: anything added always answers true. Items cannot be removed; clear() forgets everything.
  • add says whether the item was new, approximateCount() how many distinct items were added, and currentFalsePositiveRate() the rate now, from how full it is.
  • Threads may add at once (each bit is set with an atomic OR).
  • toBytes() and BloomFilter.fromBytes(...) keep a filter in a cache, a file or a database column.

API

class BloomFilter

Constructors

  • new BloomFilter(expectedItems: long, falsePositiveRate: double = 0.01) — A filter for about expectedItems with at most falsePositiveRate (0 to 1) of unseen items answering true: m = -n ln p / (ln 2)^2 bits, k = m/n ln 2.

Static members

  • static fn fromBytes(b: Bytes) -> BloomFilter — A filter from toBytes's bytes; ValueError when they are not one.

Fields

  • bitCount: long — The filter's size in bits, and the bits each item sets.
  • hashCount: int

Methods

  • fn add(item: string) -> bool — Adds an item; whether it was new (false when it probably was there).
  • fn addAll(items: Array<string>)
  • fn mightContain(item: string) -> bool — False: certainly never added. True: probably added.
  • fn approximateCount() -> long — About how many distinct items were added.
  • fn currentFalsePositiveRate() -> double — The false positive rate now, from how full the bits are.
  • fn byteSize() -> long — The memory its bits take, in bytes.
  • fn clear() — Forgets everything.
  • fn toBytes() -> Bytes — The filter as bytes (16 bytes of sizes, then its bits): to keep it.

Edit this page on GitHub