Giter Club home page Giter Club logo

bplustree's Introduction

Bplustree

image

image

An on-disk B+tree for Python 3.

It feels like a dict, but stored on disk. When to use it?

  • When the data to store does not fit in memory
  • When the data needs to be persisted
  • When keeping the keys in order is important

This project is under development: the format of the file may change between versions. Do not use as your primary source of data.

Quickstart

Install Bplustree with pip:

pip install bplustree

Create a B+tree index stored on a file and use it with:

>>> from bplustree import BPlusTree
>>> tree = BPlusTree('/tmp/bplustree.db', order=50)
>>> tree[1] = b'foo'
>>> tree[2] = b'bar'
>>> tree[1]
b'foo'
>>> tree.get(3)
>>> tree.close()

Keys and values

Keys must have a natural order and must be serializable to bytes. Some default serializers for the most common types are provided. For example to index UUIDs:

>>> import uuid
>>> from bplustree import BPlusTree, UUIDSerializer
>>> tree = BPlusTree('/tmp/bplustree.db', serializer=UUIDSerializer(), key_size=16)
>>> tree.insert(uuid.uuid1(), b'foo')
>>> list(tree.keys())
[UUID('48f2553c-de23-4d20-95bf-6972a89f3bc0')]

Values on the other hand are always bytes. They can be of arbitrary length, the parameter value_size=128 defines the upper bound of value sizes that can be stored in the tree itself. Values exceeding this limit are stored in overflow pages. Each overflowing value occupies at least a full page.

Iterating

Since keys are kept in order, it is very efficient to retrieve elements in order:

>>> for i in tree:
...     print(i)
...
1
2
>>> for key, value in tree.items():
...     print(key, value)
...
1 b'foo'
2 b'bar'

It is also possible to iterate over a subset of the tree by giving a Python slice:

>>> for key, value in tree.items(slice(start=0, stop=10)):
...     print(key, value)
...
1 b'foo'
2 b'bar'

Both methods use a generator so they don't require loading the whole content in memory, but copying a slice of the tree into a dict is also possible:

>>> tree[0:10]
{1: b'foo', 2: b'bar'}

Concurrency

The tree is thread-safe, it follows the multiple readers/single writer pattern.

It is safe to:

  • Share an instance of a BPlusTree between multiple threads

It is NOT safe to:

  • Share an instance of a BPlusTree between multiple processes
  • Create multiple instances of BPlusTree pointing to the same file

Durability

A write-ahead log (WAL) is used to ensure that the data is safe. All changes made to the tree are appended to the WAL and only merged into the tree in an operation called a checkpoint, usually when the tree is closed. This approach is heavily inspired by other databases like SQLite.

If tree doesn't get closed properly (power outage, process killed...) the WAL file is merged the next time the tree is opened.

Performances

Like any database, there are many knobs to finely tune the engine and get the best performance out of it:

  • order, or branching factor, defines how many entries each node will hold
  • page_size is the amount of bytes allocated to a node and the length of read and write operations. It is best to keep it close to the block size of the disk
  • cache_size to keep frequently used nodes at hand. Big caches prevent the expensive operation of creating Python objects from raw pages but use more memory

Some advices to efficiently use the tree:

  • Insert elements in ascending order if possible, prefer UUID v1 to UUID v4
  • Insert in batch with tree.batch_insert(iterator) instead of using tree.insert() in a loop
  • Let the tree iterate for you instead of using tree.get() in a loop
  • Use tree.checkpoint() from time to time if you insert a lot, this will prevent the WAL from growing unbounded
  • Use small keys and values, set their limit and overflow values accordingly
  • Store the file and WAL on a fast disk

License

MIT

bplustree's People

Contributors

bwangelme avatar cosmosatlas avatar nicolaslm avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

bplustree's Issues

os.open(directory, os.O_RDONLY) - [Errno 13] Permission denied

I have this line in my code:

tree = BPlusTree(file_path,
            serializer=StrSerializer(),
            order=cfg.B_TREE_ORDER,
            page_size=cfg.B_TREE_PAGE_SIZE,
            value_size=cfg.B_TREE_VALUE_SIZE,
            key_size=cfg.B_TREE_KEY_SIZE)

