海量數據處理算法—Bloom Filter

Bloom-Filter算法簡介

        Bloom-Filter,即布隆過濾器,1970年由Bloom中提出。它可以用於檢索一個元素是否在一個集合中。

       Bloom Filter(BF)是一種空間效率很高的隨機數據結構,它利用位數組很簡潔地表示一個集合,並能判斷一個元素是否屬於這個集合。它是一個判斷元素是否存在集合的快速的概率算法。Bloom Filter有可能會出現錯誤判斷,但不會漏掉判斷。也就是Bloom Filter判斷元素不再集合,那肯定不在。如果判斷元素存在集合中,有一定的概率判斷錯誤。因此,Bloom Filter不適合那些“零錯誤”的應用場合。而在能容忍低錯誤率的應用場合下,Bloom Filter比其他常見的算法(如hash,折半查找)極大節省了空間。 

      它的優點是空間效率和查詢時間都遠遠超過一般的算法,缺點是有一定的誤識別率和刪除困難。

      Bloom Filter的詳細介紹:Bloom Filter

2、 Bloom-Filter的基本思想

       Bloom-Filter算法的核心思想就是利用多個不同的Hash函數來解決“衝突”。

       計算某元素x是否在一個集合中,首先能想到的方法就是將所有的已知元素保存起來構成一個集合R,然後用元素x跟這些R中的元素一一比較來判斷是否存在於集合R中;我們可以採用鏈表等數據結構來實現。但是,隨着集合R中元素的增加,其佔用的內存將越來越大。試想,如果有幾千萬個不同網頁需要下載,所需的內存將足以佔用掉整個進程的內存地址空間。即使用MD5,UUID這些方法將URL轉成固定的短小的字符串,內存佔用也是相當巨大的。

      於是,我們會想到用Hash table的數據結構,運用一個足夠好的Hash函數將一個URL映射到二進制位數組(位圖數組)中的某一位。如果該位已經被置爲1,那麼表示該URL已經存在。

      Hash存在一個衝突(碰撞)的問題,用同一個Hash得到的兩個URL的值有可能相同。爲了減少衝突,我們可以多引入幾個Hash,如果通過其中的一個Hash值我們得出某元素不在集合中,那麼該元素肯定不在集合中。只有在所有的Hash函數告訴我們該元素在集合中時,才能確定該元素存在於集合中。這便是Bloom-Filter的基本思想。


原理要點:一是位數組, 而是k個獨立hash函數。

1)位數組:

        假設Bloom Filter使用一個m比特的數組來保存信息,初始狀態時,Bloom Filter是一個包含m位的位數組,每一位都置爲0,即BF整個數組的元素都設置爲0。


2)添加元素,k個獨立hash函數

       爲了表達S={x1, x2,…,xn}這樣一個n個元素的集合,Bloom Filter使用k個相互獨立的哈希函數(Hash Function),它們分別將集合中的每個元素映射到{1,…,m}的範圍中。

         當我們往Bloom Filter中增加任意一個元素x時候,我們使用k個哈希函數得到k個哈希值,然後將數組中對應的比特位設置爲1。即第i個哈希函數映射的位置hashi(x)就會被置爲1(1≤i≤k)。

 注意,如果一個位置多次被置爲1,那麼只有第一次會起作用,後面幾次將沒有任何效果。在下圖中,k=3,且有兩個哈希函數選中同一個位置(從左邊數第五位,即第二個“1“處)。   


 3)判斷元素是否存在集合

    在判斷y是否屬於這個集合時,我們只需要對y使用k個哈希函數得到k個哈希值,如果所有hashi(y)的位置都是11ik),即k個位置都被設置爲1了,那麼我們就認爲y是集合中的元素,否則就認爲y不是集合中的元素。下圖中y1就不是集合中的元素(因爲y1有一處指向了“0”位)。y2或者屬於這個集合,或者剛好是一個false positive



      顯然這 個判斷並不保證查找的結果是100%正確的。

Bloom Filter的缺點:

       1)Bloom Filter無法從Bloom Filter集合中刪除一個元素因爲該元素對應的位會牽動到其他的元素。所以一個簡單的改進就是 counting Bloom filter,用一個counter數組代替位數組,就可以支持刪除了。 此外,Bloom Filter的hash函數選擇會影響算法的效果。

       2)還有一個比較重要的問題,如何根據輸入元素個數n,確定位數組m的大小及hash函數個數hash函數選擇會影響算法的效果當hash函數個數k=(ln2)*(m/n)時錯誤率最小。在錯誤率不大於E的情況 下,m至少要等於n*lg(1/E) 才能表示任意n個元素的集合。但m還應該更大些,因爲還要保證bit數組裏至少一半爲0,則m應 該>=nlg(1/E)*lge ,大概就是nlg(1/E)1.44(lg表示以2爲底的對數)。 

