Bloom Filter是由Bloom在1970年提出的一種多哈希函數映射的快速查找算法。一般應用在一些須要快速判斷某個元素是否屬於集合,可是並不嚴格要求100%正確的場合。html
一. 實例java
爲了說明Bloom Filter存在的重要意義,舉一個實例:node
假設要你寫一個網絡蜘蛛(web crawler)。因爲網絡間的連接錯綜複雜,蜘蛛在網絡間爬行極可能會造成「環」。爲了不造成「環」,就須要知道蜘蛛已經訪問過那些URL。給一個URL,怎樣知道蜘蛛是否已經訪問過呢?稍微想一想,就會有以下幾種方案:git
1. 將訪問過的URL保存到數據庫。github
2. 用HashSet將訪問過的URL保存起來。那隻需接近O(1)的代價就能夠查到一個URL是否被訪問過了。web
3. URL通過MD5或SHA-1等單向哈希後再保存到HashSet或數據庫。算法
4. Bit-Map方法。創建一個BitSet,將每一個URL通過一個哈希函數映射到某一位。數據庫
方法1~3都是將訪問過的URL完整保存,方法4則只標記URL的一個映射位。express
以上方法在數據量較小的狀況下都能完美解決問題,可是當數據量變得很是龐大時問題就來了。apache
方法1的缺點:數據量變得很是龐大後關係型數據庫查詢的效率會變得很低。並且每來一個URL就啓動一次數據庫查詢是否是過小題大作了?
方法2的缺點:太消耗內存。隨着URL的增多,佔用的內存會愈來愈多。就算只有1億個URL,每一個URL只算50個字符,就須要5GB內存。
方法3:因爲字符串通過MD5處理後的信息摘要長度只有128Bit,SHA-1處理後也只有160Bit,所以方法3比方法2節省了好幾倍的內存。
方法4消耗內存是相對較少的,但缺點是單一哈希函數發生衝突的機率過高。還記得數據結構課上學過的Hash表衝突的各類解決方法麼?若要下降衝突發生的機率到1%,就要將BitSet的長度設置爲URL個數的100倍。
實質上上面的算法都忽略了一個重要的隱含條件:容許小几率的出錯,不必定要100%準確!也就是說少許url實際上沒有沒網絡蜘蛛訪問,而將它們錯判爲已訪問的代價是很小的——大不了少抓幾個網頁唄。
二. Bloom Filter的算法
廢話說到這裏,下面引入本篇的主角——Bloom Filter。其實上面方法4的思想已經很接近Bloom Filter了。方法四的致命缺點是衝突機率高,爲了下降衝突的概念,Bloom Filter使用了多個哈希函數,而不是一個。
Bloom Filter算法以下:
建立一個m位BitSet,先將全部位初始化爲0,而後選擇k個不一樣的哈希函數。第i個哈希函數對字符串str哈希的結果記爲h(i,str),且h(i,str)的範圍是0到m-1 。
(1) 加入字符串過程
下面是每一個字符串處理的過程,首先是將字符串str「記錄」到BitSet中的過程:
對於字符串str,分別計算h(1,str),h(2,str)…… h(k,str)。而後將BitSet的第h(1,str)、h(2,str)…… h(k,str)位設爲1。
圖1.Bloom Filter加入字符串過程
很簡單吧?這樣就將字符串str映射到BitSet中的k個二進制位了。
(2) 檢查字符串是否存在的過程
下面是檢查字符串str是否被BitSet記錄過的過程:
對於字符串str,分別計算h(1,str),h(2,str)…… h(k,str)。而後檢查BitSet的第h(1,str)、h(2,str)…… h(k,str)位是否爲1,若其中任何一位不爲1則能夠斷定str必定沒有被記錄過。若所有位都是1,則「認爲」字符串str存在。
若一個字符串對應的Bit不全爲1,則能夠確定該字符串必定沒有被Bloom Filter記錄過。(這是顯然的,由於字符串被記錄過,其對應的二進制位確定所有被設爲1了)
可是若一個字符串對應的Bit全爲1,其實是不能100%的確定該字符串被Bloom Filter記錄過的。(由於有可能該字符串的全部位都恰好是被其餘字符串所對應)這種將該字符串劃分錯的狀況,稱爲false positive 。
(3) 刪除字符串過程
字符串加入了就被不能刪除了,由於刪除會影響到其餘字符串。實在須要刪除字符串的可使用Counting bloomfilter(CBF),這是一種基本Bloom Filter的變體,CBF將基本Bloom Filter每個Bit改成一個計數器,這樣就能夠實現刪除字符串的功能了。
Bloom Filter跟單哈希函數Bit-Map不一樣之處在於:Bloom Filter使用了k個哈希函數,每一個字符串跟k個bit對應。從而下降了衝突的機率。
三. Bloom Filter參數選擇
(1)哈希函數選擇
哈希函數的選擇對性能的影響應該是很大的,一個好的哈希函數要能近似等機率的將字符串映射到各個Bit。選擇k個不一樣的哈希函數比較麻煩,一種簡單的方法是選擇一個哈希函數,而後送入k個不一樣的參數。
(2)Bit數組大小選擇
哈希函數個數k、位數組大小m、加入的字符串數量n的關係能夠參考參考文獻1。該文獻證實了對於給定的m、n,當 k = ln(2)* m/n 時出錯的機率是最小的。
同時該文獻還給出特定的k,m,n的出錯機率。例如:根據參考文獻1,哈希函數個數k取10,位數組大小m設爲字符串個數n的20倍時,false positive發生的機率是0.0000889 ,這個機率基本能知足網絡爬蟲的需求了。
四. Bloom Filter實現代碼
下面給出一個簡單的Bloom Filter的Java實現代碼:
參考文獻:
[1]Pei Cao. Bloom Filters - the math.
http://pages.cs.wisc.edu/~cao/papers/summary-cache/node8.html
[2]Wikipedia. Bloom filter.
http://en.wikipedia.org/wiki/Bloom_filter
Google Guava的Bloom filter實現
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.hash; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.hash.BloomFilterStrategies.BitArray; import java.io.Serializable; /** * A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test * with one-sided error: if it claims that an element is contained in it, this might be in error, * but if it claims that an element is <i>not</i> contained in it, then this is definitely true. * * <p>If you are unfamiliar with Bloom filters, this nice * <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand * how they work. * * @param <T> the type of instances that the {@code BloomFilter} accepts * @author Kevin Bourrillion * @author Dimitris Andreou * @since 11.0 */ @Beta public final class BloomFilter<T> implements Serializable { /** * A strategy to translate T instances, to {@code numHashFunctions} bit indexes. */ interface Strategy extends java.io.Serializable { /** * Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element. */ <T> void put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); /** * Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element; * returns {@code true} if and only if all selected bits are set. */ <T> boolean mightContain( T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits); } /** The bit set of the BloomFilter (not necessarily power of 2!)*/ private final BitArray bits; /** Number of hashes per element */ private final int numHashFunctions; /** The funnel to translate Ts to bytes */ private final Funnel<T> funnel; /** * The strategy we employ to map an element T to {@code numHashFunctions} bit indexes. */ private final Strategy strategy; /** * Creates a BloomFilter. */ private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel, Strategy strategy) { Preconditions.checkArgument(numHashFunctions > 0, "numHashFunctions zero or negative"); this.bits = checkNotNull(bits); this.numHashFunctions = numHashFunctions; this.funnel = checkNotNull(funnel); this.strategy = strategy; } /** * Returns {@code true} if the element <i>might</i> have been put in this Bloom filter, * {@code false} if this is <i>definitely</i> not the case. */ public boolean mightContain(T object) { return strategy.mightContain(object, funnel, numHashFunctions, bits); } /** * Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of * {@link #mightContain(Object)} with the same element will always return {@code true}. */ public void put(T object) { strategy.put(object, funnel, numHashFunctions, bits); } @VisibleForTesting int getHashCount() { return numHashFunctions; } @VisibleForTesting double computeExpectedFalsePositiveRate(int insertions) { return Math.pow( 1 - Math.exp(-numHashFunctions * ((double) insertions / (bits.size()))), numHashFunctions); } /** * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number * of insertions and expected false positive probability. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements * than specified, will result in its saturation, and a sharp deterioration of its * false positive probability. * * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided * {@code Funnel<T>} is. * * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use * @param expectedInsertions the number of expected insertions to the constructed * {@code BloomFilter<T>}; must be positive * @param falsePositiveProbability the desired false positive probability (must be positive and * less than 1.0) * @return a {@code Builder} */ public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */, double falsePositiveProbability) { checkNotNull(funnel); checkArgument(expectedInsertions > 0, "Expected insertions must be positive"); checkArgument(falsePositiveProbability > 0.0 & falsePositiveProbability < 1.0, "False positive probability in (0.0, 1.0)"); /* * andreou: I wanted to put a warning in the javadoc about tiny fpp values, * since the resulting size is proportional to -log(p), but there is not * much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680 * which is less that 10kb. Who cares! */ int numBits = optimalNumOfBits(expectedInsertions, falsePositiveProbability); int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits); return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel, BloomFilterStrategies.MURMUR128_MITZ_32); } /** * Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number * of insertions, and a default expected false positive probability of 3%. * * <p>Note that overflowing a {@code BloomFilter} with significantly more elements * than specified, will result in its saturation, and a sharp deterioration of its * false positive probability. * * <p>The constructed {@code BloomFilter<T>} will be serializable if the provided * {@code Funnel<T>} is. * * @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use * @param expectedInsertions the number of expected insertions to the constructed * {@code BloomFilter<T>}; must be positive * @return a {@code Builder} */ public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) { return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions } /* * Cheat sheet: * * m: total bits * n: expected insertions * b: m/n, bits per insertion * p: expected false positive probability * * 1) Optimal k = b * ln2 * 2) p = (1 - e ^ (-kn/m))^k * 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b * 4) For optimal k: m = -nlnp / ((ln2) ^ 2) */ private static final double LN2 = Math.log(2); private static final double LN2_SQUARED = LN2 * LN2; /** * Computes the optimal k (number of hashes per element inserted in Bloom filter), given the * expected insertions and total number of bits in the Bloom filter. * * See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula. * * @param n expected insertions (must be positive) * @param m total number of bits in Bloom filter (must be positive) */ @VisibleForTesting static int optimalNumOfHashFunctions(int n, int m) { return Math.max(1, (int) Math.round(m / n * LN2)); } /** * Computes m (total bits of Bloom filter) which is expected to achieve, for the specified * expected insertions, the required false positive probability. * * See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula. * * @param n expected insertions (must be positive) * @param p false positive rate (must be 0 < p < 1) */ @VisibleForTesting static int optimalNumOfBits(int n, double p) { return (int) (-n * Math.log(p) / LN2_SQUARED); } private Object writeReplace() { return new SerialForm<T>(this); } private static class SerialForm<T> implements Serializable { final long[] data; final int numHashFunctions; final Funnel<T> funnel; final Strategy strategy; SerialForm(BloomFilter<T> bf) { this.data = bf.bits.data; this.numHashFunctions = bf.numHashFunctions; this.funnel = bf.funnel; this.strategy = bf.strategy; } Object readResolve() { return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy); } private static final long serialVersionUID = 1; } }
本質是BitSet,適用可容忍必定錯誤的場景,優點是高效、佔用空間小;
3億個KEY,每一個實例映射1W KEY,須要3W個實例,佔用空間約600M。