海量數據處理算法—Bloom Filter

1. 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。

1.jpg

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“處)。   

2.jpg

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

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

3.jpg

      顯然這 個判斷并不保證查找的結果是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滿足下列公式:

1.png

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

2.png

此時給出的f為:

3.png

根據以上公式,對于任意給定的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數據庫。從而大大地提高了效率。如圖:

          1.png


2 .Google的BigTable

        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:

#pragma once  
#include <stdio.h>    
#include "stdlib.h"  
#include <iostream>  
#include <time.h>  
using namespace std;

#include "stdafx.h"  
  
  
#define ARRAY_SIZE 256 /*we get the 256 chars of each line*/  
#define SIZE 48000000 /* size should be 1/8 of max*/  
#define MAX  384000000/*the max bit space*/  
  
#define SETBIT(ch,n) ch[n/8]|=1<<(7-n%8)  
#define GETBIT(ch,n) (ch[n/8]&1<<(7-n%8))>>(7-n%8)  
  
unsigned int len(char *ch);/* functions to calculate the length of the url*/  
  
unsigned int RSHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int JSHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int PJWHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int ELFHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int BKDRHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int SDBMHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int DJBHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int DEKHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int BPHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int FNVHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int APHash(char* str, unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int HFLPHash(char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int HFHash(char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int StrHash( char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
unsigned int TianlHash(char* str,unsigned int len);/* functions to calculate the hash value of the url*/  
  
  
int main()  
{  
    int i,num,num2=0; /* the number to record the repeated urls and the total of it*/  
    unsigned int tt=0;  
    int flag;         /*it helps to check weather the url has already existed */  
    char buf[257];    /*it helps to print the start time of the program */  
    time_t tmp = time(NULL);  
  
    char file1[100],file2[100];  
    FILE *fp1,*fp2;/*pointer to the file */  
    char ch[ARRAY_SIZE];    
    char *vector ;/* the bit space*/  
    vector = (char *)calloc(SIZE,sizeof(char));  
  
    printf("Please enter the file with repeated urls:\n");  
    scanf("%s",&file1);     
    if( (fp1 = fopen(file1,"rb")) == NULL) {  /* open the goal file*/  
      printf("Connot open the file %s!\n",file1);  
    }  
  
    printf("Please enter the file you want to save to:\n");  
    scanf("%s",&file2);  
    if( (fp2 = fopen(file2,"w")) == NULL) {  
        printf("Connot open the file %s\n",file2);  
    }  
    strftime(buf,32,"%Y-%m-%d %H:%M:%S",localtime(&tmp));  
    printf("%s\n",buf); /*print the system time*/  
  
    for(i=0;i<SIZE;i++) {  
        vector[i]=0;  /*set 0*/  
    }  
  
    while(!feof(fp1)) { /* the check process*/  
      
        fgets(ch,ARRAY_SIZE,fp1);  
        flag=0;  
        tt++;  
        if( GETBIT(vector, HFLPHash(ch,len(ch))%MAX) ) {      
            flag++;  
        } else {  
            SETBIT(vector,HFLPHash(ch,len(ch))%MAX );  
        }     
  
        if( GETBIT(vector, StrHash(ch,len(ch))%MAX) ) {   
            flag++;  
        } else {  
            SETBIT(vector,StrHash(ch,len(ch))%MAX );  
        }  
          
        if( GETBIT(vector, HFHash(ch,len(ch))%MAX) )   {  
            flag++;  
        } else {  
            SETBIT(vector,HFHash(ch,len(ch))%MAX );  
        }  
  
        if( GETBIT(vector, DEKHash(ch,len(ch))%MAX) ) {  
            flag++;  
        } else {  
            SETBIT(vector,DEKHash(ch,len(ch))%MAX );  
        }   
          
        if( GETBIT(vector, TianlHash(ch,len(ch))%MAX) ) {  
            flag++;  
        } else {  
            SETBIT(vector,TianlHash(ch,len(ch))%MAX );  
        }  
  
        if( GETBIT(vector, SDBMHash(ch,len(ch))%MAX) )  {  
            flag++;  
        } else {  
            SETBIT(vector,SDBMHash(ch,len(ch))%MAX );  
        }  
  
        if(flag<6)  
            num2++;       
        else              
           fputs(ch,fp2);  
      
        /*  printf(" %d",flag); */        
    }  
    /* the result*/  
    printf("\nThere are %d urls!\n",tt);  
    printf("\nThere are %d not repeated urls!\n",num2);  
    printf("There are %d repeated urls!\n",tt-num2);  
    fclose(fp1);  
    fclose(fp2);  
    return 0;  
}  
  
  
/*functions may be used in the main */  
unsigned int len(char *ch)  
{  
    int m=0;  
    while(ch[m]!='') {  
        m++;  
    }  
    return m;  
}  
  
unsigned int RSHash(char* str, unsigned int len) {  
   unsigned int b = 378551;  
   unsigned int a = 63689;  
   unsigned int hash = 0;  
   unsigned int i = 0;  
  
   for(i=0; i<len; str++, i++) {  
      hash = hash*a + (*str);  
      a = a*b;  
   }  
   return hash;  
}  
/* End Of RS Hash Function */  
  
  
unsigned int JSHash(char* str, unsigned int len)  
{  
   unsigned int hash = 1315423911;  
   unsigned int i    = 0;  
  
   for(i=0; i<len; str++, i++) {  
      hash ^= ((hash<<5) + (*str) + (hash>>2));  
   }  
   return hash;  
}  
/* End Of JS Hash Function */  
  
  
unsigned int PJWHash(char* str, unsigned int len)  
{  
   const unsigned int BitsInUnsignedInt = (unsigned int)(sizeof(unsigned int) * 8);  
   const unsigned int ThreeQuarters = (unsigned int)((BitsInUnsignedInt  * 3) / 4);  
   const unsigned int OneEighth = (unsigned int)(BitsInUnsignedInt / 8);  
   const unsigned int HighBits = (unsigned int)(0xFFFFFFFF) << (BitsInUnsignedInt - OneEighth);  
   unsigned int hash = 0;  
   unsigned int test = 0;  
   unsigned int i = 0;  
  
   for(i=0;i<len; str++, i++) {  
      hash = (hash<<OneEighth) + (*str);  
      if((test = hash & HighBits)  != 0) {  
         hash = ((hash ^(test >> ThreeQuarters)) & (~HighBits));  
      }  
   }  
  
   return hash;  
}  
/* End Of  P. J. Weinberger Hash Function */  
  
  
unsigned int ELFHash(char* str, unsigned int len)  
{  
   unsigned int hash = 0;  
   unsigned int x    = 0;  
   unsigned int i    = 0;  
  
   for(i = 0; i < len; str++, i++) {  
      hash = (hash << 4) + (*str);  
      if((x = hash & 0xF0000000L) != 0) {  
         hash ^= (x >> 24);  
      }  
      hash &= ~x;  
   }  
   return hash;  
}  
/* End Of ELF Hash Function */  
  
  
unsigned int BKDRHash(char* str, unsigned int len)  
{  
   unsigned int seed = 131; /* 31 131 1313 13131 131313 etc.. */  
   unsigned int hash = 0;  
   unsigned int i    = 0;  
  
   for(i = 0; i < len; str++, i++)  
   {  
      hash = (hash * seed) + (*str);  
   }  
  
   return hash;  
}  
/* End Of BKDR Hash Function */  
  
  
unsigned int SDBMHash(char* str, unsigned int len)  
{  
   unsigned int hash = 0;  
   unsigned int i    = 0;  
  
   for(i = 0; i < len; str++, i++) {  
      hash = (*str) + (hash << 6) + (hash << 16) - hash;  
   }  
  
   return hash;  
}  
/* End Of SDBM Hash Function */  
  
  
unsigned int DJBHash(char* str, unsigned int len)  
{  
   unsigned int hash = 5381;  
   unsigned int i    = 0;  
  
   for(i = 0; i < len; str++, i++) {  
      hash = ((hash << 5) + hash) + (*str);  
   }  
  
   return hash;  
}  
/* End Of DJB Hash Function */  
  
  
unsigned int DEKHash(char* str, unsigned int len)  
{  
   unsigned int hash = len;  
   unsigned int i    = 0;  
  
   for(i = 0; i < len; str++, i++) {  
      hash = ((hash << 5) ^ (hash >> 27)) ^ (*str);  
   }  
   return hash;  
}  
/* End Of DEK Hash Function */  
  
  
unsigned int BPHash(char* str, unsigned int len)  
{  
   unsigned int hash = 0;  
   unsigned int i    = 0;  
   for(i = 0; i < len; str++, i++) {  
      hash = hash << 7 ^ (*str);  
   }  
  
   return hash;  
}  
/* End Of BP Hash Function */  
  
  
unsigned int FNVHash(char* str, unsigned int len)  
{  
   const unsigned int fnv_prime = 0x811C9DC5;  
   unsigned int hash      = 0;  
   unsigned int i         = 0;  
  
   for(i = 0; i < len; str++, i++) {  
      hash *= fnv_prime;  
      hash ^= (*str);  
   }  
  
   return hash;  
}  
/* End Of FNV Hash Function */  
  
  
unsigned int APHash(char* str, unsigned int len)  
{  
   unsigned int hash = 0xAAAAAAAA;  
   unsigned int i    = 0;  
  
   for(i = 0; i < len; str++, i++) {  
      hash ^= ((i & 1) == 0) ? (  (hash <<  7) ^ (*str) * (hash >> 3)) :  
                               (~((hash << 11) + (*str) ^ (hash >> 5)));  
   }  
  
   return hash;  
}  
/* End Of AP Hash Function */  
unsigned int HFLPHash(char *str,unsigned int len)  
{  
   unsigned int n=0;  
   int i;  
   char* b=(char *)&n;  
   for(i=0;i<strlen(str);++i) {  
     b[i%4]^=str[i];  
    }  
    return n%len;  
}  
/* End Of HFLP Hash Function*/  
unsigned int HFHash(char* str,unsigned int len)  
{  
   int result=0;  
   char* ptr=str;  
   int c;  
   int i=0;  
   for (i=1;c=*ptr++;i++)  
   result += c*3*i;  
   if (result<0)  
      result = -result;  
   return result%len;  
}  
/*End Of HKHash Function */  
  
 unsigned int StrHash( char *str,unsigned int len)  
 {  
    register unsigned int   h;  
    register unsigned char *p;  
     for(h=0,p=(unsigned char *)str;*p;p++) {  
         h=31*h+*p;  
     }  
  
      return h;  
  
  }  
 /*End Of StrHash Function*/  
  
unsigned int TianlHash(char *str,unsigned int len)  
{  
   unsigned long urlHashValue=0;  
   int ilength=strlen(str);  
   int i;  
   unsigned char ucChar;  
   if(!ilength)  {  
       return 0;  
   }  
   if(ilength<=256)  {  
      urlHashValue=16777216*(ilength-1);  
  } else {   
      urlHashValue = 42781900080;  
  }  
  if(ilength<=96) {  
      for(i=1;i<=ilength;i++) {  
          ucChar=str[i-1];  
          if(ucChar<='Z'&&ucChar>='A')  {  
              ucChar=ucChar+32;  
          }  
          urlHashValue+=(3*i*ucChar*ucChar+5*i*ucChar+7*i+11*ucChar)%1677216;  
      }  
  } else  {  
      for(i=1;i<=96;i++)  
      {  
          ucChar=str[i+ilength-96-1];  
          if(ucChar<='Z'&&ucChar>='A')  
          {  
              ucChar=ucChar+32;  
          }  
          urlHashValue+=(3*i*ucChar*ucChar+5*i*ucChar+7*i+11*ucChar)%1677216;  
      }  
  }  
  return urlHashValue;  
  
 }  
/*End Of Tianl Hash Function*/

網上找到的php簡單實現:

<?php  
  
/** 
 * Implements a Bloom Filter 
 */  
class BloomFilter {  
    /** 
     * Size of the bit array 
     * 
     * @var int 
     */  
    protected $m;  
  
    /** 
     * Number of hash functions 
     * 
     * @var int 
     */  
    protected $k;  
  
    /** 
     * Number of elements in the filter 
     * 
     * @var int 
     */  
    protected $n;  
  
    /** 
     * The bitset holding the filter information 
     * 
     * @var array 
     */  
    protected $bitset;  
  
    /** 
     * 計算最優的hash函數個數:當hash函數個數k=(ln2)*(m/n)時錯誤率最小 
     * 
     * @param int $m bit數組的寬度(bit數) 
     * @param int $n 加入布隆過濾器的key的數量 
     * @return int 
     */  
    public static function getHashCount($m, $n) {  
        return ceil(($m / $n) * log(2));  
    }  
  
    /** 
     * Construct an instance of the Bloom filter 
     * 
     * @param int $m bit數組的寬度(bit數) Size of the bit array 
     * @param int $k hash函數的個數 Number of different hash functions to use 
     */  
    public function __construct($m, $k) {  
        $this->m = $m;  
        $this->k = $k;  
        $this->n = 0;  
  
        /* Initialize the bit set */  
        $this->bitset = array_fill(0, $this->m - 1, false);  
    }  
  
    /** 
     * False Positive的比率:f = (1 – e-kn/m)k    
     * Returns the probability for a false positive to occur, given the current number of items in the filter 
     * 
     * @return double 
     */  
    public function getFalsePositiveProbability() {  
        $exp = (-1 * $this->k * $this->n) / $this->m;  
  
        return pow(1 - exp($exp),  $this->k);  
    }  
  
    /** 
     * Adds a new item to the filter 
     * 
     * @param mixed Either a string holding a single item or an array of  
     *              string holding multiple items.  In the latter case, all 
     *              items are added one by one internally. 
     */  
    public function add($key) {  
        if (is_array($key)) {  
            foreach ($key as $k) {  
                $this->add($k);  
            }  
            return;  
        }  
  
        $this->n++;  
  
        foreach ($this->getSlots($key) as $slot) {  
            $this->bitset[$slot] = true;  
        }  
    }  
  
    /** 
     * Queries the Bloom filter for an element 
     * 
     * If this method return FALSE, it is 100% certain that the element has 
     * not been added to the filter before.  In contrast, if TRUE is returned, 
     * the element *may* have been added to the filter previously.  However with 
     * a probability indicated by getFalsePositiveProbability() the element has 
     * not been added to the filter with contains() still returning TRUE. 
     * 
     * @param mixed Either a string holding a single item or an array of  
     *              strings holding multiple items.  In the latter case the 
     *              method returns TRUE if the filter contains all items. 
     * @return boolean 
     */  
    public function contains($key) {  
        if (is_array($key)) {  
            foreach ($key as $k) {  
                if ($this->contains($k) == false) {  
                    return false;  
                }  
            }  
  
            return true;  
        }  
  
        foreach ($this->getSlots($key) as $slot) {  
            if ($this->bitset[$slot] == false) {  
                return false;  
            }  
        }  
  
        return true;  
    }  
  
    /** 
     * Hashes the argument to a number of positions in the bit set and returns the positions 
     * 
     * @param string Item 
     * @return array Positions 
     */  
    protected function getSlots($key) {  
        $slots = array();  
        $hash = self::getHashCode($key);  
        mt_srand($hash);  
  
        for ($i = 0; $i < $this->k; $i++) {  
            $slots[] = mt_rand(0, $this->m - 1);  
        }  
  
        return $slots;  
    }  
  
    /** 
     * 使用CRC32產生一個32bit(位)的校驗值。 
     * 由于CRC32產生校驗值時源數據塊的每一bit(位)都會被計算,所以數據塊中即使只有一位發生了變化,也會得到不同的CRC32值。 
     * Generates a numeric hash for the given string 
     * 
     * Right now the CRC-32 algorithm is used.  Alternatively one could e.g. 
     * use Adler digests or mimick the behaviour of Java's hashCode() method. 
     * 
     * @param string Input for which the hash should be created 
     * @return int Numeric hash 
     */  
    protected static function getHashCode($string) {  
        return crc32($string);  
    }  
      
}  
  
  
  
$items = array("first item", "second item", "third item");  
          
/* Add all items with one call to add() and make sure contains() finds 
 * them all. 
 */  
$filter = new BloomFilter(100, BloomFilter::getHashCount(100, 3));  
$filter->add($items);  
  
//var_dump($filter); exit;  
$items = array("firsttem", "seconditem", "thirditem");  
foreach ($items as $item) {  
 var_dump(($filter->contains($item)));  
}  
  
/* Add all items with multiple calls to add() and make sure contains() 
* finds them all. 
*/  
$filter = new BloomFilter(100, BloomFilter::getHashCount(100, 3));  
foreach ($items as $item) {  
    $filter->add($item);  
}  
$items = array("fir sttem", "secondit em", "thir ditem");  
foreach ($items as $item) {  
 var_dump(($filter->contains($item)));  
}

問題實例】 給你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,則大大簡單了。

  1.  轉自:http://blog.csdn.net/hguisu/article/details/7866173 

原創文章,作者:s19930811,如若轉載,請注明出處:http://www.www58058.com/2751

(0)
s19930811s19930811
上一篇 2015-10-21
下一篇 2015-10-22

相關推薦

  • MySQL Order By實現原理分析和Filesort優化

    在MySQL中的ORDER BY有兩種排序實現方式: 1、利用有序索引獲取有序數據 2、文件排序 在使用explain分析查詢的時候,利用有序索引獲取有序數據顯示Using index。而文件排序顯示Using filesort。 1.利用有序索引獲取有序數據         &…

    Linux干貨 2015-04-13
  • 馬哥教育網絡版25期+第一周作業

    1、描述計算機的組成及其功能 計算機是由CPU,控制器,RAM,輸入設備,輸出設備組成的 2、按系列羅列Linux的發行版,并描述不同發行版之間的聯系與區別 現如今主流的LINUX發行版系列主要有: Debian,Slackware,Redhat,這些發行版都是基于GUNLinux開發的,不過是由不同的組織或團體開發并發行的。 3、描述Linux的哲學思想,…

    Linux干貨 2016-12-05
  • Linux初學筆記(markdown格式)

    Linux基礎命令筆記

    Linux干貨 2018-03-26
  • 集群-基礎知識(1)

    背景 隨著互聯網訪問量的急劇增加,單臺服務器的能力已嚴重不能滿足需求。則需要從兩個方面考慮提高服務能力:1、向上擴展,2、向外擴展 向上擴展的缺點: 1、造價高 2、隨著性能的提高,會在某個臨界點遇到瓶頸,導致性能隨后降低。 向外擴展的優點: 1、造價低 2、提供高并發能力和高可用性 3、可擴展性好。 分類 負載均衡集群(Load Balance) 高可用集…

    Linux干貨 2015-11-26
  • shell中的if else語句與文件查找find淺析

    shell中的if else語句與文件查找find淺析    上篇文章中我們講述了shell腳本編程的初步入門,其中講到了shell編程中的順序執行,順序執行時一種簡單的小腳本,如果在編輯腳本的時候遇到要做出條件判斷執行的時候要怎么辦呢?我們學習過if之后你會發現這會很簡單。if 語句通過關系運算符判斷表達式的真假來決定執行哪個分支。 S…

    Linux干貨 2016-08-16
  • Linux文件管理命令

    Linux系統上文件管理命令 一、文件查看類命令      1、cat 由第一行開始顯示文件內容 語法格式: cat [選項列表] [文件列表]… 參數說明: -A, –show-all 等價于 -vET 。 -b, –number-nonblank 給非空輸出行編號。 -e 等價于 -vE 。 -E…

    Linux干貨 2017-07-24
欧美性久久久久