舉個例子我們假設錯誤率爲0.01,則此時m應大概是n的13倍。這樣k大概是8個。 

 注意:

         這裏m與n的單位不同,m是bit爲單位,而n則是以元素個數爲單位(準確的說是不同元素的個數)。通常單個元素的長度都是有很多bit的。所以使用bloom filter內存上通常都是節省的。 

       一般BF可以與一些key-value的數據庫一起使用,來加快查詢。由於BF所用的空間非常小,所有BF可以常駐內存。這樣子的話,對於大部分不存在的元素,我們只需要訪問內存中的BF就可以判斷出來了,只有一小部分,我們需要訪問在硬盤上的key-value數據庫。從而大大地提高了效率。


一個Bloom Filter有以下參數:


m bit數組的寬度(bit數)
n 加入其中的key的數量
k 使用的hash函數的個數
f False Positive的比率

Bloom Filter的f滿足下列公式:


在給定m和n時,能夠使f最小化的k值爲:

此時給出的f爲:

根據以上公式,對於任意給定的f,我們有:


n = m ln(0.6185) / ln(f)    [1]

同時,我們需要k個hash來達成這個目標:

k = - ln(f) / ln(2)             [2]

由於k必須取整數,我們在Bloom Filter的程序實現中,還應該使用上面的公式來求得實際的f:

f = (1 – e-kn/m)k             [3]

以上3個公式是程序實現Bloom Filter的關鍵公式。

3、 擴展 CounterBloom Filter

CounterBloom Filter

BloomFilter有個缺點,就是不支持刪除操作,因爲它不知道某一個位從屬於哪些向量。那我們可以給Bloom Filter加上計數器,添加時增加計數器,刪除時減少計數器。

但這樣的Filter需要考慮附加的計數器大小,假如同個元素多次插入的話,計數器位數較少的情況下,就會出現溢出問題。如果對計數器設置上限值的話,會導致Cache Miss,但對某些應用來說,這並不是什麼問題,如Web Sharing。

Compressed Bloom Filter

爲了能在服務器之間更快地通過網絡傳輸Bloom Filter,我們有方法能在已完成Bloom Filter之後,得到一些實際參數的情況下進行壓縮。

將元素全部添加入Bloom Filter後,我們能得到真實的空間使用率,用這個值代入公式計算出一個比m小的值,重新構造Bloom Filter,對原先的哈希值進行求餘處理,在誤判率不變的情況下,使得其內存大小更合適。


4、 Bloom-Filter的應用

        Bloom-Filter一般用於在大數據量的集合中判定某元素是否存在。例如郵件服務器中的垃圾郵件過濾器。在搜索引擎領域,Bloom-Filter最常用於網絡蜘蛛(Spider)的URL過濾,網絡蜘蛛通常有一個URL列表,保存着將要下載和已經下載的網頁的URL,網絡蜘蛛下載了一個網頁,從網頁中提取到新的URL後,需要判斷該URL是否已經存在於列表中。此時,Bloom-Filter算法是最好的選擇。

1.key-value 加快查詢

       一般Bloom-Filter可以與一些key-value的數據庫一起使用,來加快查詢。

       一般key-value存儲系統的values存在硬盤,查詢就是件費時的事。Storage的數據都插入Filter,在Filter中查詢都不存在時,那就不需要去Storage查詢了。False Position出現時,只是會導致一次多餘的Storage查詢。

       由於Bloom-Filter所用的空間非常小,所有BF可以常駐內存。這樣子的話,對於大部分不存在的元素,我們只需要訪問內存中的Bloom-Filter就可以判斷出來了,只有一小部分,我們需要訪問在硬盤上的key-value數據庫。從而大大地提高了效率。如圖:

          


2 .GoogleBigTable

        Google的BigTable也使用了Bloom Filter,以減少不存在的行或列在磁盤上的查詢,大大提高了數據庫的查詢操作的性能。

3. Proxy-Cache

      在Internet Cache Protocol中的Proxy-Cache很多都是使用Bloom Filter存儲URLs,除了高效的查詢外,還能很方便得傳輸交換Cache信息。

4.網絡應用

      1)P2P網絡中查找資源操作,可以對每條網絡通路保存Bloom Filter,當命中時,則選擇該通路訪問。

      2)廣播消息時,可以檢測某個IP是否已發包。

      3)檢測廣播消息包的環路,將Bloom Filter保存在包裏,每個節點將自己添加入Bloom Filter。

     4)信息隊列管理,使用Counter Bloom Filter管理信息流量。

5. 垃圾郵件地址過濾

        像網易,QQ這樣的公衆電子郵件(email)提供商,總是需要過濾來自發送垃圾郵件的人(spamer)的垃圾郵件。

