天天看点

布隆过滤器及优缺点

如果想判断一个元素是不是在一个集合里,一般想到的是将集合中所有元素保存起来,然后通过比较确定。

但是随着集合中元素的增加,我们需要的存储空间会很大,检索的速度也越来越慢。

一、原理

Bloom Filter 是一种空间效率很高的随机数据结构,Bloom filter 可以看做是对 bit-map 的扩展。当一个元素被加入集合时,通过 K 个 Hash 函数将这个元素映射成一个位阵列(Bit array)中的 K 个点,把它们置为 1。

检索时,我们只要看看这些点是不是都是 1 就(大约)知道集合中有没有它。

值得注意的是:如果这些点有任何一个 0,则被检索元素一定不在。

如果都是 1,则被检索元素很可能在。

二、优点

空间效率和查询时间都远远超过一般的算法,布隆过滤器存储空间和插入 / 查询时间都是常数O(k)。

另外, 散列函数相互之间没有关系,方便由硬件并行实现。

布隆过滤器不需要存储元素本身,在某些对保密要求非常严格的场合有优势。

三、缺点

布隆过滤器的缺点和优点一样明显。

误算率是其中之一。随着存入的元素数量增加,误算率随之增加。但是如果元素数量太少,则使用散列表就可以。

另外,一般情况下不能从布隆过滤器中删除元素. 我们很容易想到把位数组变成整数数组,每插入一个元素相应的计数器加 1, 这样删除元素时将计数器减掉就可以了。然而要保证安全地删除元素并非如此简单。首先我们必须保证删除的元素的确在布隆过滤器里面. 这一点单凭这个过滤器是无法保证的。另外计数器回绕也会造成问题。

四、布隆过滤器的简单实现

1、为了检测存在时比较准确,我们这里用了五个哈希函数来映射其在位图中的位置:

template<class K>
struct _HashFunc1
{
    size_t BKDRHash(const char *str)
    {
        register size_t hash = 0;
        while (size_t ch = (size_t)*str++)
        {
            hash = hash * 131 + ch;            //也可以乘以31、131、1313、13131、131313.. 
        }
        return hash;
    }
    size_t operator()(const K& s)
    {
        return BKDRHash(s.c_str());
    }
};

template<class K>
struct _HashFunc2
{
    size_t SDBMHash(const char *str)
    {
        register size_t hash = 0;
        while (size_t ch = (size_t)*str++)
        {
            hash = 65599 * hash + ch;
            //hash = (size_t)ch + (hash << 6) + (hash << 16) - hash;  
        }
        return hash;
    }
    size_t operator()(const K& s)
    {
        return SDBMHash(s.c_str());
    }
};  
template<class K>
struct _HashFunc3
{
    size_t RSHash(const char *str)
    {
        register size_t hash = 0;
        size_t magic = 63689;
        while (size_t ch = (size_t)*str++)
        {
            hash = hash * magic + ch;
            magic *= 378551;
        }
        return hash;
    }
    size_t operator()(const K& s)
    {
        return RSHash(s.c_str());
    }
};

template<class K>
struct _HashFunc4
{
    size_t APHash(const char *str)
    {
        register size_t hash = 0;
        size_t ch;
        for (long i = 0; ch = (size_t)*str++; i++)
        {
            if ((i & 1) == 0)
            {
                hash ^= ((hash << 7) ^ ch ^ (hash >> 3));
            }
            else
            {
                hash ^= (~((hash << 11) ^ ch ^ (hash >> 5)));
            }
        }
        return hash;
    }
    size_t operator()(const K& s)
    {
        return APHash(s.c_str());
    }
};
template<class K>
struct _HashFunc5
{
    size_t JSHash(const char *str)
    {
        if (!*str)        // 这是由本人添加,以保证空字符串返回哈希值0  
            return 0;
        register size_t hash = 1315423911;
        while (size_t ch = (size_t)*str++)
        {
            hash ^= ((hash << 5) + ch + (hash >> 2));
        }
        return hash;
    }
    size_t operator()(const K& s)
    {
        return JSHash(s.c_str());
    }
};      