On Windows 7 x64 the above line generates the following error when file_path is C:\\Users\\yuri\\db\\tree1.db:

  File "C:\Users\yuri\AppData\Roaming\Python\Python36\site-packages\bplustree-0.0.2.dev1-py3.6.egg\bplustree\tree.py", line 34, in __init__
  File "C:\Users\yuri\AppData\Roaming\Python\Python36\site-packages\bplustree-0.0.2.dev1-py3.6.egg\bplustree\memory.py", line 84, in __init__
  File "C:\Users\yuri\AppData\Roaming\Python\Python36\site-packages\bplustree-0.0.2.dev1-py3.6.egg\bplustree\memory.py", line 38, in open_file_in_dir
PermissionError: [Errno 13] Permission denied: 'C:\\Users\\yuri\\db'

I never got this error on Linux.

The problem is in bplustree/memory.py, line 38:

dir_fd = os.open(directory, os.O_RDONLY)

Windows seems to have an issue with the flag os.O_RDONLY being used on directory paths (maybe only works on files).

a little thing but not bug in the code

Hi.I've been learning bplusTree recently and I found your code which has been great help for me.Thank you. But I met some problem today in the Node's dump() function。I list some lines below.
1 data = (
2 used_key_length.to_bytes(USED_VALUE_LENGTH_BYTES, ENDIAN) +
3 key_as_bytes +
4 bytes(self._tree_conf.key_size - used_key_length) +
5 used_value_length.to_bytes(USED_VALUE_LENGTH_BYTES, ENDIAN) +
6 value +
7 bytes(self._tree_conf.value_size - used_value_length) +
8 overflow_page.to_bytes(PAGE_REFERENCE_BYTES, ENDIAN)
9 )
you see, the to_bytes() has pointed out the length for representing the int(key_as_bytes), which means whatever the key is , it will cost fixed bytes(USED_VALUE_LENGTH_BYTES = 8), so i wonder that if the variant-> used_key_length is necessary or not. Maybe this is about overflow? i'm not sure about that.Hope for you reply : )thank you.

TypeError: '<' not supported between instances of 'int' and 'bytes'

Hello

I get the following error trying to insert to the B+Tree:
TypeError: '<' not supported between instances of 'int' and 'bytes'

The command is the following:
tree.insert(bytes(enVal, encoding='utf8'), bytes(val,encoding='utf8'))

enVal and val are strings.

What am I doing wrong?

Is there some problem with the write_to_file method?

The write_to_file method is as follows:

def write_to_file(file_fd: io.FileIO, dir_fileno: Optional[int],
                  data: bytes, fsync: bool=True):
    length_to_write = len(data)
    written = 0
    while written < length_to_write:
        written = file_fd.write(data[written:])
    if fsync:
        fsync_file_and_dir(file_fd.fileno(), dir_fileno)

I think the line 6 written = file_fd.write(data[written:]) should be changed to written += file_fd.write(data[written:]). If not, it will enter an endless loop.

At last, I write a unittest for write_to_file by mock the file_fd.write, as shown below:

def test_write_to_file():
    def side_effect(*args, **kwargs):
        if len(args) == 1:
            data = args[0]
        if len(data) > 5:
            return 5
        else:
            return len(data)

    mock_fd = mock.MagicMock()
    mock_fd.write.side_effect = side_effect

    write_to_file(mock_fd, None, b'abcdefg')

Inside the DB

managed to create the DB file and I opened the binary file using Neo Viewer. I can see the texts inserted but where are the keys stored and how the keys used to get the text inside the DB. Where are the addresses of the text stored and mapped to keys

DeprecationWarning: generator 'BPlusTree._iter_slice' raised StopIteration

/usr/local/lib/python3.6/site-packages/bplustree/tree.py:236: DeprecationWarning: generator 'BPlusTree._iter_slice' raised StopIteration
  for record in self._iter_slice(slice_):

In tree.py:303, we use raise StopIteration() to mark termination of the generator. It is now deprecated in Python 3.5 by PEP 479. Please use return instead, if you would like to work solely above 3.5.

ImportError: cannot import name 'StrSerializer'

After installing bplustree using pip (pip install --user bplustree), I get the following error when importing the class StrSerializer:

  from bplustree import BPlusTree, StrSerializer
ImportError: cannot import name 'StrSerializer'

The error does not occur when I install bplustree using python3 setup.py install --user.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.