一個辦法就是記錄下那些發垃圾郵件的 email地址。由於那些發送者不停地在註冊新的地址,全世界少說也有幾十億個發垃圾郵件的地址,將他們都存起來則需要大量的網絡服務器。

如果用哈希表,每存儲一億個 email地址,就需要 1.6GB的內存(用哈希表實現的具體辦法是將每一個 email地址對應成一個八字節的信息指紋,然後將這些信息指紋存入哈希表,由於哈希表的存儲效率一般只有 50%,因此一個email地址需要佔用十六個字節。一億個地址大約要 1.6GB,即十六億字節的內存)。因此存貯幾十億個郵件地址可能需要上百 GB的內存。

而Bloom Filter只需要哈希表 1/8到 1/4 的大小就能解決同樣的問題。

BloomFilter決不會漏掉任何一個在黑名單中的可疑地址。而至於誤判問題,常見的補救辦法是在建立一個小的白名單,存儲那些可能別誤判的郵件地址。



5、 Bloom-Filter的具體實現

c語言實現:

stdafx.h:

  1. #pragma once  
  2. #include <stdio.h>    
  3. #include "stdlib.h"  
  4. #include <iostream>  
  5. #include <time.h>  
  6. using namespace std;  
  1. #include "stdafx.h"  
  2.   
  3.   
  4. #define ARRAY_SIZE 256 /*we get the 256 chars of each line*/  
  5. #define SIZE 48000000 /* size should be 1/8 of max*/  
  6. #define MAX  384000000/*the max bit space*/  
  7.   
  8. #define SETBIT(ch,n) ch[n/8]|=1<<(7-n%8)  
  9. #define GETBIT(ch,n) (ch[n/8]&1<<(7-n%8))>>(7-n%8)  
  10.   
  11. unsigned int len(char *ch);/* functions to calculate the length of the url*/  
  12.   
  13. unsigned int RSHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  14. unsigned int JSHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  15. unsigned int PJWHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  16. unsigned int ELFHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  17. unsigned int BKDRHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  18. unsigned int SDBMHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  19. unsigned int DJBHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  20. unsigned int DEKHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  21. unsigned int BPHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  22. unsigned int FNVHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  23. unsigned int APHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
  24. unsigned int HFLPHash(char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
  25. unsigned int HFHash(char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
  26. unsigned int StrHash( char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
  27. unsigned int TianlHash(char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
  28.   
  29.   
  30. int main()  
  31. {  
  32.     int i,num,num2=0; /* the number to record the repeated urls and the total of it*/  
  33.     unsigned int tt=0;  
  34.     int flag;         /*it helps to check weather the url has already existed */  
  35.     char buf[257];    /*it helps to print the start time of the program */  
  36.     time_t tmp = time(NULL);  
  37.   
  38.     char file1[100],file2[100];  
  39.     FILE *fp1,*fp2;/*pointer to the file */  
  40.     char ch[ARRAY_SIZE];    
  41.     char *vector ;/* the bit space*/  
  42.     vector = (char *)calloc(SIZE,sizeof(char));  
  43.   
  44.     printf("Please enter the file with repeated urls:\n");  
  45.     scanf("%s",&file1);     
  46.     if( (fp1 = fopen(file1,"rb")) == NULL) {  /* open the goal file*/  
  47.       printf("Connot open the file %s!\n",file1);  
  48.     }  
  49.   
  50.     printf("Please enter the file you want to save to:\n");  
  51.     scanf("%s",&file2);  
  52.     if( (fp2 = fopen(file2,"w")) == NULL) {  
  53.         printf("Connot open the file %s\n",file2);  
  54.     }  
  55.     strftime(buf,32,"%Y-%m-%d %H:%M:%S",localtime(&tmp));  
  56.     printf("%s\n",buf); /*print the system time*/  
  57.   
  58.     for(i=0;i<SIZE;i++) {  
  59.         vector[i]=0;  /*set 0*/  
  60.     }  
  61.   
  62.     while(!feof(fp1)) { /* the check process*/  
  63.       
  64.         fgets(ch,ARRAY_SIZE,fp1);  
  65.         flag=0;  
  66.         tt++;  
  67.         if( GETBIT(vector, HFLPHash(ch,len(ch))%MAX) ) {      
  68.             flag++;  
  69.         } else {  
  70.             SETBIT(vector,HFLPHash(ch,len(ch))%MAX );  
  71.         }     
  72.   
  73.         if( GETBIT(vector, StrHash(ch,len(ch))%MAX) ) {   
  74.             flag++;  
  75.         } else {  
  76.             SETBIT(vector,StrHash(ch,len(ch))%MAX );  
  77.         }  
  78.           
  79.         if( GETBIT(vector, HFHash(ch,len(ch))%MAX) )   {  
  80.             flag++;  
  81.         } else {  
  82.             SETBIT(vector,HFHash(ch,len(ch))%MAX );  
  83.         }  
  84.   
  85.         if( GETBIT(vector, DEKHash(ch,len(ch))%MAX) ) {  
  86.             flag++;  
  87.         } else {  
  88.             SETBIT(vector,DEKHash(ch,len(ch))%MAX );  
  89.         }   
  90.           
  91.         if( GETBIT(vector, TianlHash(ch,len(ch))%MAX) ) {  
  92.             flag++;  
  93.         } else {  
  94.             SETBIT(vector,TianlHash(ch,len(ch))%MAX );  
  95.         }  
  96.   
  97.         if( GETBIT(vector, SDBMHash(ch,len(ch))%MAX) )  {  
  98.             flag++;  
  99.         } else {  
  100.             SETBIT(vector,SDBMHash(ch,len(ch))%MAX );  
  101.         }  
  102.   
  103.         if(flag<6)  
  104.             num2++;       
  105.         else              
  106.            fputs(ch,fp2);  
  107.       
  108.         /*  printf(" %d",flag); */        
  109.     }  
  110.     /* the result*/  
  111.     printf("\nThere are %d urls!\n",tt);  
  112.     printf("\nThere are %d not repeated urls!\n",num2);  
  113.     printf("There are %d repeated urls!\n",tt-num2);  
  114.     fclose(fp1);  
  115.     fclose(fp2);  
  116.     return 0;  
  117. }  
  118.   
  119.   
  120. /*functions may be used in the main */  
  121. unsigned int len(char *ch)  
  122. {  
  123.     int m=0;  
  124.     while(ch[m]!='\0') {  
  125.         m++;  
  126.     }  
  127.     return m;  
  128. }  
  129.   
  130. unsigned int RSHash(char* str, unsigned int len) {  
  131.    unsigned int b = 378551;  
  132.    unsigned int a = 63689;  
  133.    unsigned int hash = 0;  
  134.    unsigned int i = 0;  
  135.   
  136.    for(i=0; i<len; str++, i++) {  
  137.       hash = hash*a + (*str);  
  138.       a = a*b;  
  139.    }  
  140.    return hash;  
  141. }  
  142. /* End Of RS Hash Function */  
  143.   
  144.   
  145. unsigned int JSHash(char* str, unsigned int len)  
  146. {  
  147.    unsigned int hash = 1315423911;  
  148.    unsigned int i    = 0;  
  149.   
  150.    for(i=0; i<len; str++, i++) {  
  151.       hash ^= ((hash<<5) + (*str) + (hash>>2));  
  152.    }  
  153.    return hash;  
  154. }  
  155. /* End Of JS Hash Function */  
  156.   
  157.   
  158. unsigned int PJWHash(char* str, unsigned int len)  
  159. {  
  160.    const unsigned int BitsInUnsignedInt = (unsigned int)(sizeof(unsigned int) * 8);  
  161.    const unsigned int ThreeQuarters = (unsigned int)((BitsInUnsignedInt  * 3) / 4);  
  162.    const unsigned int OneEighth = (unsigned int)(BitsInUnsignedInt / 8);  
  163.    const unsigned int HighBits = (unsigned int)(0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth);  
  164.    unsigned int hash = 0;  
  165.    unsigned int test = 0;  
  166.    unsigned int i = 0;  
  167.   
  168.    for(i=0;i<len; str++, i++) {  
  169.       hash = (hash<<OneEighth) + (*str);  
  170.       if((test = hash & HighBits)  != 0) {  
  171.          hash = ((hash ^(test >> ThreeQuarters)) & (~HighBits));  
  172.       }  
  173.    }  
  174.   
  175.    return hash;  
  176. }  
  177. /* End Of  P. J. Weinberger Hash Function */  
  178.   
  179.   
  180. unsigned int ELFHash(char* str, unsigned int len)  
  181. {  
  182.    unsigned int hash = 0;  
  183.    unsigned int x    = 0;  
  184.    unsigned int i    = 0;  
  185.   
  186.    for(i = 0; i < len; str++, i++) {  
  187.       hash = (hash << 4) + (*str);  
  188.       if((x = hash & 0xF0000000L) != 0) {  
  189.          hash ^= (x >> 24);  
  190.       }  
  191.       hash &= ~x;  
  192.    }  
  193.    return hash;  
  194. }  
  195. /* End Of ELF Hash Function */  
  196.   
  197.   
  198. unsigned int BKDRHash(char* str, unsigned int len)  
  199. {  
  200.    unsigned int seed = 131; /* 31 131 1313 13131 131313 etc.. */  
  201.    unsigned int hash = 0;  
  202.    unsigned int i    = 0;  
  203.   
  204.    for(i = 0; i < len; str++, i++)  
  205.    {  
  206.       hash = (hash * seed) + (*str);  
  207.    }  
  208.   
  209.    return hash;  
  210. }  
  211. /* End Of BKDR Hash Function */  
  212.   
  213.   
  214. unsigned int SDBMHash(char* str, unsigned int len)  
  215. {  
  216.    unsigned int hash = 0;  
  217.    unsigned int i    = 0;  
  218.   
  219.    for(i = 0; i < len; str++, i++) {  
  220.       hash = (*str) + (hash << 6) + (hash << 16) - hash;  
  221.    }  
  222.   
  223.    return hash;  
  224. }  
  225. /* End Of SDBM Hash Function */  
  226.   
  227.   
  228. unsigned int DJBHash(char* str, unsigned int len)  
  229. {  
  230.    unsigned int hash = 5381;  
  231.    unsigned int i    = 0;  
  232.   
  233.    for(i = 0; i < len; str++, i++) {  
  234.       hash = ((hash << 5) + hash) + (*str);  
  235.    }  
  236.   
  237.    return hash;  
  238. }  
  239. /* End Of DJB Hash Function */  
  240.   
  241.   
  242. unsigned int DEKHash(char* str, unsigned int len)  
  243. {  
  244.    unsigned int hash = len;  
  245.    unsigned int i    = 0;  
  246.   
  247.    for(i = 0; i < len; str++, i++) {  
  248.       hash = ((hash << 5) ^ (hash >> 27)) ^ (*str);  
  249.    }  
  250.    return hash;  
  251. }  
  252. /* End Of DEK Hash Function */  
  253.   
  254.   
  255. unsigned int BPHash(char* str, unsigned int len)  
  256. {  
  257.    unsigned int hash = 0;  
  258.    unsigned int i    = 0;  
  259.    for(i = 0; i < len; str++, i++) {  
  260.       hash = hash << 7 ^ (*str);  
  261.    }  
  262.   
  263.    return hash;  
  264. }  
  265. /* End Of BP Hash Function */  
  266.   
  267.   
  268. unsigned int FNVHash(char* str, unsigned int len)  
  269. {  
  270.    const unsigned int fnv_prime = 0x811C9DC5;  
  271.    unsigned int hash      = 0;  
  272.    unsigned int i         = 0;  
  273.   
  274.    for(i = 0; i < len; str++, i++) {  
  275.       hash *= fnv_prime;  
  276.       hash ^= (*str);  
  277.    }  
  278.   
  279.    return hash;  
  280. }  
  281. /* End Of FNV Hash Function */  
  282.   
  283.   
  284. unsigned int APHash(char* str, unsigned int len)  
  285. {  
  286.    unsigned int hash = 0xAAAAAAAA;  
  287.    unsigned int i    = 0;  
  288.   
  289.    for(i = 0; i < len; str++, i++) {  
  290.       hash ^= ((i & 1) == 0) ? (  (hash <<  7) ^ (*str) * (hash >> 3)) :  
  291.                                (~((hash << 11) + (*str) ^ (hash >> 5)));  
  292.    }  
  293.   
  294.    return hash;  
  295. }  
  296. /* End Of AP Hash Function */  
  297. unsigned int HFLPHash(char *str,unsigned int len)  
  298. {  
  299.    unsigned int n=0;  
  300.    int i;  
  301.    char* b=(char *)&n;  
  302.    for(i=0;i<strlen(str);++i) {  
  303.      b[i%4]^=str[i];  
  304.     }  
  305.     return n%len;  
  306. }  
  307. /* End Of HFLP Hash Function*/  
  308. unsigned int HFHash(char* str,unsigned int len)  
  309. {  
  310.    int result=0;  
  311.    char* ptr=str;  
  312.    int c;  
  313.    int i=0;  
  314.    for (i=1;c=*ptr++;i++)  
  315.    result += c*3*i;  
  316.    if (result<0)  
  317.       result = -result;  
  318.    return result%len;  
  319. }  
  320. /*End Of HKHash Function */  
  321.   
  322.  unsigned int StrHash( char *str,unsigned int len)  
  323.  {  
  324.     register unsigned int   h;  
  325.     register unsigned char *p;  
  326.      for(h=0,p=(unsigned char *)str;*p;p++) {  
  327.          h=31*h+*p;  
  328.      }  
  329.   
  330.       return h;  
  331.   
  332.   }  
  333.  /*End Of StrHash Function*/  
  334.   
  335. unsigned int TianlHash(char *str,unsigned int len)  
  336. {  
  337.    unsigned long urlHashValue=0;  
  338.    int ilength=strlen(str);  
  339.    int i;  
  340.    unsigned char ucChar;  
  341.    if(!ilength)  {  
  342.        return 0;  
  343.    }  
  344.    if(ilength<=256)  {  
  345.       urlHashValue=16777216*(ilength-1);  
  346.   } else {   
  347.       urlHashValue = 42781900080;  
  348.   }  
  349.   if(ilength<=96) {  
  350.       for(i=1;i<=ilength;i++) {  
  351.           ucChar=str[i-1];  
  352.           if(ucChar<='Z'&&ucChar>='A')  {  
  353.               ucChar=ucChar+32;  
  354.           }  
  355.           urlHashValue+=(3*i*ucChar*ucChar+5*i*ucChar+7*i+11*ucChar)%1677216;  
  356.       }  
  357.   } else  {  
  358.       for(i=1;i<=96;i++)  
  359.       {  
  360.           ucChar=str[i+ilength-96-1];  
  361.           if(ucChar<='Z'&&ucChar>='A')  
  362.           {  
  363.               ucChar=ucChar+32;  
  364.           }  
  365.           urlHashValue+=(3*i*ucChar*ucChar+5*i*ucChar+7*i+11*ucChar)%1677216;  
  366.       }  
  367.   }  
  368.   return urlHashValue;  
  369.   
  370.  }  
  371. /*End Of Tianl Hash Function*/  


網上找到的php簡單實現:

  1. <?php  
  2.   
  3. /** 
  4.  * Implements a Bloom Filter 
  5.  */  
  6. class BloomFilter {  
  7.     /** 
  8.      * Size of the bit array 
  9.      * 
  10.      * @var int 
  11.      */  
  12.     protected $m;  
  13.   
  14.     /** 
  15.      * Number of hash functions 
  16.      * 
  17.      * @var int 
  18.      */  
  19.     protected $k;  
  20.   
  21.     /** 
  22.      * Number of elements in the filter 
  23.      * 
  24.      * @var int 
  25.      */  
  26.     protected $n;  
  27.   
  28.     /** 
  29.      * The bitset holding the filter information 
  30.      * 
  31.      * @var array 
  32.      */  
  33.     protected $bitset;  
  34.   
  35.     /** 
  36.      * 計算最優的hash函數個數:當hash函數個數k=(ln2)*(m/n)時錯誤率最小 
  37.      * 
  38.      * @param int $m bit數組的寬度(bit數) 
  39.      * @param int $n 加入布隆過濾器的key的數量 
  40.      * @return int 
  41.      */  
  42.     public static function getHashCount($m, $n) {  
  43.         return ceil(($m / $n) * log(2));  
  44.     }  
  45.   
  46.     /** 
  47.      * Construct an instance of the Bloom filter 
  48.      * 
  49.      * @param int $m bit數組的寬度(bit數) Size of the bit array 
  50.      * @param int $k hash函數的個數 Number of different hash functions to use 
  51.      */  
  52.     public function __construct($m, $k) {  
  53.         $this->m = $m;  
  54.         $this->k = $k;  
  55.         $this->n = 0;  
  56.   
  57.         /* Initialize the bit set */  
  58.         $this->bitset = array_fill(0, $this->m - 1, false);  
  59.     }  
  60.   
  61.     /** 
  62.      * False Positive的比率:f = (1 – e-kn/m)k    
  63.      * Returns the probability for a false positive to occur, given the current number of items in the filter 
  64.      * 
  65.      * @return double 
  66.      */  
  67.     public function getFalsePositiveProbability() {  
  68.         $exp = (-1 * $this->k * $this->n) / $this->m;  
  69.   
  70.         return pow(1 - exp($exp),  $this->k);  
  71.     }  
  72.   
  73.     /** 
  74.      * Adds a new item to the filter 
  75.      * 
  76.      * @param mixed Either a string holding a single item or an array of  
  77.      *              string holding multiple items.  In the latter case, all 
  78.      *              items are added one by one internally. 
  79.      */  
  80.     public function add($key) {  
  81.         if (is_array($key)) {  
  82.             foreach ($key as $k) {  
  83.                 $this->add($k);  
  84.             }  
  85.             return;  
  86.         }  
  87.   
  88.         $this->n++;  
  89.   
  90.         foreach ($this->getSlots($key) as $slot) {  
  91.             $this->bitset[$slot] = true;  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      * Queries the Bloom filter for an element 
  97.      * 
  98.      * If this method return FALSE, it is 100% certain that the element has 
  99.      * not been added to the filter before.  In contrast, if TRUE is returned, 
  100.      * the element *may* have been added to the filter previously.  However with 
  101.      * a probability indicated by getFalsePositiveProbability() the element has 
  102.      * not been added to the filter with contains() still returning TRUE. 
  103.      * 
  104.      * @param mixed Either a string holding a single item or an array of  
  105.      *              strings holding multiple items.  In the latter case the 
  106.      *              method returns TRUE if the filter contains all items. 
  107.      * @return boolean 
  108.      */  
  109.     public function contains($key) {  
  110.         if (is_array($key)) {  
  111.             foreach ($key as $k) {  
  112.                 if ($this->contains($k) == false) {  
  113.                     return false;  
  114.                 }  
  115.             }  
  116.   
  117.             return true;  
  118.         }  
  119.   
  120.         foreach ($this->getSlots($key) as $slot) {  
  121.             if ($this->bitset[$slot] == false) {  
  122.                 return false;  
  123.             }  
  124.         }  
  125.   
  126.         return true;  
  127.     }  
  128.   
  129.     /** 
  130.      * Hashes the argument to a number of positions in the bit set and returns the positions 
  131.      * 
  132.      * @param string Item 
  133.      * @return array Positions 
  134.      */  
  135.     protected function getSlots($key) {  
  136.         $slots = array();  
  137.         $hash = self::getHashCode($key);  
  138.         mt_srand($hash);  
  139.   
  140.         for ($i = 0; $i < $this->k; $i++) {  
  141.             $slots[] = mt_rand(0, $this->m - 1);  
  142.         }  
  143.   
  144.         return $slots;  
  145.     }  
  146.   
  147.     /** 
  148.      * 使用CRC32產生一個32bit(位)的校驗值。 
  149.      * 由於CRC32產生校驗值時源數據塊的每一bit(位)都會被計算,所以數據塊中即使只有一位發生了變化,也會得到不同的CRC32值。 
  150.      * Generates a numeric hash for the given string 
  151.      * 
  152.      * Right now the CRC-32 algorithm is used.  Alternatively one could e.g. 
  153.      * use Adler digests or mimick the behaviour of Java's hashCode() method. 
  154.      * 
  155.      * @param string Input for which the hash should be created 
  156.      * @return int Numeric hash 
  157.      */  
  158.     protected static function getHashCode($string) {  
  159.         return crc32($string);  
  160.     }  
  161.       
  162. }  
  163.   
  164.   
  165.   
  166. $items = array("first item""second item""third item");  
  167.           
  168. /* Add all items with one call to add() and make sure contains() finds 
  169.  * them all. 
  170.  */  
  171. $filter = new BloomFilter(100, BloomFilter::getHashCount(100, 3));  
  172. $filter->add($items);  
  173.   
  174. //var_dump($filter); exit;  
  175. $items = array("firsttem""seconditem""thirditem");  
  176. foreach ($items as $item) {  
  177.  var_dump(($filter->contains($item)));  
  178. }  
  179.   
  180.   
  181. /* Add all items with multiple calls to add() and make sure contains() 
  182. * finds them all. 
  183. */  
  184. $filter = new BloomFilter(100, BloomFilter::getHashCount(100, 3));  
  185. foreach ($items as $item) {  
  186.     $filter->add($item);  
  187. }  
  188. $items = array("fir sttem""secondit em""thir ditem");  
  189. foreach ($items as $item) {  
  190.  var_dump(($filter->contains($item)));  
  191. }  
  192.   
  193.   java版本的實現:
    import java.util.BitSet;

    public class bloomFilter {

    private int defaultSize = 5000 << 10000;
    private int basic = defaultSize -1;
    private String key = null;
    private BitSet bits = new BitSet(defaultSize);

    public bloomFilter(String key){
    this.key = key;
    }

    private int[] lrandom(){
    int[] randomsum = new int[8];
    int random1 = hashCode(key,1);
    int random2 = hashCode(key,2);
    int random3 = hashCode(key,3);
    int random4 = hashCode(key,4);
    int random5 = hashCode(key,5);
    int random6 = hashCode(key,6);
    int random7 = hashCode(key,7);
    int random8 = hashCode(key,8);
    randomsum[
    0] = random1;
    randomsum[
    1] = random2;
    randomsum[
    2] = random3;
    randomsum[
    3] = random4;
    randomsum[
    4] = random5;
    randomsum[
    5] = random6;
    randomsum[
    6] = random7;
    randomsum[
    7] = random8;
    return randomsum;
    }

    private int[] sameLrandom(){
    int[] randomsum = new int[8];
    int random1 = hashCode(key,1);
    int random2 = hashCode(key,1);
    int random3 = hashCode(key,1);
    int random4 = hashCode(key,1);
    int random5 = hashCode(key,1);
    int random6 = hashCode(key,1);
    int random7 = hashCode(key,1);
    int random8 = hashCode(key,1);
    randomsum[
    0] = random1;
    randomsum[
    1] = random2;
    randomsum[
    2] = random3;
    randomsum[
    3] = random4;
    randomsum[
    4] = random5;
    randomsum[
    5] = random6;
    randomsum[
    6] = random7;
    randomsum[
    7] = random8;
    return randomsum;
    }

    private void add(){
    if(exist()){
    System.out.println(
    "已經包含("+key+")");
    return;
    }
    int keyCode[] = lrandom();
    bits.set(keyCode[
    0]);
    bits.set(keyCode[
    1]);
    bits.set(keyCode[
    2]);
    bits.set(keyCode[
    3]);
    bits.set(keyCode[
    4]);
    bits.set(keyCode[
    5]);
    bits.set(keyCode[
    6]);
    bits.set(keyCode[
    7]);
    }

    private boolean exist(){
    int keyCode[] = lrandom();
    if(bits.get(keyCode[0])&&
    bits.get(keyCode[
    1])
    &&bits.get(keyCode[2])
    &&bits.get(keyCode[3])
    &&bits.get(keyCode[4])
    &&bits.get(keyCode[5])
    &&bits.get(keyCode[6])
    &&bits.get(keyCode[7])){
    return true;
    }
    return false;
    }

    private boolean set0(){
    if(exist()){
    int keyCode[] = lrandom();
    bits.clear(keyCode[
    0]);
    bits.clear(keyCode[
    1]);
    bits.clear(keyCode[
    2]);
    bits.clear(keyCode[
    3]);
    bits.clear(keyCode[
    4]);
    bits.clear(keyCode[
    5]);
    bits.clear(keyCode[
    6]);
    bits.clear(keyCode[
    7]);
    return true;
    }
    return false;
    }

    private int hashCode(String key,int Q){
    int h = 0;
    int off = 0;
    char val[] = key.toCharArray();
    int len = key.length();
    for (int i = 0; i < len; i++) {
    h
    = (30 + Q) * h + val[off++];
    }
    return changeInteger(h);
    }

    private int changeInteger(int h) {
    return basic & h;
    }

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    bloomFilter f = new bloomFilter("http://www.agrilink.cn/");

    System.out.println(f.defaultSize);
    f.add();
    System.out.println(f.exist());
    f.set0();
    System.out.println(f.exist());
    }

    }
    複製代碼

      2. 還有一個java 版的 ,也是 使用 bitset

       

    複製代碼
    import java.util.BitSet;
    public class SimpleBloomFilter {
    private static final int DEFAULT_SIZE =2 << 24 ;
    private static final int [] seeds =new int []{5,7, 11 , 13 , 31 , 37 , 61};
    private BitSet bits= new BitSet(DEFAULT_SIZE);
    private SimpleHash[] func=new SimpleHash[seeds.length];



    public SimpleBloomFilter() {
    for( int i= 0 ; i< seeds.length; i ++ ) {
    func[i]
    =new SimpleHash(DEFAULT_SIZE, seeds[i]);
    }
    }
    public void add(String value) {
    for(SimpleHash f : func) {
    bits.set(f.hash(value),
    true );
    }
    }
    public boolean contains(String value) {
    if(value ==null ) {
    return false ;
    }
    boolean ret = true ;
    for(SimpleHash f : func) {
    ret
    =ret&& bits.get(f.hash(value));
    }
    return ret;
    }

    //內部類,simpleHash
    public static class SimpleHash {
    private int cap;
    private int seed;
    public SimpleHash( int cap, int seed) {
    this.cap= cap;
    this.seed =seed;
    }
    public int hash(String value) {
    int result=0 ;
    int len= value.length();
    for (int i= 0 ; i< len; i ++ ) {
    result
    =seed* result + value.charAt(i);
    }
    return (cap - 1 ) & result;
    }
    }







    public static void main(String[] args) {
    String value
    = "[email protected]" ;
    SimpleBloomFilter filter
    =new SimpleBloomFilter();
    System.out.println(filter.contains(value));
    filter.add(value);
    System.out.println(filter.contains(value));
    }




    }
  194.       
  195.     


問題實例】 給你A,B兩個文件,各存放50億條URL,每條URL佔用64字節,內存限制是4G,讓你找出A,B文件共同的URL。如果是三個乃至n個文件呢? 

根據這個問題我們來計算下內存的佔用,4G=2^32大概是40億*8大概是340億bit,n=50億,如果按出錯率0.01算需要的大概是650億個bit。 現在可用的是340億,相差並不多,這樣可能會使出錯率上升些。另外如果這些urlip是一一對應的,就可以轉換成ip,則大大簡單了。
發佈了23 篇原創文章 · 獲贊 33 · 訪問量 18萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章