pleonasm / bloom-filter
纯PHP实现的布隆过滤器
1.0.3
2022-05-02 23:00 UTC
Requires
- php: >=7.1
Requires (Dev)
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ^6.5 || ^7.5 || ^8.5 || ^9.4
This package is auto-updated.
Last update: 2024-08-30 01:17:28 UTC
README
这是PHP中一个经过良好测试的布隆过滤器实现。它具有以下特点
- 高效使用位数组内存(无论如何PHP都可以尽可能高效)。
- 一种获取过滤器原始版本的方法,以便传输到其他系统。
- 能够将上述原始过滤器恢复为可用的过滤器。
- 根据所需的集合大小和误报概率自动计算最优的哈希和位数组大小。
- 根据需要自动生成哈希函数。
安装
通过Composer安装(确保您的路径中或项目中已配置Composer)。
在您的package.json中添加以下内容
{ "require": { "pleonasm/bloom-filter": "*" } }
运行composer install
。
使用
<?php use Pleo\BloomFilter\BloomFilter; $approximateItemCount = 100000; $falsePositiveProbability = 0.001; $before = memory_get_usage(); $bf = BloomFilter::init($approximateItemCount, $falsePositiveProbability); $after = memory_get_usage(); // if this were a 100,000 item array, we would be looking at about 4MB of // space used instead of the 200k or so this uses. echo ($after - $before) . "\n"; $bf->add('item1'); $bf->add('item2'); $bf->add('item3'); $bf->exists('item1'); // true $bf->exists('item2'); // true $bf->exists('item3'); // true // The following call will return false with a 0.1% probability of // being true as long as the amount of items in the filter are < 100000 $bf->exists('non-existing-item'); // false $serialized = json_encode($bf); // you can store/transfer this places! unset($bf); // Re-hydrate the object this way. $bf = BloomFilter::initFromJson(json_decode($serialized, true)); $bf->exists('item1'); // still true $bf->exists('item2'); // still true $bf->exists('item3'); // still true $bf->exists('non-existing-item'); // still false
序列化警告
注意:在对布隆过滤器对象使用json_encode()
时应工作于大多数系统。如果是在64位和32位系统之间移动过滤器(将根本无法工作)或在小端和大端系统之间移动(应该可以工作,但我还没有测试过),可能会遇到麻烦。
还请注意,json_encode()
会将二进制位数组进行base64编码。因此,如果您有一个大型数组,序列化后的数组大小将增加约33%。
其他注意事项
在底层,所使用的哈希机制实际上是您选择的算法的HMAC。一般来说,如果您选择一个非加密算法来计算HMAC,则PHP的hash扩展可能不会高兴,所以请不要使用此库,一切都会正常工作。
如果您特别使用PHP 7.1,这可能会出现,但通常您使用的哈希必须输出至少64位。像adler32或crc32这样的东西不合适使用,即使在PHP 7.1中它们不会抛出错误。
需求
此项目需要PHP 7.1或更高版本。但是,bloom-filter的1.0.2版本适用于PHP 5.4到7.0,并且可以正常工作。
许可
您可以在LICENSE文件中找到此代码的许可。