CatgirlIntelligenceAgency/code/libraries/btree/readme.md

47 lines
1.8 KiB
Markdown
Raw Normal View History

2023-03-04 17:21:13 +01:00
# BTree
2023-03-20 16:39:15 +01:00
This package contains a small library for creating and reading a static b-tree in as implicit pointer-less datastructure.
Both binary indices (i.e. sets) are supported, as well as arbitrary multiple-of-keysize key-value mappings where the data is
interlaced with the keys in the leaf nodes. This is a fairly low-level datastructure.
2023-03-04 17:21:13 +01:00
The b-trees are specified through a [BTreeContext](src/main/java/nu/marginalia/btree/model/BTreeContext.java)
which contains information about the data and index layout.
2023-03-04 17:57:17 +01:00
The b-trees are written through a [BTreeWriter](src/main/java/nu/marginalia/btree/BTreeWriter.java) and
read with a [BTreeReader](src/main/java/nu/marginalia/btree/BTreeReader.java).
2023-03-04 17:21:13 +01:00
## Demo
```java
BTreeContext ctx = new BTreeContext(
4, // num layers max
2023-03-20 16:39:15 +01:00
1, // entry size, 1 = the leaf node has just just the key
2023-03-05 11:27:56 +01:00
BTreeBlockSize.BS_4096); // page size
2023-03-04 17:21:13 +01:00
2023-03-04 17:21:39 +01:00
// Allocate a memory area to work in, see the array library for how to do this with files
LongArray array = LongArray.allocate(8192);
2023-03-04 17:21:13 +01:00
2023-03-04 17:21:39 +01:00
// Write a btree at offset 123 in the area
long[] items = new long[400];
BTreeWriter writer = new BTreeWriter(array, ctx);
final int offsetInFile = 123;
2023-03-04 17:21:13 +01:00
2023-03-04 17:21:39 +01:00
long btreeSize = writer.write(offsetInFile, items.length, slice -> {
2023-03-04 17:57:17 +01:00
// here we *must* write items.length * entry.size words in slice
2023-03-04 17:21:39 +01:00
// these items must be sorted!!
2023-03-04 17:21:13 +01:00
2023-03-04 17:21:39 +01:00
for (int i = 0; i < items.length; i++) {
slice.set(i, items[i]);
}
});
2023-03-04 17:21:13 +01:00
2023-03-04 17:21:39 +01:00
// Read the BTree
2023-03-04 17:21:13 +01:00
2023-03-04 17:21:39 +01:00
BTreeReader reader = new BTreeReader(array, ctx, offsetInFile);
reader.findEntry(items[0]);
2023-03-20 16:39:15 +01:00
```
## Useful Resources
Youtube: [Abdul Bari, 10.2 B Trees and B+ Trees. How they are useful in Databases](https://www.youtube.com/watch?v=aZjYr87r1b8). This isn't exactly the design implemented in this library, but very well presented and a good refresher.