[GIS] Saving python Rtree spatial index to file

pythonpython-2.7rtree

I would like to save an Rtree spatial index to file. I tried using pickle.dump, but when I loaded the .p file using pickle.load, the bounds were way off. Here's an example:

import rtree, pickle
from rtree import index
iidx=index.Index()
iidx.add(0,(1,2,3,4))
f=open('rtree2.p','wb')
pickle.dump(iidx,f)
f.close()

When I try opening the file:

f=open('rtree2.p','rb')
uudx=pickle.load(f)
f.close()
uudx.get_bounds()

I get:

[1.7976931348623157e+308, 1.7976931348623157e+308, -1.7976931348623157e+308, -1.7976931348623157e+308]

Best Answer

Is the built-in disk serialization an acceptable solution?

Make an index and flush it to disk:

from rtree.index import Index
idx = Index('filename')
idx.insert(0, (1, 2, 3, 4))
idx.get_bounds()
# [1.0, 2.0, 3.0, 4.0]
idx.close()

Load the index at a later point in time:

from rtree.index import Index
idx = Index('filename')
idx.get_bounds()
# [1.0, 2.0, 3.0, 4.0]
Related Question