布隆过滤器

布隆过滤器(Bloom Filter)是一种概率空间高效的数据结构。它与hashmap非常相似,用于检索一个元素是否在一个集合中。它在检索元素是否存在时,能很好地取舍空间使用率与误报比例。正是由于这个特性,它被称作概率性数据结构(probabilistic data structure)。

空间效率

我们来仔细地看看它的空间效率。如果你想在集合中存储一系列的元素,有很多种不同的做法。你可以把数据存储在hashmap,随后在hashmap中检索元素是否存在,hashmap的插入和查询的效率都非常高。但是,由于hashmap直接存储内容,所以空间利用率并不高。

如果希望提高空间利用率,我们可以在元素插入集合之前做一次哈希变换。还有其它方法呢?我们可以用位数组来存储元素的哈希值。还有吗,还有吗?我们也允许在位数组中存在哈希冲突。这正是布隆过滤器的工作原理,它们就是基于允许哈希冲突的位数组,可能会造成一些误报。在布隆过滤器的设计阶段就允许哈希冲突的存在,否则空间使用就不够紧凑了。

当使用列表或者集合时,空间效率都是重要且显著的,那么布隆过滤器就应当被考虑。

布隆过滤器基础

布隆过滤器是N位的位数组,其中N是位数组的大小。它还有另一个参数k,表示使用哈希函数的个数。这些哈希函数用来设置位数组的值。当往过滤器中插入元素x时,h1(x), h2(x), …, hk(x)所对应索引位置的值被置“1”,索引值由各个哈希函数计算得到。注意,如果我们增加哈希函数的数量,误报的概率会趋近于0.但是,插入和查找的时间开销更大,布隆过滤器的容量也会减小。

为了用布隆过滤器检验元素是否存在,我们需要校验是否所有的位置都被置“1”,与我们插入元素的过程非常相似。如果所有位置都被置“1”,那也就意味着该元素很有可能存在于布隆过滤器中。若有位置未被置“1”,那该元素一定不存在。

简单的Python实现

如果想实现一个简单的布隆过滤器,我们可以这样做:

     from bitarray import bitarray

     # 3rd party
import mmh3 class BloomFilter(set): def __init__(self, size, hash_count):
super(BloomFilter, self).__init__()
self.bit_array = bitarray(size)
self.bit_array.setall(0)
self.size = size
self.hash_count = hash_count def __len__(self):
return self.size def __iter__(self):
return iter(self.bit_array) def add(self, item):
for ii in range(self.hash_count):
index = mmh3.hash(item, ii) % self.size
self.bit_array[index] = 1 return self def __contains__(self, item):
out = True
for ii in range(self.hash_count):
index = mmh3.hash(item, ii) % self.size
if self.bit_array[index] == 0:
out = False return out def main():
bloom = BloomFilter(100, 10)
animals = ['dog', 'cat', 'giraffe', 'fly', 'mosquito', 'horse', 'eagle',
'bird', 'bison', 'boar', 'butterfly', 'ant', 'anaconda', 'bear',
'chicken', 'dolphin', 'donkey', 'crow', 'crocodile']
# First insertion of animals into the bloom filter
for animal in animals:
bloom.add(animal) # Membership existence for already inserted animals
# There should not be any false negatives
for animal in animals:
if animal in bloom:
print('{} is in bloom filter as expected'.format(animal))
else:
print('Something is terribly went wrong for {}'.format(animal))
print('FALSE NEGATIVE!') # Membership existence for not inserted animals
# There could be false positives
other_animals = ['badger', 'cow', 'pig', 'sheep', 'bee', 'wolf', 'fox',
'whale', 'shark', 'fish', 'turkey', 'duck', 'dove',
'deer', 'elephant', 'frog', 'falcon', 'goat', 'gorilla',
'hawk' ]
for other_animal in other_animals:
if other_animal in bloom:
print('{} is not in the bloom, but a false positive'.format(other_animal))
else:
print('{} is not in the bloom filter as expected'.format(other_animal)) if __name__ == '__main__':
main()
 

输出结果如下所示:

