BloomFilter: Extensible and Removable

In this example, we present two types of implementations of bloom filter which have similarities and differences.

The similarity is that both support capacity extension, we can extend the capacity by creating another layer of bloom filter to hold the new coming data. Once this layer is full, deliver the new data to next layer which is a recursive process;

Th difference is that only one support deletion operation. The naive one that only supports add but with good efficiency and conserves a great amount of memory. The other supports both add and remove, the cost is a great deal of extra memory space. It depends on different situations and applications when choosing a proper one.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import java.io.Serializable;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.List;
import java.util.Random;


public class BloomFilter {

public static void main(String[] args) {

FlexibleBloomFilter fbf = new FlexibleBloomFilter<Integer>(10, 10000, 2);
for (int i = 0; i < 55000; i++) {
fbf.add(i);

if (Math.random() > 0.9) {
int val = new Random().nextInt(20000);
System.out.println("Current i=" + i + ", contains " + val + ": " + fbf.contains(val));
}
}

System.out.println(fbf.getFalsePositiveProbability());

CountableBloomFilter cbf = new CountableBloomFilter(10, 1000, 2);

int count = 0;
while (true) {
for (int i = 0; i < 3000; i++) {
cbf.add(i);
}

count++;
if (count > 5) {
break;
}
}

for (int i = 0; i < count + 2; i++) {
cbf.remove(10);
System.out.println("Current i=" + i + ", contains " + 10 + ": " + cbf.contains(10));
}
}
}

