6

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]
3
  • The Rtree documentation appears to use dumps and loads, which writes the index as a string Commented Sep 8, 2017 at 20:58
  • 1
    I think the dumps and loads are just for serializing Python objects for storage in the index. I don't think you can pickle the index object since it's just a ctypes wrapper around libspatialindex. Commented Sep 8, 2017 at 22:00
  • @marc-pfister I did this on a test index, and the shape of the index seems to have changed. The original index I used had two index nodes each with leaves. I "saved" this to file using your insert method, and reloaded it, but the new index has just one index node with all the leaves in that. Commented Jun 18, 2018 at 14:04

1 Answer 1

8

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]
1
  • I've tried to implement this approach, but I'm seeing the same issue as the OP. Commented Aug 7, 2022 at 21:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.