dog is in bloom filter as expected
cat is in bloom filter as expected
giraffe is in bloom filter as expected
fly is in bloom filter as expected
mosquito is in bloom filter as expected
horse is in bloom filter as expected
eagle is in bloom filter as expected
bird is in bloom filter as expected
bison is in bloom filter as expected
boar is in bloom filter as expected
butterfly is in bloom filter as expected
ant is in bloom filter as expected
anaconda is in bloom filter as expected
bear is in bloom filter as expected
chicken is in bloom filter as expected
dolphin is in bloom filter as expected
donkey is in bloom filter as expected
crow is in bloom filter as expected
crocodile is in bloom filter as expected badger is not in the bloom filter as expected
cow is not in the bloom filter as expected
pig is not in the bloom filter as expected
sheep is not in the bloom, but a false positive
bee is not in the bloom filter as expected
wolf is not in the bloom filter as expected
fox is not in the bloom filter as expected
whale is not in the bloom filter as expected
shark is not in the bloom, but a false positive
fish is not in the bloom, but a false positive
turkey is not in the bloom filter as expected
duck is not in the bloom filter as expected
dove is not in the bloom filter as expected
deer is not in the bloom filter as expected
elephant is not in the bloom, but a false positive
frog is not in the bloom filter as expected
falcon is not in the bloom filter as expected
goat is not in the bloom filter as expected
gorilla is not in the bloom filter as expected
hawk is not in the bloom filter as expected
 

从输出结果可以发现,存在不少误报样本,但是并不存在假阴性。

不同于这段布隆过滤器的实现代码,其它语言的多个实现版本并不提供哈希函数的参数。这是因为在实际应用中误报比例这个指标比哈希函数更重要,用户可以根据误报比例的需求来调整哈希函数的个数。通常来说,sizeerror_rate是布隆过滤器的真正误报比例。如果你在初始化阶段减小了error_rate,它们会调整哈希函数的数量。

误报

布隆过滤器能够拍着胸脯说某个元素“肯定不存在”,但是对于一些元素它们会说“可能存在”。针对不同的应用场景,这有可能会是一个巨大的缺陷,亦或是无关紧要的问题。如果在检索元素是否存在时不介意引入误报情况,那么你就应当考虑用布隆过滤器。

另外,如果随意地减小了误报比率,哈希函数的数量相应地就要增加,在插入和查询时的延时也会相应地增加。本节的另一个要点是,如果哈希函数是相互独立的,并且输入元素在空间中均匀的分布,那么理论上真实误报率就不会超过理论值。否则,由于哈希函数的相关性和更频繁的哈希冲突,布隆过滤器的真实误报比例会高于理论值。

在使用布隆过滤器时,需要考虑误报的潜在影响。

确定性

当你使用相同大小和数量的哈希函数时,某个元素通过布隆过滤器得到的是正反馈还是负反馈的结果是确定的。对于某个元素x,如果它现在可能存在,那五分钟之后、一小时之后、一天之后、甚至一周之后的状态都是可能存在。当我得知这一特性时有一点点惊讶。因为布隆过滤器是概率性的,那其结果显然应该存在某种随机因素,难道不是吗?确实不是。它的概率性体现在我们无法判断究竟哪些元素的状态是可能存在

换句话说,过滤器一旦做出可能存在的结论后,结论不会发生变化。

缺点

布隆过滤器并不十全十美。

布隆过滤器的容量

布隆过滤器需要事先知道将要插入的元素个数。如果你并不知道或者很难估计元素的个数,情况就不太好。你也可以随机指定一个很大的容量,但这样就会浪费许多存储空间,存储空间却是我们试图优化的首要任务,也是选择使用布隆过滤器的原因之一。一种解决方案是创建一个能够动态适应数据量的布隆过滤器,但是在某些应用场景下这个方案无效。有一种可扩展布隆过滤器,它能够调整容量来适应不同数量的元素。它能弥补一部分短板。

布隆过滤器的构造和检索

在使用布隆过滤器时,我们不仅要接受少量的误报率,还要接受速度方面的额外时间开销。相比于hashmap,对元素做哈希映射和构建布隆过滤器时必然存在一些额外的时间开销。

无法返回元素本身

布隆过滤器并不会保存插入元素的内容,只能检索某个元素是否存在,因为存在哈希函数和哈希冲突我们无法得到完整的元素列表。这是它相对于其它数据结构的最显著优势,空间的使用率也造成了这块短板。

删除某个元素

想从布隆过滤器中删除某个元素可不是一件容易的事情,你无法撤回某次插入操作,因为不同项目的哈希结果可以被索引在同一位置。如果想撤消插入,你只能记录每个索引位置被置位的次数,或是重新创建一次。两种方法都有额外的开销。基于不同的应用场景,若要删除一些元素,我们更倾向于重建布隆过滤器。