class FlexibleBloomFilter<T> implements Serializable {

// This is a flexible BloomFilter that support multi-layer keep data. Once the added element exceeds
// the capacity of the filter, the accuracy will drop dramatically. It is necessary to instantiate another
// filter to keep the extra data so that the filter can maintain good condition.

// By the way, this version does not support element deletion.

// MD5 assure good enough accuracy in most circumstances.
static String hashName = "MD5";
static MessageDigest digestFunction = null;

static {
try {
digestFunction = java.security.MessageDigest.getInstance(hashName);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}

FlexibleBloomFilter<T> next = null;
// translate string data to char array with below charset
Charset charset = Charset.forName("UTF-8");
private BitSet bitset = null;
private int bitSetSize = 0;
private double bitsPerElement = 8;

// expected (maximum) number of elements to be added
private int expectedElementNum;

// number of elements actually added to the Bloom filter
private int addedElementNum = 0;

// number of hash functions
private int hashFuncNum = 8;

public FlexibleBloomFilter(double bitsPerElement, int expectedElementNum, int hashFuncNum) {
this.expectedElementNum = expectedElementNum;
this.hashFuncNum = hashFuncNum;
this.bitsPerElement = bitsPerElement;
this.bitSetSize = (int) Math.ceil(bitsPerElement * expectedElementNum);
this.bitset = new BitSet(bitSetSize);
}

// (1 - e^(-hashFuncNum * n / m)) ^ hashFuncNum
public List<Double> getFalsePositiveProbability() {
double fpp = Math.pow((1 - Math.exp(-hashFuncNum * addedElementNum / (double) bitSetSize)), hashFuncNum);

// the last filter creates a array list used to keep false positive probability for each layer's filter.
if (next == null) {
List<Double> fpps = new ArrayList<>();
fpps.add(fpp);

return fpps;
}

List<Double> fpps = next.getFalsePositiveProbability();
fpps.add(0, fpp);

return fpps;
}

public void add(T element) {

// the next layer filter will exists if current layer is full
if (next != null) {
next.add(element);

return;
}

int[] hashes = createHashes(element.toString(), hashFuncNum);

for (int hash : hashes) {
bitset.set(Math.abs(hash % bitSetSize), true);
}

addedElementNum++;

// duplicate another layer of filter if current is full
if (addedElementNum > expectedElementNum) {
next = new FlexibleBloomFilter<>(bitsPerElement, expectedElementNum, hashFuncNum);
}
}

public boolean contains(T element) {
int[] hashes = createHashes(element.toString(), hashFuncNum);

for (int hash : hashes) {
if (!bitset.get(Math.abs(hash % bitSetSize))) {
if (next == null) {
return false;
}

// check the next layer if not found at current layer.
return next.contains(element);
}
}

return true;
}

public synchronized int[] createHashes(String str, int hashes) {

// set the function synchronized in case of multi thread circumstances.

byte[] data = str.getBytes(charset);

int[] result = new int[hashes];

int k = 0;
byte salt = 0;

while (k < hashes) {
byte[] digest;

digestFunction.update(salt);

salt++;

digest = digestFunction.digest(data);

for (int i = 0; i < digest.length / 4 && k < hashes; i++) {
int h = 0;

for (int j = (i * 4); j < (i * 4) + 4; j++) {
h <<= 8;
h |= ((int) digest[j]) & 0xFF;
}

result[k] = h;
k++;
}
}

return result;
}
}

class CountableBloomFilter<T> implements Serializable {

// This is a flexible BloomFilter that support multi-layer keep data. Once the added element exceeds
// the capacity of the filter, the accuracy will drop dramatically. It is necessary to instantiate another
// filter to keep the extra data so that the filter can maintain good condition.

// This version support element deletion, but the count limit for same element is 2^16, so if there are more
// than 2^16 duplicated elements, error occurs. But you can increase the capacity by change the bitset type,
// currently the type is char, but for more large scale application, int or long will be more favorable.

// MD5 assure good enough accuracy in most circumstances.
static String hashName = "MD5";
static MessageDigest digestFunction = null;

static {
try {
digestFunction = java.security.MessageDigest.getInstance(hashName);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}

CountableBloomFilter<T> next = null;
// translate string data to char array with below charset
Charset charset = Charset.forName("UTF-8");
private char[] bitset = null;
private int bitSetSize = 0;
private double bitsPerElement = 8;

// expected (maximum) number of elements to be added
private int expectedElementNum;

// number of elements actually added to the Bloom filter
private int addedElementNum = 0;

// number of hash functions
private int hashFuncNum = 8;

public CountableBloomFilter(double bitsPerElement, int expectedElementNum, int hashFuncNum) {
this.expectedElementNum = expectedElementNum;
this.hashFuncNum = hashFuncNum;
this.bitsPerElement = bitsPerElement;
this.bitSetSize = (int) Math.ceil(bitsPerElement * expectedElementNum);
this.bitset = new char[bitSetSize];
}

// (1 - e^(-hashFuncNum * n / m)) ^ hashFuncNum
public List<Double> getFalsePositiveProbability() {
double fpp = Math.pow((1 - Math.exp(-hashFuncNum * addedElementNum / (double) bitSetSize)), hashFuncNum);

// the last filter creates a array list used to keep false positive probability for each layer's filter.
if (next == null) {
List<Double> fpps = new ArrayList<>();
fpps.add(fpp);

return fpps;
}

List<Double> fpps = next.getFalsePositiveProbability();
fpps.add(0, fpp);

return fpps;
}

public void add(T element) {
// the next layer filter will exists if current layer is full
if (next != null) {
next.add(element);

return;
}

int[] hashes = createHashes(element.toString(), hashFuncNum);

for (int hash : hashes) {
bitset[Math.abs(hash % bitSetSize)]++;
}

addedElementNum++;

// duplicate another layer of filter if current is full
if (addedElementNum > expectedElementNum) {
next = new CountableBloomFilter<>(bitsPerElement, expectedElementNum, hashFuncNum);
}
}

public void remove(T element) {

// the duplicate element may exists in several layers, you cannot walk through every layer
// and delete all of them. Instead, if you find them in certain layer, delete it then return,
// rather than dig down.

if (currentLayerContains(element)) {
int[] hashes = createHashes(element.toString(), hashFuncNum);

for (int hash : hashes) {
bitset[Math.abs(hash % bitSetSize)]--;
}

addedElementNum--;
}
// check out if the given element lies in the next layer
else if (next != null) {
next.remove(element);
}
}

private boolean currentLayerContains(T element) {
int[] hashes = createHashes(element.toString(), hashFuncNum);

for (int hash : hashes) {
if (bitset[Math.abs(hash % bitSetSize)] <= 0) {
return false;
}
}

return true;
}

public boolean contains(T element) {
int[] hashes = createHashes(element.toString(), hashFuncNum);

for (int hash : hashes) {
if (bitset[Math.abs(hash % bitSetSize)] <= 0) {
if (next == null) {
return false;
}

// check the next layer if not found at current layer.
return next.contains(element);
}
}

return true;
}

public synchronized int[] createHashes(String str, int hashes) {

// set the function synchronized in case of multi thread circumstances.

byte[] data = str.getBytes(charset);

int[] result = new int[hashes];

int k = 0;
byte salt = 0;

while (k < hashes) {
byte[] digest;

digestFunction.update(salt);

salt++;

digest = digestFunction.digest(data);

for (int i = 0; i < digest.length / 4 && k < hashes; i++) {
int h = 0;

for (int j = (i * 4); j < (i * 4) + 4; j++) {
h <<= 8;
h |= ((int) digest[j]) & 0xFF;
}

result[k] = h;
k++;
}
}

return result;
}
}