2、底层结构用位图:

class BitMap
{
public:
    BitMap(size_t bitSet = 10)
    :_bitCount(bitSet)
    {
        _bitSet.resize((bitSet >> 5) + 1);   
    }
    void Set(size_t whichBit)   //置1
    {
        size_t index = whichBit >> 5;
        if (whichBit < _bitCount)
            _bitSet[index] |= 1 << (whichBit % 32);
    }
    void ReSet(size_t whichBit)   //置0
    {
        size_t index = whichBit >> 5;
        if (whichBit < _bitCount)
            _bitSet[index] &= ~(1 << (whichBit % 32));
    }
    bool Test(size_t whichBit)   //查看比特位是0是1
    {
        size_t index = whichBit >> 5;
        if (whichBit < _bitCount)
            return _bitSet[index] & (1 << (whichBit % 32));

        cout << whichBit << "比特位不存在" << endl;
        return false;
    }
    size_t Count()const      //1的个数
    {
        char *pBitCount = "\0\1\1\2\1\2\2\3\1\2\2\3\2\3\3\4";
        size_t count = 0;
        for (size_t i = 0; i < _bitSet.size(); i++)
        {
            int value = _bitSet[i];
            int j = 0;
            while (j < sizeof(int))
            {
                count += pBitCount[value & 0x0F];
                value >>= 4;
                count += pBitCount[value & 0x0F];
                value >>= 4;
                j++;
            }
        }
        return count;
    }
    size_t Size()const    //比特位的个数
    {
        return _bitCount;
    }
protected:
    vector<int> _bitSet;
    size_t _bitCount;
};      

关于位图的介绍请看上篇文章:

​​javascript:void(0)​​

3、布隆过滤器的实现

template<class K, class KTOInt1 = _HashFunc1<K>,
                  class KTOInt2 = _HashFunc2<K>,
                  class KTOInt3 = _HashFunc3<K>,
                  class KTOInt4 = _HashFunc4<K>,
                  class KTOInt5 = _HashFunc5<K>>
//检测一个元素是不是在集合里
class BloomFilter
{
public:
    BloomFilter(size_t size)
        :_bmp(size)
        , _size(0)
    {}

    void Insert(const K& key)
    {
        size_t bitCount = _bmp.Size();
        size_t index1 = KTOInt1()(key) % bitCount;
        size_t index2 = KTOInt2()(key) % bitCount;
        size_t index3 = KTOInt3()(key) % bitCount;
        size_t index4 = KTOInt4()(key) % bitCount;
        size_t index5 = KTOInt5()(key) % bitCount;

        _bmp.Set(index1);
        _bmp.Set(index2);
        _bmp.Set(index3);
        _bmp.Set(index4);
        _bmp.Set(index5);
        _size++;

        cout << index1 << " " << index2 << " " << index3 << " " << index4 << " " << index5 << endl;
    }

    bool IsInBloomFilter(const K&key)
    {
        size_t bitCount = _bmp.Size();

        size_t index1 = KTOInt1()(key) % bitCount;
        if (!_bmp.Test(index1))
            return false;
        size_t index2 = KTOInt2()(key) % bitCount;
        if (!_bmp.Test(index2))
            return false;
        size_t index3 = KTOInt3()(key) % bitCount;
        if (!_bmp.Test(index3))
            return false;
        size_t index4 = KTOInt4()(key) % bitCount;
        if (!_bmp.Test(index4))
            return false;
        size_t index5 = KTOInt5()(key) % bitCount;
        if (!_bmp.Test(index5))
            return false;

        return true;   //可能
    }

    size_t Size()
    {
        return _size;
    }
protected:
    BitMap _bmp;
    size_t _size;    //实际元素的个数
};      

看测试:

void BloomFilterTest()
{
    BloomFilter<string> bft(100);
    bft.Insert("张三");
    bft.Insert("李四");
    bft.Insert("刘师");

    cout << bft.IsInBloomFilter("张三") << endl;
    cout << bft.IsInBloomFilter("小明") << endl;
    cout << bft.Size() << endl;
}      

继续阅读