Adam Matan Adam Matan - 9 months ago 22
Python Question

Serializing and deserializing and Python RTree

I have been trying to debug some strange behaviour in a software package that uses Pythons RTree version 0.8.2.

In order to trace the problem, I need to serialize the RTree instance every few minutes, and when the problem happens I can have a pretty accurate snapshot of the RTree.

I am using the following code for the dump:

def _dump_tree(self, filename, tree):
try:
dump_file = Rtree(filename)
for item in tree.intersection(tree.bounds, objects=True):
dump_file.insert(item.id, item.bbox, item.object)
except RTreeError:
pass


This function takes the RTree and copies it to a new RTree with a given filename.

Every invocation creates the following pairs:

2015-10-01---14-21-16_items.dat
2015-10-01---14-21-16_items.idx
...


How do I deserialize the
dat
/
idx
pairs back to Python objects?

Answer

Just open the RTree from the same filename:

>>> from rtree import index
>>> idx = index.Index('2015-10-01---14-21-16_items')
>>> idx.count(idx.bounds)
42 # The number of items you had in the original tree