Bloom filter 簡單而言就是對hash 表的創新,用在 Hbase 中可以有有效減少磁盤IO次數。
圖片來源:hbase 權威指南
**使用場景總結:
- 當用戶定期更新所有行時不適合使用Bloom filter,當用戶定期更新部分行時,適合使用Bloom filter
- 當數據單元格較小時不合適使用Bloom filter (因爲此時將會有太多的Bloom filter)
- 使用行級Bloom filter 還是 行加列級Bloom Filter 取決於使用模式,當操作是整行操作時,採用Bloom Filter 操作較合適
**
下面是一個java 的簡單實現
package basic;
/*
* @author: wjf
* @version: 2016年4月15日 下午10:05:28
*/
import java.util.BitSet;
public class BloomFilter {
private static int DEFAULT_SIZE=1<<24;
private int[] seeds={3,5,7,11,13,17,31,41};
private static BitSet bits=new BitSet(DEFAULT_SIZE);
private SimpleHash[] hashs=new SimpleHash[seeds.length];
public boolean addValue(String value){
if(value==null){
return false;
}else{
for(int i=0;i<seeds.length;i++){
hashs[i]=new SimpleHash(DEFAULT_SIZE,seeds[i]);
bits.set(hashs[i].hash(value),true);
}
return true;
}
}
public boolean contains(String value){
if(value==null){
return false;
}else{
boolean ret=true;
for(SimpleHash h:hashs){
ret=ret && bits.get(h.hash(value));
if(ret == false){
return false;
}
}
return true;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
BloomFilter bfilter=new BloomFilter();
bfilter.addValue("just for test");
System.out.println(bfilter.contains("just for test"));
}
}
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;
for(int i=0;i<value.length();i++){
result=result*seed+value.charAt(i);
}
return (cap-1)&result;
}
}