-
Notifications
You must be signed in to change notification settings - Fork 0
/
B+tree.cpp
515 lines (415 loc) · 15.1 KB
/
B+tree.cpp
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
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
#include "B+tree.hpp"
//Config parameters
#define CONFIG_FILE "./bplustree.config"
#define SESSION_FILE "./.tree.session"
// Constants
#define TREE_PREFIX "leaves/leaf_"
#define OBJECT_FILE "objects/objectFile"
#define DEFAULT_LOCATION -1
//#define DEBUG_NORMAL
#include <sys/types.h>
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstring>
#include <fstream>
#include <iostream>
#include <memory>
#include <queue>
#include <vector>
#include <list>
using std::list;
using std::sort;
using std::vector;
using std::queue;
long TreeNode::lowerBound = 0;
long TreeNode::upperBound = 0;
long TreeNode::pageSize = 0;
long TreeNode::fileCount = 0;
TreeNode *bRoot = nullptr;
//Initialize a B+ Tree
TreeNode::TreeNode(){
//Initially all the fileNames are DEFAULT_LOCATION
parentIndex = DEFAULT_LOCATION;
nextLeafIndex = DEFAULT_LOCATION;
previousLeafIndex = DEFAULT_LOCATION;
// Initially every node is a leaf
leaf = true;
// Exit if the lowerBoundKey is not defined
if (lowerBound == 0) {
cout << "LowerKeyBound not defined";
exit(1);
}
// LeafNode properties
fileIndex = ++fileCount;
}
TreeNode::TreeNode(long _fileIndex) {
// Exit if the lowerBoundKey is not defined
if (lowerBound == 0) {
cout << "LowerKeyBound not defined";
exit(1);
}
// Load the current node from disk
fileIndex = _fileIndex;
readFromDisk();
}
void TreeNode::initialize() {
// Set page size
ifstream configFile;
configFile.open(CONFIG_FILE);
configFile >> pageSize;
// Save some place in the file for the header
long headerSize = sizeof(fileIndex)
+ sizeof(leaf)
+ sizeof(parentIndex)
+ sizeof(nextLeafIndex)
+ sizeof(previousLeafIndex);
pageSize = pageSize - headerSize;
// Compute parameters
long nodeSize = sizeof(fileIndex);
long keySize = sizeof(keyType);
lowerBound = floor((pageSize - nodeSize) / (2 * (keySize + nodeSize)));
upperBound = 2 * lowerBound;
pageSize = pageSize + headerSize;
}
//Check where the given key fits in the Keys vector.
long TreeNode::getKeyPosition(double key) {
// If keys are empty, return
if (keys.size() == 0 || key <= keys.front()) {
return 0;
}
for (long i = 1; i < (long)keys.size(); ++i) {
if (keys[i -1] < key && key <= keys[i]) {
return i;
}
}
return keys.size();
}
//Write to disk, information of all the files.
void TreeNode::commitToDisk() {
// Create a character buffer which will be written to disk
long location = 0;
char buffer[pageSize];
memcpy(buffer + location, &fileIndex, sizeof(fileIndex)); // Store the fileIndex
location += sizeof(fileIndex);
memcpy(buffer + location, &leaf, sizeof(leaf)); // Add the leaf to memory
location += sizeof(leaf);
memcpy(buffer + location, &parentIndex, sizeof(parentIndex)); // Add parent to memory
location += sizeof(parentIndex);
memcpy(buffer + location, &previousLeafIndex, sizeof(nextLeafIndex)); // Add the previous leaf node
location += sizeof(nextLeafIndex);
memcpy(buffer + location, &nextLeafIndex, sizeof(nextLeafIndex)); // Add the next leaf node
location += sizeof(nextLeafIndex);
long numKeys = keys.size(); // Store the number of keys
memcpy(buffer + location, &numKeys, sizeof(numKeys));
location += sizeof(numKeys);
// Add the keys to memory
for (auto key : keys) {
memcpy(buffer + location, &key, sizeof(key));
location += sizeof(key);
}
// Add the child pointers to memory
if (!leaf) {
for (auto childIndex : childIndices) {
memcpy(buffer + location, &childIndex, sizeof(childIndex));
location += sizeof(childIndex);
}
} else {
for (auto objectPointer : objectPointers) {
memcpy(buffer + location, &objectPointer, sizeof(objectPointer));
location += sizeof(objectPointer);
}
}
// Create a binary file and write to memory
ofstream nodeFile;
nodeFile.open(getFileName(), ios::binary|ios::out);
nodeFile.write(buffer, pageSize);
nodeFile.close();
}
void TreeNode::readFromDisk() {
// Create a character buffer which will be written to disk
long location = 0;
char buffer[pageSize];
// Open the binary file ane read into memory
ifstream nodeFile;
nodeFile.open(getFileName(), ios::binary|ios::in);
nodeFile.read(buffer, pageSize);
nodeFile.close();
memcpy((char *) &fileIndex, buffer + location, sizeof(fileIndex)); // Retrieve the fileIndex
location += sizeof(fileIndex);
memcpy((char *) &leaf, buffer + location, sizeof(leaf)); // Retreive the type of node
location += sizeof(leaf);
memcpy((char *) &parentIndex, buffer + location, sizeof(parentIndex)); // Retrieve the parentIndex
location += sizeof(parentIndex);
memcpy((char *) &previousLeafIndex, buffer + location, sizeof(previousLeafIndex)); // Retrieve the previousLeafIndex
location += sizeof(previousLeafIndex);
memcpy((char *) &nextLeafIndex, buffer + location, sizeof(nextLeafIndex)); // Retrieve the nextLeafIndex
location += sizeof(nextLeafIndex);
long numKeys;
memcpy((char *) &numKeys, buffer + location, sizeof(numKeys)); // Retrieve the number of keys
location += sizeof(numKeys);
// Retrieve the keys
keys.clear();
double key;
for (long i = 0; i < numKeys; ++i) {
memcpy((char *) &key, buffer + location, sizeof(key));
location += sizeof(key);
keys.push_back(key);
}
// Retrieve childPointers
if (!leaf) {
childIndices.clear();
long childIndex;
for (long i = 0; i < numKeys + 1; ++i) {
memcpy((char *) &childIndex, buffer + location, sizeof(childIndex));
location += sizeof(childIndex);
childIndices.push_back(childIndex);
}
} else {
objectPointers.clear();
long objectPointer;
for (long i = 0; i < numKeys; ++i) {
memcpy((char *) &objectPointer, buffer + location, sizeof(objectPointer));
location += sizeof(objectPointer);
objectPointers.push_back(objectPointer);
}
}
}
//Helper for object Insertion
void TreeNode::insertObject(FileObject object) {
long position = getKeyPosition(object.getKey());
// insert the new key to keys
keys.insert(keys.begin() + position, object.getKey());
// insert the object pointer to the end
objectPointers.insert(objectPointers.begin() + position, object.getFileIndex());
// Commit the new node back into memory
commitToDisk();
}
//Split a node if it is full
void TreeNode::splitInternal() {
//Create a surrogate internal node
TreeNode *surrogateInternalNode = new TreeNode();
surrogateInternalNode->setToInternalNode();
//Fix the keys of the new node
double startPoint = *(keys.begin() + lowerBound);
for (auto key = keys.begin() + lowerBound + 1; key != keys.end(); ++key) {
surrogateInternalNode->keys.push_back(*key);
}
//Resize the keys of the current node
keys.resize(lowerBound);
//Partition children for the surrogateInternalNode
for (auto childIndex = childIndices.begin() + lowerBound + 1; childIndex != childIndices.end(); ++childIndex) {
surrogateInternalNode->childIndices.push_back(*childIndex);
//Assign parent to the children nodes
TreeNode *tempChildNode = new TreeNode(*childIndex);
tempChildNode->parentIndex = surrogateInternalNode->fileIndex;
tempChildNode->commitToDisk();
delete tempChildNode;
}
//Fix children for the current node
childIndices.resize(lowerBound + 1);
//If the current node is not a root node
if (parentIndex != DEFAULT_LOCATION) {
//Assign parents
surrogateInternalNode->parentIndex = parentIndex;
surrogateInternalNode->commitToDisk();
commitToDisk();
//Now we push up the splitting one level
TreeNode *tempParent = new TreeNode(parentIndex);
tempParent->insertNode(startPoint, fileIndex, surrogateInternalNode->fileIndex);
delete tempParent;
} else {
//Create a new parent node
TreeNode *newParent = new TreeNode();
newParent->setToInternalNode();
//Assign parents
surrogateInternalNode->parentIndex = newParent->fileIndex;
parentIndex = newParent->fileIndex;
//Insert the key into the keys
newParent->keys.push_back(startPoint);
//Insert the children
newParent->childIndices.push_back(fileIndex);
newParent->childIndices.push_back(surrogateInternalNode->fileIndex);
// Commit changes to disk
newParent->commitToDisk();
commitToDisk();
surrogateInternalNode->commitToDisk();
// Clean up the previous root node
delete bRoot;
// Reset the root node
bRoot = newParent;
}
// Clean the surrogateInternalNode
delete surrogateInternalNode;
}
void TreeNode::serialize() {
//Return if node is empty
if (keys.size() == 0) {
return;
}
queue< pair<long, char> > previousLevel;
previousLevel.push(make_pair(fileIndex, 'N'));
long currentIndex;
TreeNode *iterator;
char type;
while (!previousLevel.empty()) {
queue< pair<long, char> > nextLevel;
while (!previousLevel.empty()) {
//Get the front and pop
currentIndex = previousLevel.front().first;
iterator = new TreeNode(currentIndex);
type = previousLevel.front().second;
previousLevel.pop();
//If it a seperator, print and move ahead
if (type == '|') {
cout << "|| ";
continue;
}
//Print all the keys
for (auto key : iterator->keys) {
cout << key << " ";
}
// Enqueue all the children
for (auto childIndex : iterator->childIndices) {
nextLevel.push(make_pair(childIndex, 'N'));
// Insert a marker to indicate end of child
nextLevel.push(make_pair(DEFAULT_LOCATION, '|'));
}
// Delete allocated memory
delete iterator;
}
// Seperate different levels
cout << endl << endl;
previousLevel = nextLevel;
}
}
void TreeNode::insertNode(double key, long leftChildIndex, long rightChildIndex) {
// insert the new key to keys
long position = getKeyPosition(key);
keys.insert(keys.begin() + position, key);
// insert the newChild
childIndices.insert(childIndices.begin() + position + 1, rightChildIndex);
// commit changes to disk
commitToDisk();
// If this overflows, we move again upward
if ((long)keys.size() > upperBound) {
splitInternal();
}
// Update the root if the element was inserted in the root
if (fileIndex == bRoot->getFileIndex()) {
bRoot->readFromDisk();
}
}
void TreeNode::splitLeaf() {
// Create a surrogate leaf node with the keys and object Pointers
TreeNode *surrogateLeafNode = new TreeNode();
for (long i = lowerBound; i < (long) keys.size(); ++i) {
FileObject object = FileObject(keys[i], objectPointers[i]);
surrogateLeafNode->insertObject(object);
}
// Resize the current leaf node and commit the node to disk
keys.resize(lowerBound);
objectPointers.resize(lowerBound);
// Link up the leaves
long tempLeafIndex = nextLeafIndex;
nextLeafIndex = surrogateLeafNode->fileIndex;
surrogateLeafNode->nextLeafIndex = tempLeafIndex;
// If the tempLeafIndex is not null we have to load it and set its
// previous index
if (tempLeafIndex != DEFAULT_LOCATION) {
TreeNode *tempLeaf = new TreeNode(tempLeafIndex);
tempLeaf->previousLeafIndex = surrogateLeafNode->fileIndex;
tempLeaf->commitToDisk();
delete tempLeaf;
}
surrogateLeafNode->previousLeafIndex = fileIndex;
// Consider the case when the current node is not a root
if (parentIndex != DEFAULT_LOCATION) {
// Assign parents
surrogateLeafNode->parentIndex = parentIndex;
surrogateLeafNode->commitToDisk();
commitToDisk();
// Now we push up the splitting one level
TreeNode *tempParent = new TreeNode(parentIndex);
tempParent->insertNode(surrogateLeafNode->keys.front(), fileIndex, surrogateLeafNode->fileIndex);
delete tempParent;
} else {
// Create a new parent node
TreeNode *newParent = new TreeNode();
newParent->setToInternalNode();
// Assign parents
surrogateLeafNode->parentIndex = newParent->fileIndex;
parentIndex = newParent->fileIndex;
// Insert the key into the keys
newParent->keys.push_back(surrogateLeafNode->keys.front());
// Insert the children
newParent->childIndices.push_back(this->fileIndex);
newParent->childIndices.push_back(surrogateLeafNode->fileIndex);
// Commit to disk
newParent->commitToDisk();
surrogateLeafNode->commitToDisk();
commitToDisk();
// Clean up the root node
delete bRoot;
// Reset the root node
bRoot = newParent;
}
// Clean up surrogateNode
delete surrogateLeafNode;
}
void insert(TreeNode *root, FileObject object) {
//If the root is a leaf, we can directly insert
if (root->isLeaf()) {
//Insert object
root->insertObject(object);
//Split if required
if (root->size() > root->upperBound) {
root->splitLeaf();
}
} else {
//We traverse the tree
long position = root->getKeyPosition(object.getKey());
//Load the node from disk
TreeNode *nextRoot = new TreeNode(root->childIndices[position]);
//Recurse into the node
insert(nextRoot, object);
//Clean up
delete nextRoot;
}
}
//Point search in a BPlusTree
void pointQuery(TreeNode *root, double searchKey) {
//If the root is a leaf, we can directly search
if (root->isLeaf()) {
//Print all nodes in the current leaf
for (long i = 0; i < (long) root->keys.size(); ++i) {
if (root->keys[i] == searchKey) {
#ifdef DEBUG_NORMAL
cout << root->keys[i] << " ";
#endif
#ifdef OUTPUT
cout << FileObject(root->keys[i], root->objectPointers[i]).getDataString() << endl;
#endif
}
}
//Check nextleaf for same node
if (root->nextLeafIndex != DEFAULT_LOCATION) {
//Load up the nextLeaf from disk
TreeNode *tempNode = new TreeNode(root->nextLeafIndex);
//Check in the nextLeaf and delegate
if (tempNode->keys.front() == searchKey) {
pointQuery(tempNode, searchKey);
}
delete tempNode;
}
} else {
//We traverse the tree
long position = root->getKeyPosition(searchKey);
//Load the node from disk
TreeNode *nextRoot = new TreeNode(root->childIndices[position]);
//Recurse into the node
pointQuery(nextRoot, searchKey);
//Clean up
delete nextRoot;
}
}