浅析布隆过滤器及实现demo的更多相关文章

  1. 【浅析】|白话布隆过滤器BloomFilter

    通过本文将了解到以下内容: 查找问题的一般思路 布隆过滤器的基本原理 布隆过滤器的典型应用 布隆过滤器的工程实现 场景说明: 本文阐述的场景均为普通单机服务器.并非分布式大数据平台,因为在大数据平台下 ...

  2. 布隆过滤器的demo

    /** * 缓存击穿 * @author * */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = ...

  3. 【布隆过滤器】基于Hutool库实现的布隆过滤器Demo

    布隆过滤器出现的背景: 如果想判断一个元素是不是在一个集合里,一般想到的是将集合中所有元素保存起来,然后通过比较确定.链表.树.散列表(又叫哈希表,Hash table)等等数据结构都是这种思路,存储 ...

  4. 布隆过滤器(BloomFilter)持久化

    摘要 Bloomfilter运行在一台机器的内存上,不方便持久化(机器down掉就什么都没啦),也不方便分布式程序的统一去重.我们可以将数据进行持久化,这样就克服了down机的问题,常见的持久化方法包 ...

  5. 【面试突击】-缓存击穿(布隆过滤器 Bloom Filter)

    原文地址:https://blog.csdn.net/fouy_yun/article/details/81075432 前面的文章介绍了缓存的分类和使用的场景.通常情况下,缓存是加速系统响应的一种途 ...

  6. python实现布隆过滤器及原理解析

    python实现布隆过滤器及原理解析     布隆过滤器( BloomFilter )是一种数据结构,比较巧妙的概率型数据结构(probabilistic data structure),特点是高效地 ...

  7. 细谈布隆过滤器及Redis实现

    ​ 何为布隆过滤器? 本质上是一种数据结构,是1970年由布隆提出的.它实际上是一个很长的二进制向量(位图)和一系列随机映射函数(哈希函数).可以用于检索一个元素是否在一个集合中. 数据结构: 布隆过 ...

  8. 布隆过滤器的概述及Python实现

    布隆过滤器 布隆过滤器是一种概率空间高效的数据结构.它与hashmap非常相似,用于检索一个元素是否在一个集合中.它在检索元素是否存在时,能很好地取舍空间使用率与误报比例.正是由于这个特性,它被称作概 ...

  9. 【转】Bloom Filter布隆过滤器的概念和原理

    转自:http://blog.csdn.net/jiaomeng/article/details/1495500 之前看数学之美丽,里面有提到布隆过滤器的过滤垃圾邮件,感觉到何其的牛,竟然有这么高效的 ...

随机推荐

  1. POJ2960 S-Nim 【博弈论】

    Description Arthur and his sister Caroll have been playing a game called Nim for some time now. Nim ...

  2. python学习day19 面向对象(一)封装/多态/继承

    面向对象 封装思想:将同一类的函数函数封装到同一个py文件中,方便调用 面向对象也有封装的作用,将同一类的函数封装到一个类中 多态(鸭子模型):多种类型/多种形态 #,什么事鸭子模型 对于一个函数,p ...

  3. linux下python安装

    下载包: wget https://www.python.org/ftp/python/3.6.3/Python-3.6.3.tar.gz 解压安装: tar -zvxf  Python-3.6.3. ...

  4. 编写高质量的Python代码系列(二)之函数

    Python中的函数具备多种特性,这可以简化编程工作.Python函数的某些性质与其他编程语言中的函数相似,但也有性质是Python独有的.本节将介绍如何用函数来表达亿图.提升可复用程度,并减少Bug ...

  5. Spring Cloud微服务实战:手把手带你整合eureka&zuul&feign&hystrix

    转载自:https://www.jianshu.com/p/cab8f83b0f0e 代码实现:https://gitee.com/ccsoftlucifer/springCloud_Eureka_z ...

  6. GIL全局锁测试

    基础知识:https://www.cnblogs.com/SuKiWX/p/8804974.html 测试环境 python3.7默认解释器(cpython) cpu为四核 测试代码 #! /usr/ ...

  7. 洛谷红名+AC150祭

    emmmm没什么想说的,随便放个图吧23333(逃~

  8. ajax跨域例子

    例子 https://github.com/ruanyf/react-demos/blob/master/demo12/index.html 此网页代码运行在本地, 是可以访问 github 数据的. ...

  9. S2-045漏洞初步分析

    0x01 前言 前几天刚分析完s2-032这个漏洞,今天又爆发了一个s2-045的漏洞,又是直接的命令执行,影响了struts2绝大多数的版本. 官方给的漏洞公告在这里   https://cwiki ...

  10. vuex概念详解

    阅读vuex官网以后用自己的话概括起来就是:vuex是vue配套的公共数据管理工具,它可以把一些共享的数据,保存到vuex中,方便整个程序中的任何组件直接获取或修改我们的公共数据. vuex是为了保存 ...